ostrya 0.2.1

Pure-Rust async reimplementation of the ostree repository library
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
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
//! The in-process OpenPGP signature engine: it answers the cryptographic
//! question a stored signature blob asks and reports what the certificate and
//! the signature packet state about it.
//!
//! [`verify_signatures`] takes the certificates a [`GpgVerifier`](super::GpgVerifier)
//! loaded, the signed payload, and the `aay` blobs stored under
//! `ostree.gpgsigs`, and reports one [`SignatureInfo`] per signature packet.
//! One blob holds one or more signature packets, so a blob can contribute
//! several records; a blob the parser reads no signature out of contributes
//! one record of its own, so the record count follows the stored blob count.
//!
//! Each signature names its issuer in a subpacket. Resolution reads the issuer
//! fingerprint first and the issuer key id second, and each is matched against
//! every certificate's primary key and then its subkeys. A signature whose
//! issuer no loaded certificate holds is reported with `key_missing`, and the
//! fields the report then carries -- the fingerprint, the creation time, and
//! the two algorithm names -- come out of the signature packet itself.
//!
//! Every certificate that answers for the issuer takes part in the verdict.
//! The matches are grouped by the primary key of the certificate each one came
//! from, and one group is read as one certificate: the direct signatures, the
//! user ids with their certifications, and the binding signatures over a
//! signing subkey of every copy form one set, and the key expiry rule runs
//! once over that set, so the newest statement any copy carries answers.
//! Across groups a revocation any group states refuses the signature, and the
//! key expires at the earliest instant any group states, so the load order of
//! the trusted set decides neither. The first match supplies the rest -- the
//! reported user id, the primary-key fingerprint, the cryptography, and the
//! cross-certification gate -- so the load order still decides those.
//!
//! The engine also owns the trust and validity policy: which signature classes
//! and which digest algorithms a data signature may use, when a subkey speaks
//! for its certificate, when a key has expired, and when it is revoked. A
//! signature is valid where it verifies, where the certificate that holds the
//! signing key is loaded, where the signature is over a document, where the
//! bindings hold, where the digest is allowed, where the signature's own expiry
//! has not passed, and where the key is neither expired nor revoked. A
//! self-signature whose own expiration time has passed sets no key expiry,
//! binds no subkey, and ranks no user id. Each rule below cites the `gpgv`
//! 2.4.9 behavior it reproduces, observed in an isolated `GNUPGHOME` on
//! fixtures the unit tests build.
//!
//! A stored blob is untrusted input, so it is bounded and the parse is
//! contained. One blob is held to one mebibyte, which is checked before the
//! parser sees the bytes, and to 64 signature packets, which is checked as the
//! packets are read. Each refusal names the cap it reached. The policy runs
//! inside the same containment, so a crafted certificate that drives a public-
//! key operation into a panic reads as a blob the parser rejects.

use std::io::Cursor;

use pgp::composed::{Deserializable, DetachedSignature, SignedPublicKey, SignedPublicSubKey};
use pgp::crypto::hash::HashAlgorithm;
use pgp::crypto::public_key::PublicKeyAlgorithm;
use pgp::packet::{PublicKey, Signature, SignatureType, SubpacketData};
use pgp::types::{Fingerprint, KeyDetails, SignedUser, Tag, Timestamp};

use crate::error::{Error, Result};
use crate::sign::{SignatureInfo, VerifyOutcome};

/// The ceiling on one stored signature blob, whose whole content is parsed in
/// memory. One detached signature is a few hundred bytes, so a mebibyte holds
/// thousands of them.
const MAX_SIGNATURE_BLOB: usize = 1024 * 1024;
/// The ceiling on the signature packets one blob may hold. A commit carries a
/// handful of signatures, and the ceiling bounds the work a blob out of a
/// pulled commit's detached metadata can ask the parser and the public-key
/// operations for.
const MAX_SIGNATURE_PACKETS: usize = 64;

/// Report on each signature `blobs` holds, over `payload`, against the
/// certificates `certs` holds.
///
/// [`VerifyOutcome::valid`] is the OR over the per-signature flags, so one
/// valid signature among several makes the outcome valid.
///
/// The work is public-key cryptography over untrusted input and belongs on the
/// blocking pool, which is where
/// [`Verifier::verify`](crate::sign::Verifier::verify) for
/// [`GpgVerifier`](super::GpgVerifier) calls it.
pub(super) fn verify_signatures(
    certs: &[SignedPublicKey],
    payload: &[u8],
    blobs: &[Vec<u8>],
) -> Result<VerifyOutcome> {
    let mut outcome = VerifyOutcome::default();
    for (index, blob) in blobs.iter().enumerate() {
        let infos = verify_blob(certs, payload, blob, &format!("the signature blob {index}"))?;
        if infos.is_empty() {
            outcome.signatures.push(SignatureInfo::default());
        } else {
            for info in infos {
                outcome.valid |= info.valid;
                outcome.signatures.push(info);
            }
        }
    }
    Ok(outcome)
}

/// Report on each signature one blob holds. `subject` names the blob, so a
/// refusal states which blob reached which cap.
///
/// A blob is untrusted input, so the parse and the public-key operations run
/// inside [`std::panic::catch_unwind`] and a caught panic reads as a blob the
/// parser rejects. Two limits hold: `catch_unwind` catches nothing where the
/// final binary is built with `panic = "abort"`, and it says nothing about a
/// parser that returns a wrong answer without panicking.
fn verify_blob(
    certs: &[SignedPublicKey],
    payload: &[u8],
    blob: &[u8],
    subject: &str,
) -> Result<Vec<SignatureInfo>> {
    if blob.len() > MAX_SIGNATURE_BLOB {
        return Err(Error::Signature(format!(
            "{subject} is over the {MAX_SIGNATURE_BLOB}-byte ceiling"
        )));
    }
    let work = || -> Result<Vec<SignatureInfo>> {
        let mut infos: Vec<SignatureInfo> = Vec::new();
        // A blob the parser reads no whole signature packet out of reports no
        // record here, whether the packet stream refuses to open or the first
        // packet is incomplete. The caller gives such a blob one record, so the
        // record count follows the blob count.
        let Ok(signatures) = DetachedSignature::from_bytes_many(Cursor::new(blob)) else {
            return Ok(infos);
        };
        for signature in signatures {
            // The packets that were read whole keep their records, and the
            // stream stops at the first one that was not. Each packet is read
            // ahead of the cap test, so the cap refuses a blob on a packet the
            // stream carried whole. A blob that holds the cap and ends in a
            // partial packet reports the whole packets and stops there.
            let Ok(signature) = signature else { break };
            if infos.len() == MAX_SIGNATURE_PACKETS {
                return Err(Error::Signature(format!(
                    "{subject} holds more than {MAX_SIGNATURE_PACKETS} signature packets"
                )));
            }
            infos.push(describe(certs, payload, &signature));
        }
        Ok(infos)
    };
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)) {
        Ok(result) => result,
        Err(_) => Err(Error::Signature(format!(
            "{subject} is not readable as an OpenPGP signature: the parser panicked"
        ))),
    }
}

/// Report on one signature packet.
///
/// Six outcomes carry four field sets. A signature whose issuer no certificate
/// holds reports what its own packet states, with `key_missing`. A signature
/// whose class is not a document signature, one whose digest algorithm the
/// policy refuses, and one by a signing subkey the primary key did not
/// cross-certify report the same fields without `key_missing`. A signature
/// whose issuer resolved and whose cryptography failed reports the resolved
/// signing key, its certificate, and the certificate's user id, and states
/// nothing else the packet claims, since nothing else was checked. A signature
/// a resolved key verifies reports the signing key, its certificate, the
/// certificate's user id, and the validity policy's answer.
fn describe(
    certs: &[SignedPublicKey],
    payload: &[u8],
    signature: &DetachedSignature,
) -> SignatureInfo {
    let sig = &signature.signature;
    let mut info = SignatureInfo::default();
    // The issuer is resolved first, which is the order `gpgv` answers in: over
    // an MD5 data signature whose issuer no loaded keyring holds it reports
    // `ERRSIG <keyid> 1 1 00 <created> 9 <fingerprint>` and `NO_PUBKEY`, and it
    // names the digest as the cause only where the issuer resolved. No rule
    // below can make such a record valid, so a refused digest and a refused
    // class stay refused on every path.
    let Some(issuers) = resolve_issuers(certs, sig) else {
        info.key_missing = true;
        describe_packet(&mut info, sig);
        return info;
    };
    // The fields below name one key and one certificate, and the
    // cross-certification rule below reads one binding. The first match is the
    // one all of them read.
    let issuer = issuers.reported();
    // `gpgv` over a class 0x02 signature reports
    // `ERRSIG <keyid> 22 10 02 <created> 32 <fingerprint>` and no user id,
    // where a class 0x00 signature by the same key over the same payload
    // reports `GOODSIG`.
    if !is_data_signature(sig) {
        describe_packet(&mut info, sig);
        return info;
    }
    // `gpgv` over an MD5 data signature by a key its keyring holds reports
    // `ERRSIG <keyid> 22 1 00 <created> 5 <fingerprint>` and "Invalid digest
    // algorithm", so it names the signature packet's own fields and no user id.
    if !digest_allowed(sig) {
        describe_packet(&mut info, sig);
        return info;
    }
    // A signing subkey the primary key did not cross-certify signs for
    // nothing. `gpgv` over the same certificate with the back-signature
    // removed reports `ERRSIG <keyid> 22 10 00 <created> 1 <fingerprint>`,
    // "signing subkey ... is not cross-certified", and no `NO_PUBKEY`, where
    // the intact certificate reports `GOODSIG`.
    if !issuer.cross_certified() {
        describe_packet(&mut info, sig);
        return info;
    }
    let (user_name, user_email) = reported_user_id(issuer.cert);
    info.user_name = user_name;
    info.user_email = user_email;
    // The signing key the lookup resolved, and the certificate that holds it,
    // name themselves on both paths. A signature the cryptography refuses
    // therefore states which key made it, and `sign --delete` reaches it under
    // the key id or the fingerprint of either key. `ostree` 2026.1 names both
    // keys over a commit whose payload changed: a signature a subkey made
    // draws `key ID <subkey-key-id>`, the subkey's own key id, with `Primary
    // key ID <primary-key-id>` under it, and its own `gpg-sign --delete`
    // removes such a signature under either key's key id and under either
    // key's fingerprint. Each value here comes from the key the lookup
    // resolved, so a packet answers for no key of its own naming, and each is
    // a whole fingerprint even where the signature named its issuer by eight
    // bytes alone.
    info.fingerprint = Some(format!("{:X}", issuer.fingerprint()));
    info.primary_fingerprint = Some(format!("{:X}", issuer.cert.fingerprint()));
    if !issuer.verify(signature, payload) {
        return info;
    }
    info.created = created_at(sig);
    info.expires = expires_at(sig);
    info.pubkey_algorithm = pubkey_algorithm_name(sig);
    info.hash_algorithm = hash_algorithm_name(sig);
    let now = now();
    // `gpgv` reports an expired key as `EXPKEYSIG` with `KEYEXPIRED <instant>`
    // and a revoked one as `REVKEYSIG`, and it prints the `VALIDSIG` detail
    // line in both cases, so both records carry the fields above. Neither is
    // `GOODSIG`, so neither is valid. A key stands live at the instant it
    // expires and expires from the next second: polled second by second across
    // its expiry instant, `gpgv` reports `GOODSIG` through that instant and
    // `EXPKEYSIG` from the second after it.
    let key_expires = issuers.key_expires_at();
    if key_expires.is_some_and(|instant| instant < now) {
        info.expired = true;
        info.key_expires = key_expires;
    }
    info.revoked = issuers.revoked();
    // A signature past its own expiry reports `EXPSIG` and no `GOODSIG`, so it
    // is not valid, and no status keyword states more about it. The signature
    // expires at the instant it names: polled second by second across that
    // instant, `gpgv` reports `GOODSIG` through the second before it and
    // `EXPSIG` from the instant on.
    let signature_expired = info.expires.is_some_and(|instant| instant <= now);
    info.valid = !signature_expired && !info.expired && !info.revoked;
    info
}

/// Fill the fields a signature packet states about itself: the issuer
/// fingerprint it names, its creation time, and the two algorithm names. These
/// are the fields `ERRSIG` carries, and they are all a record holds where no
/// key answered for the signature.
fn describe_packet(info: &mut SignatureInfo, sig: &Signature) {
    info.fingerprint = sig.issuer_fingerprint().first().map(|f| format!("{f:X}"));
    info.created = created_at(sig);
    info.pubkey_algorithm = pubkey_algorithm_name(sig);
    info.hash_algorithm = hash_algorithm_name(sig);
}

/// Whether a signature is over a document, which is the class a stored blob
/// may hold. The two document classes are the binary one and the text one.
/// `gpgv` 2.4.9 refuses every other class: over a class 0x02 signature and over
/// a class 0x40 signature it reports "Invalid signature class" and no
/// `GOODSIG`. Such a signature covers one payload byte, so one of them would
/// otherwise answer for every payload that starts with that byte.
fn is_data_signature(sig: &Signature) -> bool {
    matches!(sig.typ(), Some(SignatureType::Binary | SignatureType::Text))
}

/// Whether a data signature's digest algorithm is allowed. MD5 is refused and
/// SHA-1 is accepted, which is what `gpgv` 2.4.9 answers on a data signature:
/// an MD5 signature reports `ERRSIG ... 5` and "Note: signatures using the MD5
/// algorithm are rejected", and a SHA-1 signature reports `GOODSIG`. The
/// policy is the port's own, because GnuPG's is configurable and moves between
/// versions, so the divergence to record is a class and not a version number.
fn digest_allowed(sig: &Signature) -> bool {
    sig.hash_alg() != Some(HashAlgorithm::Md5)
}

/// The instant the policy is evaluated against, in seconds since the Unix
/// epoch. A clock standing before the epoch reads as the epoch itself.
fn now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |since| since.as_secs())
}

/// The key a signature names as its issuer: a certificate, and the subkey of
/// it that signed where a subkey did.
#[derive(Clone, Copy)]
struct Issuer<'a> {
    cert: &'a SignedPublicKey,
    /// The subkey that signed, together with the newest binding signature the
    /// primary key made over it.
    subkey: Option<(&'a SignedPublicSubKey, &'a Signature)>,
}

impl Issuer<'_> {
    /// The signing key's own fingerprint: the subkey's where a subkey signed,
    /// and the primary key's otherwise.
    fn fingerprint(&self) -> Fingerprint {
        match self.subkey {
            Some((subkey, _)) => subkey.fingerprint(),
            None => self.cert.fingerprint(),
        }
    }

    /// Whether the signing key verifies `signature` over `payload`.
    fn verify(&self, signature: &DetachedSignature, payload: &[u8]) -> bool {
        match self.subkey {
            Some((subkey, _)) => signature.verify(subkey, payload).is_ok(),
            None => signature.verify(self.cert, payload).is_ok(),
        }
    }

    /// Whether the signing key is cross-certified: a subkey's binding
    /// signature must carry an embedded primary-key binding signature -- the
    /// back-signature -- that the subkey itself made over the primary key. A
    /// primary key that signed for itself needs none.
    ///
    /// This is the check that keeps a subkey stapled onto a trusted
    /// certificate from speaking for it. rPGP's `verify_subkey_binding` reads
    /// the binding signature alone, and the back-signature stands in a
    /// separate `verify_primary_key_binding` call over the binding's embedded
    /// signature. The requirement holds for every subkey that produced a data
    /// signature, whatever key flags its binding carries.
    fn cross_certified(&self) -> bool {
        let Some((subkey, binding)) = self.subkey else {
            return true;
        };
        binding.embedded_signature().is_some_and(|back| {
            back.verify_primary_key_binding(&subkey.key, &self.cert.primary_key)
                .is_ok()
        })
    }

    /// Whether this certificate revokes the signing key. Two revocation sites
    /// answer, each with its own reach:
    ///
    /// - a key revocation signature over the primary key revokes the whole
    ///   certificate, so every key it binds stops speaking for it, the signing
    ///   subkey included. [`key_revoked`] states which keys may make one, and
    ///   `trusted` is the set a designated revoker is resolved among;
    /// - a subkey revocation signature the primary key made over the signing
    ///   subkey revokes that subkey alone, and leaves the primary key and the
    ///   certificate's other subkeys as they stand.
    ///
    /// A certificate that answers for the issuer through a subkey is read at
    /// both sites, and one that answers through its primary key at the first.
    ///
    /// The second site admits the primary key's own signature alone. `gpg`
    /// 2.4.9 writes a designated revoker's revocation with `--desig-revoke`,
    /// which produces a key revocation over the primary key, so the observed
    /// states cover the first site and state nothing about a designated
    /// revoker at the second.
    ///
    /// A revocation is verified before it is honored. A key revocation
    /// signature another key made that no self-signature designates, and that
    /// anyone can staple onto a certificate, revokes nothing, which is what
    /// `gpgv` answers: over a certificate carrying such a packet it still
    /// reports `GOODSIG`.
    fn revoked(&self, trusted: &[SignedPublicKey]) -> bool {
        if key_revoked(self.cert, trusted) {
            return true;
        }
        let primary = &self.cert.primary_key;
        let Some((subkey, _)) = self.subkey else {
            return false;
        };
        subkey.signatures.iter().any(|sig| {
            sig.typ() == Some(SignatureType::SubkeyRevocation)
                && sig.verify_subkey_binding(primary, &subkey.key).is_ok()
        })
    }
}

/// Every key the loaded certificates hold that answers for the issuer one
/// signature names, in the order the trusted set holds them. The list is never
/// empty: it is built only where a match was found.
///
/// One key reaches the trusted set through more than one certificate on
/// ordinary paths: a repository's `<remote>.trustedkeys.gpg` beside the global
/// trusted directory, two `gpgkeypath` entries, or one keyring file holding two
/// exports of one key. The certificates need not state the same thing about the
/// key. The key state is therefore read over every match: the matches of one
/// certificate are read as one certificate (see [`Issuers::groups`]), a
/// revocation any match states refuses the signature, and the key expires at
/// the earliest instant any group states, so the load order decides neither the
/// revocation nor the expiry.
struct Issuers<'a> {
    matched: Vec<Issuer<'a>>,
    /// Every loaded certificate, which is the set a designated revoker is
    /// resolved among (see [`key_revoked`]). A revoker speaks for a
    /// certificate it stands outside of, so the whole trusted set answers
    /// here, whichever source carried each certificate: a remote's keyring,
    /// the global trusted directory, or a `gpgkeypath` entry. The `ostree`
    /// tool resolves no revoker standing in a keyring source other than the
    /// one carrying the revocation, so a load whose sources part answers
    /// differently in the two implementations and the port is the stricter one
    /// (`docs/conformance/cli-surface.md`, "P3").
    trusted: &'a [SignedPublicKey],
}

impl<'a> Issuers<'a> {
    /// The match the report's own fields come from: the signing key, its
    /// certificate, that certificate's user id, the cryptography, and
    /// [`Issuer::cross_certified`].
    ///
    /// Where the issuer fingerprint answered, every match holds the same
    /// signing key, so the reported signing-key fingerprint stands whichever
    /// match answers. The certificate around that key can differ: one
    /// certificate holds the key as its primary key where another binds it as
    /// a subkey. The reported user id, the primary-key fingerprint, and the
    /// cross-certification gate therefore follow the order of the trusted set.
    fn reported(&self) -> &Issuer<'a> {
        &self.matched[0]
    }

    /// Whether any matching certificate revokes the signing key. Each is read
    /// at the sites [`Issuer::revoked`] gives it, so a key revocation on one
    /// copy of a certificate refuses a signature another copy answers for. A
    /// revocation is permanent, so it is read over every copy on its own and
    /// no copy stands in for another.
    fn revoked(&self) -> bool {
        self.matched
            .iter()
            .any(|issuer| issuer.revoked(self.trusted))
    }

    /// The earliest instant any group states the signing key expires at. A
    /// group stating no expiry states nothing here, and does not extend a life
    /// another group bounds.
    fn key_expires_at(&self) -> Option<u64> {
        self.groups().iter().filter_map(Group::key_expires_at).min()
    }

    /// The matches read as merged certificates: one group per primary key, in
    /// load order, each holding the certificates its matches came from.
    ///
    /// Two exports of one certificate fall in one group and are read as one
    /// certificate. A certificate that holds the signing key as its primary key
    /// and one that binds it as a subkey fall in two groups, since their
    /// self-signatures verify under different primary keys.
    ///
    /// The group key is the primary key packet and not the fingerprint that
    /// names it. A fingerprint is a digest over that packet, so every producer
    /// answers the same either way, and a certificate whose fingerprint
    /// collides with another's under a broken digest stands in its own group,
    /// where the cross-group rule holds it to the earliest instant any group
    /// states.
    fn groups(&self) -> Vec<Group<'a>> {
        let mut groups: Vec<Group<'a>> = Vec::new();
        for issuer in &self.matched {
            let primary = &issuer.cert.primary_key;
            let group = match groups
                .iter_mut()
                .find(|group| group.primary_key() == primary)
            {
                Some(group) => group,
                None => {
                    groups.push(Group {
                        matched: Vec::new(),
                        copies: vec![issuer.cert],
                    });
                    groups.last_mut().expect("the group pushed above")
                }
            };
            group.matched.push(*issuer);
            if !group
                .copies
                .iter()
                .any(|cert| std::ptr::eq(*cert, issuer.cert))
            {
                group.copies.push(issuer.cert);
            }
        }
        groups
    }
}

/// The matches that came from certificates holding one primary key, read as
/// one certificate.
///
/// Every copy in a group states the same primary key, so the self-signatures of
/// every copy verify under that key and their signatures form one set. The key
/// expiry the group states is read over that set: [`key_expiry_over`] runs the
/// tiered rule of [`primary_key_lifetime`] once over the direct signatures and
/// the user ids of every copy, and a subkey's own lifetime comes from the
/// binding signature [`verified_binding`] answers with out of the bindings
/// every copy carries over it. A copy stating a lifetime the owner has
/// replaced therefore states nothing on its own, and the newest statement
/// answers.
///
/// The group holds at least one match and at least one copy: it is built from a
/// match.
struct Group<'a> {
    /// The matches, in load order.
    matched: Vec<Issuer<'a>>,
    /// The certificates those matches came from, one entry per certificate, in
    /// load order.
    copies: Vec<&'a SignedPublicKey>,
}

impl Group<'_> {
    /// The instant the group states the signing key expires at: the earliest
    /// instant its matches state, absent where none of them states one.
    fn key_expires_at(&self) -> Option<u64> {
        let primary = key_expiry_over(self.copies.iter().copied());
        self.matched
            .iter()
            .filter_map(|issuer| match issuer.subkey {
                None => primary,
                Some((subkey, _)) => earlier(primary, self.subkey_expires_at(subkey)),
            })
            .min()
    }

    /// The instant `subkey` expires at on its own terms: its creation time plus
    /// the lifetime the binding signature [`verified_binding`] answers with
    /// states, read over the bindings every copy carries for that subkey.
    fn subkey_expires_at(&self, subkey: &SignedPublicSubKey) -> Option<u64> {
        let wanted = subkey.fingerprint();
        let bindings = self
            .copies
            .iter()
            .flat_map(|cert| &cert.public_subkeys)
            .filter(|held| held.fingerprint() == wanted)
            .flat_map(|held| &held.signatures);
        let lifetime = key_lifetime(verified_binding(self.primary_key(), subkey, bindings)?)?;
        Some(u64::from(subkey.key.created_at().as_secs()) + lifetime)
    }

    /// The primary key every copy states.
    fn primary_key(&self) -> &PublicKey {
        &self.copies[0].primary_key
    }
}

/// The earlier of two instants, where an absent one states nothing.
fn earlier(one: Option<u64>, two: Option<u64>) -> Option<u64> {
    match (one, two) {
        (Some(one), Some(two)) => Some(one.min(two)),
        (one, two) => one.or(two),
    }
}

/// Resolve every key the loaded certificates hold for the issuer a signature
/// names: by issuer fingerprint first, then by issuer key id, and each over the
/// primary key before the subkeys. The matches of the first identifier that
/// answers are the whole set, so an issuer fingerprint the trusted set holds
/// keeps the issuer key id out of the answer.
///
/// A subkey answers only where the primary key made a binding signature over
/// it that [`verified_binding`] answers with. A subkey whose binding does not
/// verify -- one taken from another certificate and attached with the binding
/// it carried there -- belongs to no loaded certificate, and so does a subkey
/// whose every binding signature has itself expired. `gpgv` answers the same
/// way: it reports `ERRSIG ... 9` and `NO_PUBKEY` for a signature such a
/// subkey made.
fn resolve_issuers<'a>(certs: &'a [SignedPublicKey], sig: &Signature) -> Option<Issuers<'a>> {
    for wanted in sig.issuer_fingerprint() {
        let mut matched: Vec<Issuer<'a>> = Vec::new();
        for cert in certs {
            if &cert.fingerprint() == wanted {
                matched.push(Issuer { cert, subkey: None });
            }
            for subkey in &cert.public_subkeys {
                if &subkey.fingerprint() == wanted
                    && let Some(binding) =
                        verified_binding(&cert.primary_key, subkey, &subkey.signatures)
                {
                    matched.push(Issuer {
                        cert,
                        subkey: Some((subkey, binding)),
                    });
                }
            }
        }
        if !matched.is_empty() {
            return Some(Issuers {
                matched,
                trusted: certs,
            });
        }
    }
    for wanted in sig.issuer_key_id() {
        let mut matched: Vec<Issuer<'a>> = Vec::new();
        for cert in certs {
            if &cert.legacy_key_id() == wanted {
                matched.push(Issuer { cert, subkey: None });
            }
            for subkey in &cert.public_subkeys {
                if &subkey.legacy_key_id() == wanted
                    && let Some(binding) =
                        verified_binding(&cert.primary_key, subkey, &subkey.signatures)
                {
                    matched.push(Issuer {
                        cert,
                        subkey: Some((subkey, binding)),
                    });
                }
            }
        }
        if !matched.is_empty() {
            return Some(Issuers {
                matched,
                trusted: certs,
            });
        }
    }
    None
}

/// The newest binding signature `primary` made over `subkey` that verifies and
/// that has not itself expired, out of `signatures`.
///
/// The signatures a subkey carries are one source, and the bindings every copy
/// of one certificate carries over that subkey are another, so the caller
/// states the set the rule runs over.
///
/// A binding signature whose own expiration time has passed binds nothing, and
/// a live older binding beside it still binds. `gpgv` 2.4.9 answers the same
/// way. Over a certificate whose one binding signature carries signature
/// subpacket 3 with an instant already past, it reports
/// `ERRSIG <keyid> 22 10 00 <created> 9 <fingerprint>` and `NO_PUBKEY` for a
/// signature that subkey made, and exits 2; the same binding without
/// subpacket 3 reports `GOODSIG`. Over a certificate carrying that expired
/// binding beside the live one, it reports `GOODSIG`.
fn verified_binding<'a, I>(
    primary: &PublicKey,
    subkey: &SignedPublicSubKey,
    signatures: I,
) -> Option<&'a Signature>
where
    I: IntoIterator<Item = &'a Signature>,
{
    signatures
        .into_iter()
        .filter(|sig| {
            sig.typ() == Some(SignatureType::SubkeyBinding)
                && !signature_expired(sig)
                && sig.verify_subkey_binding(primary, &subkey.key).is_ok()
        })
        .max_by_key(|sig| created_secs(sig))
}

/// The instant the copies of one certificate state their primary key expires
/// at: the key creation time plus the lifetime [`primary_key_lifetime`] reads
/// over the union of those copies. Absent where they state no lifetime, and
/// absent over an empty set.
///
/// Every copy states one primary key, which is the key the caller grouped them
/// by, so the first copy supplies it. The verdict reads a match group through
/// this function and the keyring import reads the copies a keyring holds for
/// one key through it, so the two answer off the same signature.
pub(super) fn key_expiry_over<'a, I>(copies: I) -> Option<u64>
where
    I: IntoIterator<Item = &'a SignedPublicKey> + Clone,
{
    let primary = &copies.clone().into_iter().next()?.primary_key;
    let lifetime = primary_key_lifetime(
        primary,
        copies
            .clone()
            .into_iter()
            .flat_map(|cert| &cert.details.direct_signatures),
        copies.into_iter().flat_map(|cert| &cert.details.users),
    )?;
    Some(u64::from(primary.created_at().as_secs()) + lifetime)
}

/// The key expiration time a primary key carries, in seconds after the key
/// creation time: the newest verified direct-key self-signature of `direct`
/// that states a lifetime, and, where there is no such signature, the lifetime
/// the newest verified certification self-signature over a user id of `users`
/// states.
///
/// The two sets are the signatures of one certificate, or the signatures of
/// every copy of one certificate the trusted set holds. The tier outranks
/// recency in either set, so a direct-key self-signature answers over a
/// certification self-signature that stands newer.
///
/// A direct-key signature that states a lifetime is what `gpgv` reads.
/// Measured on a certificate carrying both a direct-key and a certification
/// self-signature, with two key-expiration-time subpackets that disagree. The
/// direct-key signature's value answers in both directions: it makes an expired
/// key live and a live key expired. It answers whether it stands older or newer
/// than the certification self-signature. A direct-key signature whose bytes
/// were altered is passed over, and so is one whose key-expiration-time
/// subpacket is absent or zero; the certification self-signature then answers.
///
/// Among the certification self-signatures the newest verified one answers on
/// its own terms, and no older one stands in for it: over a certificate whose
/// newest certification self-signature states a zero lifetime, and again over
/// one whose newest states no lifetime at all, `gpgv` reports `GOODSIG` while
/// an older certification self-signature states a lifetime already past. An
/// altered newest one is passed over, and `gpgv` then reports the expiry the
/// older one states.
///
/// A self-signature whose own expiration time has passed states no lifetime
/// (see [`key_lifetime`]). The two tiers carry that rule differently, and
/// `gpgv` 2.4.9 answers the same way in both. In the direct-key tier such a
/// signature is passed over, so the newest live one that states a lifetime
/// answers and, where every direct-key self-signature has expired, the
/// certification tier answers. Among the certification self-signatures the
/// newest one answers whether or not it has itself expired, so an expired
/// newest one leaves the tier stating nothing.
fn primary_key_lifetime<'a, D, U>(primary: &PublicKey, direct: D, users: U) -> Option<u64>
where
    D: IntoIterator<Item = &'a Signature>,
    U: IntoIterator<Item = &'a SignedUser>,
{
    let newest = direct
        .into_iter()
        .filter(|sig| sig.typ() == Some(SignatureType::Key) && sig.verify_key(primary).is_ok())
        .filter_map(|sig| Some((created_secs(sig), key_lifetime(sig)?)))
        .max_by_key(|(created, _)| *created);
    if let Some((_, lifetime)) = newest {
        return Some(lifetime);
    }
    users
        .into_iter()
        .flat_map(|user| user.signatures.iter().map(move |sig| (user, sig)))
        .filter(|(user, sig)| {
            is_certification(sig)
                && sig
                    .verify_certification(primary, Tag::UserId, &user.id)
                    .is_ok()
        })
        .max_by_key(|(_, sig)| created_secs(sig))
        .and_then(|(_, sig)| key_lifetime(sig))
}

/// Whether a signature is a certification over a user id, which is what a
/// primary key's own key expiration time rides on. A revocation over a user id
/// is a certification of another kind and states no key expiration time.
fn is_certification(sig: &Signature) -> bool {
    matches!(
        sig.typ(),
        Some(
            SignatureType::CertGeneric
                | SignatureType::CertPersona
                | SignatureType::CertCasual
                | SignatureType::CertPositive
        )
    )
}

/// The key lifetime a self-signature states, in seconds after the key creation
/// time. A zero lifetime means no expiry, so it reads as absent, as a zero
/// `gpgv` status field does.
///
/// A self-signature whose own expiration time has passed states no lifetime.
/// This is what `gpgv` 2.4.9 answers, measured over a certificate whose newest
/// certification self-signature carries signature subpacket 3 with an instant
/// already past:
///
/// - where that signature states a one-day key lifetime and an older
///   certification self-signature states ten years, `gpgv` reports `GOODSIG`,
///   so the expired signature's own statement is unread;
/// - where it states no key lifetime and an older certification self-signature
///   states one day, `gpgv` reports `GOODSIG`, so the older signature does not
///   answer in place of it.
///
/// The same holds over a direct-key self-signature. Where the one direct-key
/// self-signature of a certificate has itself expired and states ten years,
/// `gpgv` reports `EXPKEYSIG` with the instant the certification
/// self-signature's one-day lifetime names, and the same signature without
/// subpacket 3 reports `GOODSIG`. Where a live older direct-key
/// self-signature stating ten years stands beside it, `gpgv` reports
/// `GOODSIG`, so the direct-key tier reads the newest one that states a
/// lifetime and the expired one states none.
fn key_lifetime(sig: &Signature) -> Option<u64> {
    if signature_expired(sig) {
        return None;
    }
    epoch(sig.key_expiration_time()?.as_secs())
}

/// Whether a signature's own expiration time has passed. A signature expires
/// at the instant it names. This is the boundary [`describe`] measures on a
/// data signature, and signature subpacket 3 is the same field on a
/// self-signature, so one boundary answers for both. The boundary second on a
/// self-signature is itself unmeasured.
fn signature_expired(sig: &Signature) -> bool {
    expires_at(sig).is_some_and(|instant| instant <= now())
}

/// Whether a verified key revocation signature stands over `cert`'s primary
/// key, which revokes the whole certificate. Two keys may make one:
///
/// - the certificate's own primary key;
/// - a key that a verified self-signature of the certificate designates as a
///   revoker through signature subpacket 12, where `trusted` holds that
///   revoker's certificate.
///
/// The revoker's certificate must be reachable, which is what `gpgv` 2.4.9
/// answers. Measured over two keyrings holding the same bytes for the revoked
/// key, one of them holding the revoker's certificate as well: the keyring
/// without it reports `GOODSIG` and prints no `KEY_CONSIDERED` line for the
/// revoker, and the keyring with it reports `REVKEYSIG`. So `trusted` is the
/// whole loaded set, and the designation is matched against the primary key of
/// each certificate it holds.
///
/// The designation is what admits the revocation. Over a keyring holding the
/// byte-identical revocation and a primary key that carries no subpacket 12,
/// `gpgv` reports `GOODSIG`, and it reports `GOODSIG` again where the
/// revoker's certificate stands in that keyring too. A key revocation
/// signature another key made that no self-signature designates, and that
/// anyone can staple onto a certificate, therefore revokes nothing.
///
/// Every revocation is verified before it is honored: the certificate's own
/// primary key verifies one through [`Signature::verify_key`], and a
/// designated revoker verifies one over the revoked primary key through
/// [`Signature::verify_key_third_party`]. A revocation past its own
/// expiration time still revokes. The reference tool's rule for that case is
/// unmeasured, and the check here therefore reads the signature mathematics
/// alone.
///
/// The keyring import reads a certificate offered for a key the keyring
/// already holds through this function. It passes as `trusted` every
/// certificate the keyring under edit and the offered stream hold, so a
/// revocation a designated revoker made carries into a keyring where either
/// stream states the revoker.
pub(super) fn key_revoked<'a, I>(cert: &SignedPublicKey, trusted: I) -> bool
where
    I: IntoIterator<Item = &'a SignedPublicKey>,
{
    let primary = &cert.primary_key;
    let revocations: Vec<&Signature> = cert
        .details
        .revocation_signatures
        .iter()
        .filter(|sig| sig.typ() == Some(SignatureType::KeyRevocation))
        .collect();
    if revocations.is_empty() {
        return false;
    }
    if revocations
        .iter()
        .any(|sig| sig.verify_key(primary).is_ok())
    {
        return true;
    }
    let designated = designated_revokers(cert);
    if designated.is_empty() {
        return false;
    }
    trusted.into_iter().any(|revoker| {
        let fingerprint = revoker.fingerprint();
        designated
            .iter()
            .any(|named| *named == fingerprint.as_bytes())
            && revocations.iter().any(|sig| {
                sig.verify_key_third_party(primary, &revoker.primary_key)
                    .is_ok()
            })
    })
}

/// The keys a certificate designates as revokers, each as the fingerprint
/// bytes the designation names.
///
/// A designation rides on a self-signature, and only a self-signature that
/// verifies under the primary key designates: the direct-key signatures and
/// the certifications over a user id are read, each verified under the primary
/// key. A designation on a signature that does not verify designates nothing.
/// [`revocation_keys`] reads the hashed subpacket area alone, so a subpacket
/// 12 anyone can staple onto a certificate names no revoker either way.
///
/// A designation on a self-signature past its own expiration time still names
/// a revoker. The reference tool's rule for that case is unmeasured, and the
/// check here therefore reads the signature mathematics alone.
///
/// Both designation classes are read, the default one and the sensitive one.
/// The class states whether the designation is to be published.
fn designated_revokers(cert: &SignedPublicKey) -> Vec<&[u8]> {
    let primary = &cert.primary_key;
    let direct = cert
        .details
        .direct_signatures
        .iter()
        .filter(|sig| sig.typ() == Some(SignatureType::Key) && sig.verify_key(primary).is_ok());
    let certifications = cert
        .details
        .users
        .iter()
        .flat_map(|user| user.signatures.iter().map(move |sig| (user, sig)))
        .filter(|(user, sig)| {
            is_certification(sig)
                && sig
                    .verify_certification(primary, Tag::UserId, &user.id)
                    .is_ok()
        })
        .map(|(_, sig)| sig);
    direct
        .chain(certifications)
        .flat_map(revocation_keys)
        .collect()
}

/// The fingerprints the revocation-key subpackets of one signature name.
///
/// The hashed area alone is read, so a subpacket the signature does not cover
/// names no revoker. `gpgv` 2.4.9 answers the same way: over a keyring holding
/// the revocation, the revoker's certificate, and a subpacket 12 stapled into
/// the unhashed area of a self-signature that still verifies, it reports
/// `GOODSIG`. A signature may carry several of them, and each one names a key.
fn revocation_keys(sig: &Signature) -> impl Iterator<Item = &[u8]> {
    sig.config().into_iter().flat_map(|config| {
        config
            .hashed_subpackets()
            .filter_map(|packet| match &packet.data {
                SubpacketData::RevocationKey(key) => Some(&key.fingerprint[..]),
                _ => None,
            })
    })
}

/// Whether a verified revocation stands over a user id.
fn user_revoked(cert: &SignedPublicKey, user: &SignedUser) -> bool {
    user.signatures.iter().any(|sig| {
        sig.typ() == Some(SignatureType::CertRevocation)
            && sig
                .verify_certification(&cert.primary_key, Tag::UserId, &user.id)
                .is_ok()
    })
}

/// The signature creation time the packet carries, in seconds since the Unix
/// epoch. A zero instant reads as absent.
fn created_at(sig: &Signature) -> Option<u64> {
    epoch(sig.created()?.as_secs())
}

/// The instant the signature itself expires: its creation time plus the
/// expiration the packet carries. Absent where the packet carries no
/// expiration or carries a zero one.
fn expires_at(sig: &Signature) -> Option<u64> {
    let created = created_at(sig)?;
    let lifetime = epoch(sig.signature_expiration_time()?.as_secs())?;
    Some(created + lifetime)
}

/// A packet time field in seconds, with zero read as absent.
fn epoch(secs: u32) -> Option<u64> {
    (secs != 0).then(|| u64::from(secs))
}

/// The public-key algorithm name the report writes. Algorithm id 22 is
/// reported as `EdDSA`. The enum admits ids the port knows no name for, which
/// are reported as their number.
fn pubkey_algorithm_name(sig: &Signature) -> Option<String> {
    let alg = sig.config()?.pub_alg;
    Some(match alg {
        PublicKeyAlgorithm::RSA | PublicKeyAlgorithm::RSAEncrypt | PublicKeyAlgorithm::RSASign => {
            "RSA".to_owned()
        }
        PublicKeyAlgorithm::DSA => "DSA".to_owned(),
        PublicKeyAlgorithm::ECDH => "ECDH".to_owned(),
        PublicKeyAlgorithm::ECDSA => "ECDSA".to_owned(),
        PublicKeyAlgorithm::EdDSALegacy => "EdDSA".to_owned(),
        PublicKeyAlgorithm::Ed25519 => "Ed25519".to_owned(),
        PublicKeyAlgorithm::Ed448 => "Ed448".to_owned(),
        other => u8::from(other).to_string(),
    })
}

/// The digest algorithm name the report writes. The enum admits ids the port
/// knows no name for, which are reported as their number.
fn hash_algorithm_name(sig: &Signature) -> Option<String> {
    let alg = sig.hash_alg()?;
    Some(match alg {
        HashAlgorithm::Md5
        | HashAlgorithm::Sha1
        | HashAlgorithm::Ripemd160
        | HashAlgorithm::Sha256
        | HashAlgorithm::Sha384
        | HashAlgorithm::Sha512
        | HashAlgorithm::Sha224 => alg.to_string(),
        other => u8::from(other).to_string(),
    })
}

/// The name and the email of the user id the report names for a certificate:
/// the primary user id, or, where no user id is marked primary, the newest
/// self-signed one. A user id that is not valid UTF-8 is read with the invalid
/// sequences replaced.
///
/// A revoked user id is passed over, and the primary-user-id subpacket on a
/// revoked user id counts for nothing. This is what `gpgv` names on the
/// verdict line: over a certificate whose primary user id is revoked and whose
/// second user id is not, it names the second one. Where every user id is
/// revoked it names a revoked one, so a certificate holding nothing else still
/// reports a user id.
///
/// A user id is chosen on its certifications that verify under the primary key
/// alone, both where it is marked primary and where it is ranked. A
/// third-party certification and a packet anyone stapled onto the certificate
/// therefore choose nothing. This too is what `gpgv` names. Over a certificate
/// where one user id carries the newest self-signature and another carries a
/// newer third-party certification, it names the user id the self-signature
/// stands on; and over a certificate whose primary mark rides on a
/// self-signature that does not verify, it names the other user id.
fn reported_user_id(cert: &SignedPublicKey) -> (Option<String>, Option<String>) {
    let mut usable: Vec<&SignedUser> = cert
        .details
        .users
        .iter()
        .filter(|user| !user_revoked(cert, user))
        .collect();
    if usable.is_empty() {
        usable = cert.details.users.iter().collect();
    }
    let user = usable
        .iter()
        .copied()
        .find(|user| user_marked_primary(cert, user))
        .or_else(|| {
            usable
                .iter()
                .copied()
                .max_by_key(|user| newest_certification(cert, user))
        });
    match user {
        Some(user) => split_uid(&String::from_utf8_lossy(user.id.id())),
        None => (None, None),
    }
}

/// Split an OpenPGP user id into name and email: the trailing `<address>` is
/// the email and what precedes it is the name. A user id without an address is
/// all name.
fn split_uid(uid: &str) -> (Option<String>, Option<String>) {
    let non_empty = |s: &str| {
        let s = s.trim();
        (!s.is_empty()).then(|| s.to_owned())
    };
    if let Some(start) = uid.rfind('<')
        && let Some(end) = uid.rfind('>')
        && end > start
    {
        (non_empty(&uid[..start]), non_empty(&uid[start + 1..end]))
    } else {
        (non_empty(uid), None)
    }
}

/// Over a user id, the creation time of the newest certification that verifies
/// under the certificate's primary key and that has not itself expired. A
/// third-party certification and a packet anyone stapled onto the certificate
/// do not verify under that key, so neither ranks a user id. A user id holding
/// no such certification ranks at the epoch.
///
/// A certification whose own expiration time has passed ranks nothing, which
/// is what `gpgv` 2.4.9 names. Over a certificate whose newest certification
/// self-signature over one user id carries signature subpacket 3 with an
/// instant already past, it names the other user id, whose own self-signature
/// stands older than that signature and is live; the same signature without
/// subpacket 3 makes it name the first user id.
///
/// A certification another signature revokes still ranks. The reference tool's
/// rule for that case is unmeasured, and the field the rule decides is the
/// reported name.
fn newest_certification(cert: &SignedPublicKey, user: &SignedUser) -> u32 {
    let primary = &cert.primary_key;
    user.signatures
        .iter()
        .filter(|sig| {
            is_certification(sig)
                && !signature_expired(sig)
                && sig
                    .verify_certification(primary, Tag::UserId, &user.id)
                    .is_ok()
        })
        .filter_map(|sig| sig.created())
        .map(Timestamp::as_secs)
        .max()
        .unwrap_or(0)
}

/// Whether a certification that verifies under the certificate's primary key
/// and that has not itself expired marks a user id primary. A primary-user-id
/// subpacket on a packet the primary key did not make marks nothing, which is
/// what `gpgv` names: over a certificate whose primary-marked self-signature
/// was altered, it names the other user id.
///
/// A certification whose own expiration time has passed marks nothing either.
/// `gpgv` 2.4.9 answers the same way: over a certificate whose primary mark
/// rides on a self-signature carrying signature subpacket 3 with an instant
/// already past, it names the other user id, and the same signature without
/// subpacket 3 makes it name the marked one.
fn user_marked_primary(cert: &SignedPublicKey, user: &SignedUser) -> bool {
    let primary = &cert.primary_key;
    user.signatures.iter().any(|sig| {
        sig.is_primary()
            && is_certification(sig)
            && !signature_expired(sig)
            && sig
                .verify_certification(primary, Tag::UserId, &user.id)
                .is_ok()
    })
}

/// The creation time a signature packet states, with an absent one reading as
/// the epoch, so that a signature stating none is the oldest.
fn created_secs(sig: &Signature) -> u32 {
    sig.created().map(Timestamp::as_secs).unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::process::Command;

    use super::*;
    use crate::gpg::{GpgVerifier, STATUS_PREFIX, parse_epoch, scratch_dir};

    /// The payload every fixture signs.
    const PAYLOAD: &[u8] = b"ostrya commit payload";
    /// A payload no fixture signs, for the changed-payload case.
    const OTHER_PAYLOAD: &[u8] = b"ostrya other payload";

    /// Whether the named binary answers. The cases below build their fixtures
    /// with `gpg` and read their reference records from `gpgv`, so an absent
    /// binary skips a case and never passes one.
    fn available(program: &str) -> bool {
        Command::new(program)
            .arg("--version")
            .output()
            .is_ok_and(|out| out.status.success())
    }

    /// A private GnuPG home holding one freshly generated, passphrase-free
    /// ed25519 signing key, under the test scratch tree. Every `gpg` and
    /// `gpgv` run names a directory inside it, so the invoking user's GnuPG
    /// home and any agent of theirs take no part. Dropping the fixture kills
    /// the agent GnuPG auto-started for the directory and removes the tree.
    struct Fixture {
        dir: PathBuf,
        /// The primary key fingerprint, uppercase hex.
        primary: String,
        /// Whether every `gpg` run in this home stands at the instant
        /// [`KEY_CREATED`] names.
        faked: bool,
    }

    impl Fixture {
        /// A new home directory holding one ed25519 signing key for `uid`
        /// that never expires.
        fn new(uid: &str) -> Fixture {
            Fixture::build(uid, "ed25519", false, "never")
        }

        /// The same with an RSA signing key. rPGP refuses a digest weaker than
        /// 256 bits with an Ed25519 key, so the digest policy of the port is
        /// stated over a key whose cryptography admits one.
        fn rsa(uid: &str) -> Fixture {
            Fixture::build(uid, "rsa2048", false, "never")
        }

        /// A new home directory whose key was created at the instant
        /// [`KEY_CREATED`] names and expires after `expiry`. Every `gpg` run
        /// in it stands at that instant, so a signature it makes was made
        /// while the key was live. `gpgv` reads the real clock, which is what
        /// makes an expired key expired.
        fn at(uid: &str, expiry: &str) -> Fixture {
            Fixture::build(uid, "ed25519", true, expiry)
        }

        /// A new home directory holding no key, for building a keyring out of
        /// the certificates other homes export.
        fn bare() -> Fixture {
            use std::os::unix::fs::DirBuilderExt;
            let dir = scratch_dir();
            let mut builder = std::fs::DirBuilder::new();
            builder.mode(0o700);
            builder.create(&dir).unwrap();
            builder.create(dir.join("gv")).unwrap();
            Fixture {
                dir,
                primary: String::new(),
                faked: false,
            }
        }

        fn build(uid: &str, algorithm: &str, faked: bool, expiry: &str) -> Fixture {
            let mut fixture = Fixture::bare();
            fixture.faked = faked;
            for _ in 0..16 {
                let status = fixture
                    .gpg()
                    .args(["--quick-gen-key", uid, algorithm, "sign", expiry])
                    .status()
                    .unwrap();
                assert!(status.success(), "gpg --quick-gen-key failed");
                fixture.primary = fixture.fingerprints().remove(0);
                if fixture.secret_key_is_read() {
                    return fixture;
                }
                fixture.delete_key();
            }
            panic!("no generated key exported a secret key the pgp crate reads");
        }

        /// Whether the `pgp` crate reads the home's exported secret key.
        ///
        /// `gpg` writes the ed25519 secret scalar as an MPI declaring 256 bits
        /// even where its leading octet is zero, and the two-octet checksum it
        /// writes covers the octets it wrote. The `pgp` crate reads the MPI,
        /// drops the leading zero, and sums the shorter form, so it refuses
        /// such a key with "Invalid checksum". One scalar in 256 carries that
        /// octet, so a key whose secret export the crate refuses is generated
        /// again and the cases that sign with it stand on every run.
        fn secret_key_is_read(&self) -> bool {
            pgp::composed::SignedSecretKey::from_bytes(Cursor::new(self.secret_key())).is_ok()
        }

        /// Remove the home's key, both its secret and its public part.
        fn delete_key(&self) {
            let status = self
                .gpg()
                .args(["--yes", "--delete-secret-and-public-key", &self.primary])
                .status()
                .unwrap();
            assert!(
                status.success(),
                "gpg --delete-secret-and-public-key failed"
            );
        }

        /// A `gpg` command bound to this home directory, batch mode and with
        /// the empty passphrase supplied without a prompt.
        fn gpg(&self) -> Command {
            let mut cmd = Command::new("gpg");
            cmd.arg("--homedir").arg(&self.dir).arg("--batch").args([
                "--pinentry-mode",
                "loopback",
                "--passphrase",
                "",
            ]);
            if self.faked {
                cmd.args(["--faked-system-time", "20250101T000000!"]);
            }
            cmd
        }

        /// A `gpg` command bound to this home directory that reads the answers
        /// to an interactive command's prompts from standard input. Batch mode
        /// answers no prompt, so the commands that ask one run through this.
        fn gpg_interactive(&self) -> Command {
            let mut cmd = Command::new("gpg");
            cmd.arg("--homedir").arg(&self.dir).args([
                "--no-tty",
                "--no-batch",
                "--command-fd",
                "0",
                "--pinentry-mode",
                "loopback",
                "--passphrase",
                "",
            ]);
            if self.faked {
                cmd.args(["--faked-system-time", "20250101T000000!"]);
            }
            cmd
        }

        /// Import a certificate stream into this home.
        fn import(&self, bytes: &[u8]) {
            let path = self.write("import.gpg", bytes);
            let status = self.gpg().arg("--import").arg(path).status().unwrap();
            assert!(status.success(), "gpg --import failed");
        }

        /// Import a stream `gpg` merges while it reports a failure.
        ///
        /// `gpg --import` exits 2 over a designated revoker's revocation, with
        /// "no public key - can't apply revocation certificate", and it exits 2
        /// whether or not the home holds the revoker's certificate. It merges
        /// the class 0x20 signature into the certificate it holds either way:
        /// the export of the home carries the packet, and the case that reads
        /// the export states that the packet is there.
        fn import_merging(&self, bytes: &[u8]) {
            let path = self.write("import.gpg", bytes);
            self.gpg().arg("--import").arg(path).status().unwrap();
        }

        /// The exported binary certificates of the keys `keys` names, in the
        /// order they are named.
        fn export_keys(&self, keys: &[&str]) -> Vec<u8> {
            let out = self.gpg().arg("--export").args(keys).output().unwrap();
            assert!(out.status.success() && !out.stdout.is_empty());
            out.stdout
        }

        /// Designate the key `revoker` names as a revoker of this home's
        /// primary key. `gpg` writes a fresh direct-key self-signature
        /// carrying signature subpacket 12, so this home must already hold the
        /// revoker's certificate.
        fn add_revoker(&self, revoker: &str) {
            let mut cmd = self.gpg_interactive();
            cmd.arg("--edit-key").arg(&self.primary);
            answer(
                cmd,
                format!("addrevoker\n{revoker}\ny\ny\nsave\n").as_bytes(),
                "gpg --edit-key addrevoker",
            );
        }

        /// The key revocation a designated revoker makes over the key `key`
        /// names, as the binary packet stream `gpg --desig-revoke` writes: a
        /// transferable public key of the revoked key carrying the class 0x20
        /// signature right after the primary key packet. This home must hold
        /// the revoker's secret key and a certificate of the revoked key that
        /// designates the revoker.
        fn desig_revoke(&self, key: &str) -> Vec<u8> {
            let path = self.dir.join("desig-revoke.asc");
            let mut cmd = self.gpg_interactive();
            cmd.arg("--armor")
                .arg("--output")
                .arg(&path)
                .arg("--desig-revoke")
                .arg(key);
            answer(cmd, b"y\n0\n\ny\n", "gpg --desig-revoke");
            crate::gpg::dearmor(&std::fs::read(&path).unwrap()).unwrap()
        }

        /// The exported secret key, which `gpg` writes unprotected because the
        /// passphrase is empty.
        fn secret_key(&self) -> Vec<u8> {
            let out = self.gpg().arg("--export-secret-keys").output().unwrap();
            assert!(out.status.success() && !out.stdout.is_empty());
            out.stdout
        }

        /// The revocation certificate `gpg` stored when it generated the key,
        /// as the binary key revocation signature packet it holds. The stored
        /// file carries prose before the armored block, and a colon before the
        /// block's first dash so that an accidental import does nothing.
        fn revocation_packet(&self) -> Vec<u8> {
            let text = std::fs::read_to_string(self.revocation_path()).unwrap();
            let at = text.find("-----BEGIN PGP").unwrap();
            let packet = crate::gpg::dearmor(&text.as_bytes()[at..]).unwrap();
            assert_eq!(split_packets(&packet).len(), 1);
            packet
        }

        fn revocation_path(&self) -> PathBuf {
            self.dir
                .join("openpgp-revocs.d")
                .join(format!("{}.rev", self.primary))
        }

        /// Revoke the primary key by importing the revocation certificate
        /// `gpg` stored for it.
        fn revoke_primary(&self) {
            let text = std::fs::read_to_string(self.revocation_path()).unwrap();
            let at = text.find("-----BEGIN PGP").unwrap();
            let path = self.write("revocation.asc", &text.as_bytes()[at..]);
            let status = self.gpg().arg("--import").arg(path).status().unwrap();
            assert!(status.success(), "gpg --import of the revocation failed");
        }

        /// Revoke the first subkey.
        fn revoke_subkey(&self) {
            let out = self
                .gpg()
                .args(["--command-fd", "0", "--edit-key", &self.primary])
                .stdin(std::process::Stdio::piped())
                .stdout(std::process::Stdio::null())
                .spawn()
                .and_then(|mut child| {
                    use std::io::Write;
                    child
                        .stdin
                        .take()
                        .unwrap()
                        .write_all(b"key 1\nrevkey\ny\n1\n\ny\nsave\n")?;
                    child.wait_with_output()
                })
                .unwrap();
            assert!(out.status.success(), "gpg --edit-key revkey failed");
        }

        /// Add a user id.
        fn add_uid(&self, uid: &str) {
            let status = self
                .gpg()
                .args(["--quick-add-uid", &self.primary, uid])
                .status()
                .unwrap();
            assert!(status.success(), "gpg --quick-add-uid failed");
        }

        /// Add a user id, with `gpg` standing at `when`, so that the
        /// self-signature it makes over the new user id carries a creation
        /// time the caller chooses. The clock option stated last answers.
        fn add_uid_at(&self, when: &str, uid: &str) {
            let status = self
                .gpg()
                .args(["--faked-system-time", when])
                .args(["--quick-add-uid", &self.primary, uid])
                .status()
                .unwrap();
            assert!(status.success(), "gpg --quick-add-uid failed");
        }

        /// Mark a user id primary.
        fn set_primary_uid(&self, uid: &str) {
            let status = self
                .gpg()
                .args(["--quick-set-primary-uid", &self.primary, uid])
                .status()
                .unwrap();
            assert!(status.success(), "gpg --quick-set-primary-uid failed");
        }

        /// Set the primary key's expiry, with `gpg` standing at `when`.
        ///
        /// A fresh self-signature carries a creation time, and `gpg` refuses to
        /// write one at the instant the self-signature it replaces carries: it
        /// reports "make_keysig_packet failed: Time conflict". The clock option
        /// stated last answers, so a run at a later instant writes the
        /// signature a run at the fixture's own instant cannot.
        fn set_expire_at(&self, when: &str, expiry: &str) {
            let status = self
                .gpg()
                .args(["--faked-system-time", when])
                .args(["--quick-set-expire", &self.primary, expiry])
                .status()
                .unwrap();
            assert!(status.success(), "gpg --quick-set-expire failed");
        }

        /// Revoke a user id.
        fn revoke_uid(&self, uid: &str) {
            let status = self
                .gpg()
                .args(["--quick-revoke-uid", &self.primary, uid])
                .status()
                .unwrap();
            assert!(status.success(), "gpg --quick-revoke-uid failed");
        }

        /// Add a signing subkey to the primary key and report its
        /// fingerprint.
        fn add_signing_subkey(&self) -> String {
            self.add_signing_subkey_expiring("never")
        }

        /// The same, with a lifetime for the subkey.
        fn add_signing_subkey_expiring(&self, expiry: &str) -> String {
            let status = self
                .gpg()
                .args(["--quick-add-key", &self.primary, "ed25519", "sign", expiry])
                .status()
                .unwrap();
            assert!(status.success(), "gpg --quick-add-key failed");
            let fingerprints = self.fingerprints();
            assert_eq!(fingerprints.len(), 2);
            fingerprints[1].clone()
        }

        /// Every key fingerprint the home directory holds, in listing order:
        /// the primary key first, then its subkeys.
        fn fingerprints(&self) -> Vec<String> {
            let out = self
                .gpg()
                .args(["--with-colons", "--list-keys"])
                .output()
                .unwrap();
            assert!(out.status.success(), "gpg --list-keys failed");
            String::from_utf8_lossy(&out.stdout)
                .lines()
                .filter_map(|line| line.strip_prefix("fpr:"))
                .filter_map(|rest| rest.split(':').nth(8).map(str::to_owned))
                .collect()
        }

        /// The exported binary public keyring.
        fn keyring(&self) -> Vec<u8> {
            let out = self.gpg().arg("--export").output().unwrap();
            assert!(out.status.success() && !out.stdout.is_empty());
            out.stdout
        }

        /// The certificates a verifier loads the exported keyring into.
        fn certs(&self) -> Vec<SignedPublicKey> {
            std::sync::Arc::unwrap_or_clone(
                GpgVerifier::from_keyring_bytes([self.keyring()])
                    .unwrap()
                    .certs,
            )
        }

        /// One detached signature over `payload`, made by the key `key`
        /// names exactly.
        fn sign(&self, key: &str, payload: &[u8]) -> Vec<u8> {
            self.sign_with(key, payload, &[])
        }

        /// One detached signature over `payload`, made by the key `key` names
        /// exactly, with `extra` passed to `gpg` on top of the base options.
        fn sign_with(&self, key: &str, payload: &[u8], extra: &[&str]) -> Vec<u8> {
            let file = self.write("payload", payload);
            let out = self
                .gpg()
                .args(extra)
                .args(["--detach-sign", "--output", "-", "--local-user"])
                .arg(format!("{key}!"))
                .arg(file)
                .output()
                .unwrap();
            assert!(out.status.success() && !out.stdout.is_empty());
            out.stdout
        }

        /// The records `gpgv` reports for the same inputs, read through the
        /// status-stream parser. This is the reference every case below
        /// compares against.
        fn gpgv_records(&self, keyring: &[u8], blob: &[u8], payload: &[u8]) -> Vec<SignatureInfo> {
            let ring = self.write("ring.gpg", keyring);
            let sig = self.write("blob.sig", blob);
            let data = self.write("data", payload);
            let out = Command::new("gpgv")
                .arg("--homedir")
                .arg(self.dir.join("gv"))
                .args(["--status-fd", "1", "--keyring"])
                .arg(ring)
                .arg(sig)
                .arg(data)
                .output()
                .unwrap();
            parse_status(&out.stdout)
        }

        /// Write one file into the fixture directory and report its path.
        fn write(&self, name: &str, bytes: &[u8]) -> PathBuf {
            let path = self.dir.join(name);
            std::fs::write(&path, bytes).unwrap();
            path
        }
    }

    impl Drop for Fixture {
        fn drop(&mut self) {
            let _ = Command::new("gpgconf")
                .arg("--homedir")
                .arg(&self.dir)
                .args(["--kill", "gpg-agent"])
                .status();
            let _ = std::fs::remove_dir_all(&self.dir);
        }
    }

    /// Run `cmd`, writing `answers` to its standard input, and assert that it
    /// reported success. `what` names the command in the assertion message.
    fn answer(mut cmd: Command, answers: &[u8], what: &str) {
        use std::io::Write;

        let out = cmd
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::null())
            .spawn()
            .and_then(|mut child| {
                child.stdin.take().unwrap().write_all(answers)?;
                child.wait_with_output()
            })
            .unwrap();
        assert!(out.status.success(), "{what} failed");
    }

    /// The environment variable that turns the absent-GnuPG skip into a
    /// failure. A harness setting it declares that the GnuPG binaries are
    /// installed, so a run where one is not is a broken harness rather than a
    /// test to pass over. The integration tests read the same variable.
    const REQUIRE_GNUPG: &str = "OSTRYA_REQUIRE_GNUPG";

    /// Whether both binaries answer, naming the absent one when they do not.
    /// These cases state each policy rule against `gpgv`, so a harness without
    /// a binary would otherwise report the rules as tested while no assertion
    /// ran. With [`REQUIRE_GNUPG`] set the absence fails.
    fn tools_available() -> bool {
        for program in ["gpg", "gpgv"] {
            if !available(program) {
                assert!(
                    std::env::var_os(REQUIRE_GNUPG).is_none(),
                    "{REQUIRE_GNUPG} is set and `{program}` is not available, \
                     so the GPG tests cannot run"
                );
                eprintln!("skipping: {program} not available");
                return false;
            }
        }
        true
    }

    /// Assert one record states what `gpgv` states about the same signature,
    /// field by field, the verdict included. A case that parts from `gpgv` on
    /// purpose states the divergence itself and does not come here.
    fn assert_agrees(port: &SignatureInfo, reference: &SignatureInfo) {
        assert_eq!(port.fingerprint, reference.fingerprint, "fingerprint");
        assert_eq!(
            port.primary_fingerprint, reference.primary_fingerprint,
            "primary_fingerprint"
        );
        assert_eq!(port.created, reference.created, "created");
        assert_eq!(port.expires, reference.expires, "expires");
        assert_eq!(
            port.pubkey_algorithm, reference.pubkey_algorithm,
            "pubkey_algorithm"
        );
        assert_eq!(
            port.hash_algorithm, reference.hash_algorithm,
            "hash_algorithm"
        );
        assert_eq!(port.user_name, reference.user_name, "user_name");
        assert_eq!(port.user_email, reference.user_email, "user_email");
        assert_eq!(port.key_missing, reference.key_missing, "key_missing");
        assert_eq!(port.valid, reference.valid, "valid");
        assert_eq!(port.expired, reference.expired, "expired");
        assert_eq!(port.revoked, reference.revoked, "revoked");
        assert_eq!(port.key_expires, reference.key_expires, "key_expires");
    }

    /// Assert one record states what `gpgv` states about the same signature,
    /// apart from the two key fingerprints.
    ///
    /// The two references part on those two fields where the issuer resolved
    /// and the cryptography failed. `gpgv` draws `BADSIG <keyid> <uid>`, which
    /// names the issuer by eight bytes where the field holds a whole
    /// fingerprint, so [`parse_status`] passes that key id over and the
    /// reference record states neither fingerprint. `ostree` 2026.1 names both
    /// keys on the lines it draws over such a signature: a signature a subkey
    /// made draws `key ID <subkey-key-id>`, the subkey's own key id, with
    /// `Primary key ID <primary-key-id>` under it, and a signature the primary
    /// key made draws that same pair with the primary key in both places. The
    /// report a user reads is the oracle here, so the engine states both keys.
    /// The instant and the algorithm stay absent: `gpgv` states neither on
    /// this path, the tool draws the Unix epoch and `[unknown name]` in their
    /// places, and the engine states neither.
    fn assert_agrees_but_fingerprints(port: &SignatureInfo, reference: &SignatureInfo) {
        let mut port = port.clone();
        port.fingerprint = reference.fingerprint.clone();
        port.primary_fingerprint = reference.primary_fingerprint.clone();
        assert_agrees(&port, reference);
    }

    /// A signature the primary key made reports the primary key as both the
    /// signing key and the certificate, with the certificate's user id.
    #[test]
    fn primary_key_signature_agrees_with_gpgv() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Prim <prim@ostrya.example>");
        let keyring = home.keyring();
        let blob = home.sign(&home.primary, PAYLOAD);
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        // The reference verified the signature, and the port reports the key
        // that did so.
        assert!(reference[0].valid);
        assert_eq!(
            outcome.signatures[0].fingerprint.as_deref(),
            Some(&*home.primary)
        );
        assert_eq!(
            outcome.signatures[0].primary_fingerprint.as_deref(),
            Some(&*home.primary)
        );
        assert_eq!(
            outcome.signatures[0].user_email.as_deref(),
            Some("prim@ostrya.example")
        );
    }

    /// A signature carrying an expiry of its own reports the instant it
    /// expires. The packet states a lifetime counted from the creation time and
    /// the reference states an absolute instant, so this is the one field whose
    /// value the engine computes.
    #[test]
    fn expiring_signature_agrees_with_gpgv() {
        if !tools_available() {
            return;
        }
        /// The lifetime `--default-sig-expire 1d` writes, in seconds.
        const ONE_DAY: u64 = 24 * 60 * 60;
        let home = Fixture::new("Exp <exp@ostrya.example>");
        let keyring = home.keyring();
        let blob = home.sign_with(&home.primary, PAYLOAD, &["--default-sig-expire", "1d"]);
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        let created = info.created.expect("the packet carries a creation time");
        assert_eq!(reference[0].expires, Some(created + ONE_DAY));
        assert_eq!(info.expires, Some(created + ONE_DAY));
    }

    /// A signature a signing subkey made reports the subkey as the signing key
    /// and its certificate as the primary fingerprint.
    #[test]
    fn subkey_signature_agrees_with_gpgv() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Sub <sub@ostrya.example>");
        let subkey = home.add_signing_subkey();
        let keyring = home.keyring();
        let blob = home.sign(&subkey, PAYLOAD);
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(reference[0].valid);
        assert_eq!(outcome.signatures[0].fingerprint.as_deref(), Some(&*subkey));
        assert_eq!(
            outcome.signatures[0].primary_fingerprint.as_deref(),
            Some(&*home.primary)
        );
    }

    /// One blob holding two concatenated signatures reports two records, in
    /// the order the packets stand in.
    #[test]
    fn two_signature_blob_agrees_with_gpgv() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Two <two@ostrya.example>");
        let subkey = home.add_signing_subkey();
        let keyring = home.keyring();
        let mut blob = home.sign(&home.primary, PAYLOAD);
        blob.extend_from_slice(&home.sign(&subkey, PAYLOAD));
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 2);
        assert_eq!(reference.len(), 2);
        for (port, reference) in outcome.signatures.iter().zip(&reference) {
            assert_agrees(port, reference);
        }
        assert_eq!(
            outcome.signatures[0].fingerprint.as_deref(),
            Some(&*home.primary)
        );
        assert_eq!(outcome.signatures[1].fingerprint.as_deref(), Some(&*subkey));
    }

    /// A signature whose issuer no loaded certificate holds reports
    /// `key_missing`, with the fingerprint, the creation time, and the two
    /// algorithm names read out of the signature packet. These are the fields
    /// `ERRSIG` carries.
    #[test]
    fn unknown_issuer_agrees_with_errsig() {
        if !tools_available() {
            return;
        }
        let signer = Fixture::new("Signer <signer@ostrya.example>");
        let other = Fixture::new("Other <other@ostrya.example>");
        let blob = signer.sign(&signer.primary, PAYLOAD);
        let outcome =
            verify_signatures(&other.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = signer.gpgv_records(&other.keyring(), &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(info.key_missing);
        assert!(reference[0].key_missing);
        // The three field groups `ERRSIG` supplies, named one at a time.
        assert_eq!(info.pubkey_algorithm.as_deref(), Some("EdDSA"));
        assert_eq!(info.pubkey_algorithm, reference[0].pubkey_algorithm);
        assert_eq!(info.hash_algorithm, reference[0].hash_algorithm);
        assert_eq!(info.created, reference[0].created);
        assert!(info.created.is_some());
        assert_eq!(info.fingerprint.as_deref(), Some(&*signer.primary));
        assert_eq!(info.fingerprint, reference[0].fingerprint);
        // No key verified, so the certificate fields stay absent.
        assert_eq!(info.primary_fingerprint, None);
        assert_eq!(info.user_name, None);
    }

    /// A signature over a payload other than the one it was made over reports
    /// the resolved signing key, its certificate, and the certificate's user
    /// id. Nothing else the signature claims was checked, so the record states
    /// nothing else, and neither reference states more.
    #[test]
    fn changed_payload_agrees_with_gpgv() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Bad <bad@ostrya.example>");
        let keyring = home.keyring();
        let blob = home.sign(&home.primary, PAYLOAD);
        let outcome =
            verify_signatures(&home.certs(), OTHER_PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, OTHER_PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees_but_fingerprints(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(!reference[0].valid);
        assert!(!info.key_missing);
        // The fields the record carries on this path: the resolved signing key,
        // its certificate, and the certificate's user id. The signing key is
        // the primary key here, so both fingerprints name it, and it is the key
        // `gpgv` names by eight bytes on its `BADSIG` line and `ostree` names
        // on the line it draws.
        assert_eq!(info.fingerprint.as_deref(), Some(&*home.primary));
        assert_eq!(info.primary_fingerprint.as_deref(), Some(&*home.primary));
        assert_eq!(reference[0].fingerprint, None);
        assert_eq!(reference[0].primary_fingerprint, None);
        assert_eq!(info.user_name.as_deref(), Some("Bad"));
        assert_eq!(info.user_email.as_deref(), Some("bad@ostrya.example"));
        // Nothing else the packet claims is stated. `gpgv` names no instant and
        // no algorithm on `BADSIG`, and `ostree` 2026.1 draws the epoch instant
        // and `[unknown name]` in their places.
        assert_eq!(info.created, None);
        assert_eq!(info.pubkey_algorithm, None);
        assert_eq!(info.hash_algorithm, None);
    }

    /// A signature a signing subkey made over a payload other than the one it
    /// was made over reports the subkey as the signing key and its certificate
    /// as the primary fingerprint. `ostree` 2026.1 names those same two keys
    /// over such a signature, on the `key ID` field of the report line and on
    /// the `Primary key ID` line under the verdict, and its `gpg-sign
    /// --delete` removes the signature under either key's key id.
    #[test]
    fn changed_payload_by_a_subkey_reports_both_keys() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Subbad <subbad@ostrya.example>");
        let subkey = home.add_signing_subkey();
        let keyring = home.keyring();
        let blob = home.sign(&subkey, PAYLOAD);
        let outcome =
            verify_signatures(&home.certs(), OTHER_PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, OTHER_PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees_but_fingerprints(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(!info.valid && !reference[0].valid);
        assert_eq!(info.fingerprint.as_deref(), Some(&*subkey));
        assert_eq!(info.primary_fingerprint.as_deref(), Some(&*home.primary));
        assert_eq!(info.user_email.as_deref(), Some("subbad@ostrya.example"));
    }

    /// A blob holding half a signature packet reports one record and nothing
    /// about it, so the record count follows the stored blob count. `gpgv`
    /// reads no signature out of it and states no record at all.
    #[test]
    fn truncated_blob_reports_one_bare_record() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Cut <cut@ostrya.example>");
        let keyring = home.keyring();
        let whole = home.sign(&home.primary, PAYLOAD);
        let blob = whole[..whole.len() / 2].to_vec();
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        assert!(home.gpgv_records(&keyring, &blob, PAYLOAD).is_empty());
        assert_eq!(outcome.signatures.len(), 1);
        assert_bare(&outcome.signatures[0]);
        assert!(!outcome.valid);
    }

    /// An empty blob reports one record and nothing about it, as a truncated
    /// one does.
    #[test]
    fn empty_blob_reports_one_bare_record() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Empty <empty@ostrya.example>");
        let keyring = home.keyring();
        let outcome = verify_signatures(&home.certs(), PAYLOAD, &[Vec::new()]).unwrap();
        assert!(home.gpgv_records(&keyring, b"", PAYLOAD).is_empty());
        assert_eq!(outcome.signatures.len(), 1);
        assert_bare(&outcome.signatures[0]);
        assert!(!outcome.valid);
    }

    /// Assert a record states nothing about a signature.
    fn assert_bare(info: &SignatureInfo) {
        assert!(!info.valid);
        assert_eq!(info.fingerprint, None);
        assert_eq!(info.primary_fingerprint, None);
        assert_eq!(info.created, None);
        assert_eq!(info.expires, None);
        assert_eq!(info.pubkey_algorithm, None);
        assert_eq!(info.hash_algorithm, None);
        assert_eq!(info.user_name, None);
        assert_eq!(info.user_email, None);
        assert!(!info.key_missing);
    }

    /// A blob over the one-mebibyte ceiling is refused by the name of the blob
    /// that carried it, and the refusal states the ceiling. The blob is
    /// bounded before it is parsed, so the packet cap is not what refused it.
    /// The ceiling is the port's own bound and the reference tool holds none,
    /// which is why nothing is compared against `gpgv` here.
    #[test]
    fn oversized_blob_is_refused() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Big <big@ostrya.example>");
        let one = home.sign(&home.primary, PAYLOAD);
        let copies = MAX_SIGNATURE_BLOB / one.len() + 1;
        let blob = one.repeat(copies);
        assert!(blob.len() > MAX_SIGNATURE_BLOB);
        let err = verify_signatures(&home.certs(), PAYLOAD, &[blob]).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("signature blob 0")
                && m.contains("ceiling") && !m.contains("packets")),
            "{err}"
        );
    }

    /// A blob holding more than 64 signature packets is refused by name, and
    /// the refusal states the cap. `gpgv` reads every packet and reports one
    /// record each, so the cap is a bound of the port's own.
    #[test]
    fn too_many_signature_packets_is_refused() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Many <many@ostrya.example>");
        let keyring = home.keyring();
        let certs = home.certs();
        let one = home.sign(&home.primary, PAYLOAD);
        let many = one.repeat(MAX_SIGNATURE_PACKETS + 1);
        assert!(many.len() <= MAX_SIGNATURE_BLOB);
        let err = verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&many)).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("signature blob 0")
                && m.contains("64 signature packets")),
            "{err}"
        );
        assert_eq!(
            home.gpgv_records(&keyring, &many, PAYLOAD).len(),
            MAX_SIGNATURE_PACKETS + 1
        );
        // One packet short of the cap reports one record each, so the cap is
        // what refused the blob above.
        let allowed = one.repeat(MAX_SIGNATURE_PACKETS);
        let outcome = verify_signatures(&certs, PAYLOAD, &[allowed]).unwrap();
        assert_eq!(outcome.signatures.len(), MAX_SIGNATURE_PACKETS);
    }

    /// A blob that holds the cap in whole packets and ends in a partial packet
    /// reports one record per whole packet. The stream stops at the partial
    /// packet, and every blob ending in a partial packet gets that report. The
    /// cap refuses a blob on a packet the stream carried whole, which
    /// `too_many_signature_packets_is_refused` states.
    ///
    /// `gpgv` reads the same whole packets and states one record each. Over
    /// this blob it reports one `GOODSIG` line per whole packet and exits 0,
    /// so it passes over the partial packet with no diagnostic.
    #[test]
    fn a_partial_packet_after_the_cap_ends_the_stream() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Cap <cap@ostrya.example>");
        let keyring = home.keyring();
        let one = home.sign(&home.primary, PAYLOAD);
        let mut blob = one.repeat(MAX_SIGNATURE_PACKETS);
        blob.extend_from_slice(&one[..one.len() / 2]);
        assert!(blob.len() <= MAX_SIGNATURE_BLOB);
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        assert_eq!(outcome.signatures.len(), MAX_SIGNATURE_PACKETS);
        assert!(outcome.valid);
        assert_eq!(
            home.gpgv_records(&keyring, &blob, PAYLOAD).len(),
            MAX_SIGNATURE_PACKETS
        );
    }

    /// Every stored blob contributes at least one record, so a run over
    /// several blobs reports them in the order they were stored.
    #[test]
    fn record_count_follows_the_blob_count() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Count <count@ostrya.example>");
        let good = home.sign(&home.primary, PAYLOAD);
        let blobs = vec![good.clone(), Vec::new(), good];
        let outcome = verify_signatures(&home.certs(), PAYLOAD, &blobs).unwrap();
        assert_eq!(outcome.signatures.len(), 3);
        assert!(outcome.signatures[0].fingerprint.is_some());
        assert_bare(&outcome.signatures[1]);
        assert!(outcome.signatures[2].fingerprint.is_some());
    }

    /// The instant `Fixture::at` pins the clock to, in seconds since the Unix
    /// epoch: 2025-01-01T00:00:00Z.
    const KEY_CREATED: u64 = 1735689600;
    /// One day in seconds, the lifetime `1d` states.
    const ONE_DAY: u64 = 24 * 60 * 60;
    /// Ten years in seconds, as `gpg` counts a year at 365 days.
    const TEN_YEARS: u64 = 10 * 365 * ONE_DAY;

    /// The certificates a verifier loads a keyring blob into.
    fn certs_of(keyring: &[u8]) -> Vec<SignedPublicKey> {
        std::sync::Arc::unwrap_or_clone(GpgVerifier::from_keyring_bytes([keyring]).unwrap().certs)
    }

    /// Split an OpenPGP packet stream into (tag, body) pairs. Both packet
    /// header formats are read, since `gpg` writes the old one and the `pgp`
    /// crate writes the new one.
    fn split_packets(bytes: &[u8]) -> Vec<(u8, Vec<u8>)> {
        let mut out = Vec::new();
        let mut i = 0;
        while i < bytes.len() {
            let ctb = bytes[i];
            assert_eq!(ctb & 0x80, 0x80, "a packet tag byte at offset {i}");
            let (tag, len, header) = if ctb & 0x40 == 0 {
                let tag = (ctb >> 2) & 0x0f;
                match ctb & 0x03 {
                    0 => (tag, usize::from(bytes[i + 1]), 2),
                    1 => (
                        tag,
                        usize::from(u16::from_be_bytes([bytes[i + 1], bytes[i + 2]])),
                        3,
                    ),
                    other => panic!("packet length type {other}"),
                }
            } else {
                let tag = ctb & 0x3f;
                match bytes[i + 1] {
                    first @ 0..=191 => (tag, usize::from(first), 2),
                    first @ 192..=223 => (
                        tag,
                        ((usize::from(first) - 192) << 8) + usize::from(bytes[i + 2]) + 192,
                        3,
                    ),
                    other => panic!("packet length octet {other}"),
                }
            };
            out.push((tag, bytes[i + header..i + header + len].to_vec()));
            i += header + len;
        }
        out
    }

    /// Write (tag, body) pairs back as an OpenPGP packet stream, in the
    /// old header format `gpg` writes.
    fn join_packets(packets: &[(u8, Vec<u8>)]) -> Vec<u8> {
        let mut out = Vec::new();
        for (tag, body) in packets {
            assert!(*tag < 16, "tag {tag} needs the new header format");
            if body.len() < 256 {
                out.push(0x80 | (tag << 2));
                out.push(body.len() as u8);
            } else {
                out.push(0x80 | (tag << 2) | 1);
                out.extend_from_slice(&(u16::try_from(body.len()).unwrap()).to_be_bytes());
            }
            out.extend_from_slice(body);
        }
        out
    }

    /// Remove the embedded primary-key binding signature -- unhashed
    /// subpacket 32 -- from every subkey binding signature a certificate
    /// carries. The subpacket stands in the unhashed area, so the binding
    /// signature still verifies over what is left, which is what makes the
    /// certificate the shape a stapled subkey has: a binding the primary key
    /// made and no back-signature under it.
    fn strip_backsig(cert: &[u8]) -> Vec<u8> {
        let mut packets = split_packets(cert);
        let mut stripped = 0;
        for (tag, body) in &mut packets {
            if *tag != 2 || body[1] != 0x18 {
                continue;
            }
            let hashed = usize::from(u16::from_be_bytes([body[4], body[5]]));
            let start = 6 + hashed;
            let len = usize::from(u16::from_be_bytes([body[start], body[start + 1]]));
            let area = &body[start + 2..start + 2 + len];
            let mut kept: Vec<u8> = Vec::new();
            let mut i = 0;
            while i < area.len() {
                let (subpacket, header) = match area[i] {
                    first @ 0..=191 => (usize::from(first), 1),
                    first @ 192..=254 => (
                        ((usize::from(first) - 192) << 8) + usize::from(area[i + 1]) + 192,
                        2,
                    ),
                    other => panic!("subpacket length octet {other}"),
                };
                let whole = header + subpacket;
                if area[i + header] & 0x7f == 32 {
                    stripped += 1;
                } else {
                    kept.extend_from_slice(&area[i..i + whole]);
                }
                i += whole;
            }
            let mut new = body[..start].to_vec();
            new.extend_from_slice(&(u16::try_from(kept.len()).unwrap()).to_be_bytes());
            new.extend_from_slice(&kept);
            new.extend_from_slice(&body[start + 2 + len..]);
            *body = new;
        }
        assert_eq!(stripped, 1, "one back-signature was removed");
        join_packets(&packets)
    }

    /// Flip the last byte of the embedded primary-key binding signature --
    /// unhashed subpacket 32 -- in every subkey binding signature a certificate
    /// carries, so that the back-signature stands and verifies against nothing.
    /// The subpacket stands in the unhashed area, so the binding signature
    /// still verifies, which is the shape an attacker who holds no subkey
    /// secret can build over a genuine binding.
    fn alter_backsig(cert: &[u8]) -> Vec<u8> {
        let mut packets = split_packets(cert);
        let mut altered = 0;
        for (tag, body) in &mut packets {
            if *tag != 2 || body[1] != 0x18 {
                continue;
            }
            let hashed = usize::from(u16::from_be_bytes([body[4], body[5]]));
            let start = 6 + hashed;
            let len = usize::from(u16::from_be_bytes([body[start], body[start + 1]]));
            let area = start + 2;
            let mut i = 0;
            while i < len {
                let at = area + i;
                let (subpacket, header) = match body[at] {
                    first @ 0..=191 => (usize::from(first), 1),
                    first @ 192..=254 => (
                        ((usize::from(first) - 192) << 8) + usize::from(body[at + 1]) + 192,
                        2,
                    ),
                    other => panic!("subpacket length octet {other}"),
                };
                let whole = header + subpacket;
                if body[at + header] & 0x7f == 32 {
                    let last = at + whole - 1;
                    body[last] ^= 0xff;
                    altered += 1;
                }
                i += whole;
            }
        }
        assert_eq!(altered, 1, "one back-signature was altered");
        join_packets(&packets)
    }

    /// Splice one packet in right after a certificate's primary key packet,
    /// where a direct-key signature and a key revocation signature stand.
    fn insert_after_primary(cert: &[u8], packet: &[u8]) -> Vec<u8> {
        let mut packets = split_packets(cert);
        assert_eq!(packets[0].0, 6, "the first packet is the primary key");
        let mut inserted = split_packets(packet);
        assert_eq!(inserted.len(), 1);
        packets.insert(1, inserted.remove(0));
        join_packets(&packets)
    }

    /// Staple a revocation-key subpacket naming the key `revoker` names, as
    /// uppercase hex, into the unhashed area of the one certification
    /// self-signature a certificate carries.
    ///
    /// The unhashed area stands outside the bytes the signature covers, so the
    /// self-signature still verifies over what it covered before. This is the
    /// shape anyone who holds no key of the certificate can build: the
    /// designation is stapled on and the certificate still parses and
    /// verifies.
    fn staple_revocation_key(cert: &[u8], revoker: &str) -> Vec<u8> {
        let fingerprint: Vec<u8> = (0..revoker.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&revoker[i..i + 2], 16).unwrap())
            .collect();
        assert_eq!(fingerprint.len(), 20, "a version 4 key fingerprint");
        // Signature subpacket 12 carries a class octet and a public-key
        // algorithm octet ahead of the fingerprint. Class 0x80 and algorithm
        // 22 are what `gpg` writes for an ed25519 revoker.
        let mut body = vec![12, 0x80, 22];
        body.extend_from_slice(&fingerprint);
        let mut subpacket = vec![u8::try_from(body.len()).unwrap()];
        subpacket.extend_from_slice(&body);

        let mut packets = split_packets(cert);
        let mut stapled = 0;
        for (tag, body) in &mut packets {
            if *tag != 2 || body[0] != 4 || body[1] != 0x13 {
                continue;
            }
            let hashed = usize::from(u16::from_be_bytes([body[4], body[5]]));
            let start = 6 + hashed;
            let len = usize::from(u16::from_be_bytes([body[start], body[start + 1]]));
            let mut new = body[..start].to_vec();
            new.extend_from_slice(&(u16::try_from(len + subpacket.len()).unwrap()).to_be_bytes());
            new.extend_from_slice(&body[start + 2..start + 2 + len]);
            new.extend_from_slice(&subpacket);
            new.extend_from_slice(&body[start + 2 + len..]);
            *body = new;
            stapled += 1;
        }
        assert_eq!(stapled, 1, "one designation was stapled");
        join_packets(&packets)
    }

    /// The key revocation signature packet a certificate carries, as a stream
    /// of one packet.
    fn key_revocation_packet(cert: &[u8]) -> Vec<u8> {
        let packets = split_packets(cert);
        let found = packets
            .iter()
            .find(|(tag, body)| *tag == 2 && body[0] == 4 && body[1] == 0x20)
            .expect("a key revocation signature packet");
        join_packets(std::slice::from_ref(found))
    }

    /// Attach the first subkey of `donor`, with the binding signature it
    /// carries there, to the end of `host`.
    fn attach_subkey(host: &[u8], donor: &[u8]) -> Vec<u8> {
        let donor = split_packets(donor);
        let at = donor
            .iter()
            .position(|(tag, _)| *tag == 14)
            .expect("the donor holds a subkey");
        assert_eq!(donor[at + 1].0, 2, "the binding signature follows it");
        let mut packets = split_packets(host);
        packets.push(donor[at].clone());
        packets.push(donor[at + 1].clone());
        join_packets(&packets)
    }

    /// The first subkey of a certificate as a certificate of its own: the
    /// Public-Subkey packet (tag 14) written as a Public-Key packet (tag 6),
    /// with no signature under it.
    ///
    /// A v4 key fingerprint is over the key material, so the certificate this
    /// builds holds the key the subkey is and answers for the same issuer. It
    /// is the shape a certificate carrying a key and nothing else takes, which
    /// the keyring parser reads.
    fn subkey_as_certificate(cert: &[u8]) -> Vec<u8> {
        let packets = split_packets(cert);
        let (_, body) = packets
            .iter()
            .find(|(tag, _)| *tag == 14)
            .expect("the certificate holds a subkey");
        join_packets(&[(6, body.clone())])
    }

    /// Remove one user id, and the signatures that stand under it, from a
    /// certificate.
    fn remove_user_id(cert: &[u8], id: &str) -> Vec<u8> {
        let packets = split_packets(cert);
        let at = packets
            .iter()
            .position(|(tag, body)| *tag == 13 && body == id.as_bytes())
            .expect("the certificate holds the user id");
        let mut end = at + 1;
        while end < packets.len() && packets[end].0 == 2 {
            end += 1;
        }
        let mut kept = packets[..at].to_vec();
        kept.extend_from_slice(&packets[end..]);
        join_packets(&kept)
    }

    /// What one self-signature the cases build states about itself.
    ///
    /// `gpg` 2.4.9 writes no signature expiration time into a self-signature,
    /// and it writes the key expiration time into the certification
    /// self-signature alone, so every state that needs another combination is
    /// built here with the `pgp` crate, over the secret key the same GnuPG
    /// home exported.
    #[derive(Clone, Copy)]
    struct SelfSig {
        /// The instant the signature was made.
        created: u64,
        /// The key lifetime signature subpacket 9 states, in seconds after the
        /// key creation time. Absent where the signature carries no such
        /// subpacket.
        key_lifetime: Option<u64>,
        /// The signature lifetime signature subpacket 3 states, in seconds
        /// after the signature creation time. Absent where the signature
        /// carries no such subpacket.
        sig_lifetime: Option<u64>,
        /// Whether the signature marks the user id it stands over primary.
        marks_primary: bool,
    }

    impl SelfSig {
        /// A self-signature made at `created` that states nothing else.
        fn at(created: u64) -> SelfSig {
            SelfSig {
                created,
                key_lifetime: None,
                sig_lifetime: None,
                marks_primary: false,
            }
        }

        /// The same, stating the key lifetime `lifetime` where one is given.
        fn key_lifetime(self, lifetime: Option<u64>) -> SelfSig {
            SelfSig {
                key_lifetime: lifetime,
                ..self
            }
        }

        /// The same, expiring `lifetime` seconds after it was made.
        fn expiring_after(self, lifetime: u64) -> SelfSig {
            SelfSig {
                sig_lifetime: Some(lifetime),
                ..self
            }
        }

        /// The same, marking the user id it stands over primary.
        fn marking_primary(self) -> SelfSig {
            SelfSig {
                marks_primary: true,
                ..self
            }
        }
    }

    /// The hashed subpackets a self-signature `spec` describes carries: the
    /// creation time, the issuer fingerprint, and the subpackets `spec` states.
    fn self_signature_subpackets<K: pgp::types::KeyDetails>(
        spec: SelfSig,
        public: &K,
    ) -> Vec<pgp::packet::Subpacket> {
        use pgp::packet::{Subpacket, SubpacketData};
        use pgp::types::Duration;

        let mut hashed = vec![
            Subpacket::regular(SubpacketData::SignatureCreationTime(Timestamp::from_secs(
                u32::try_from(spec.created).unwrap(),
            )))
            .unwrap(),
            Subpacket::regular(SubpacketData::IssuerFingerprint(public.fingerprint())).unwrap(),
        ];
        if let Some(lifetime) = spec.key_lifetime {
            hashed.push(
                Subpacket::regular(SubpacketData::KeyExpirationTime(Duration::from_secs(
                    u32::try_from(lifetime).unwrap(),
                )))
                .unwrap(),
            );
        }
        if let Some(lifetime) = spec.sig_lifetime {
            hashed.push(
                Subpacket::regular(SubpacketData::SignatureExpirationTime(Duration::from_secs(
                    u32::try_from(lifetime).unwrap(),
                )))
                .unwrap(),
            );
        }
        if spec.marks_primary {
            hashed.push(Subpacket::regular(SubpacketData::IsPrimary(true)).unwrap());
        }
        hashed
    }

    /// A direct-key self-signature (type 0x1F) over a primary key, as `spec`
    /// states it.
    fn direct_self_signature(secret: &[u8], spec: SelfSig) -> Vec<u8> {
        use pgp::packet::{PacketTrait, SignatureConfig, Subpacket, SubpacketData};
        use pgp::types::Password;

        let secret_key = pgp::composed::SignedSecretKey::from_bytes(Cursor::new(secret)).unwrap();
        let public = secret_key.primary_key.public_key();
        let mut config = SignatureConfig::v4(
            SignatureType::Key,
            PublicKeyAlgorithm::EdDSALegacy,
            HashAlgorithm::Sha512,
        );
        config.hashed_subpackets = self_signature_subpackets(spec, &public);
        config.unhashed_subpackets =
            vec![Subpacket::regular(SubpacketData::IssuerKeyId(public.legacy_key_id())).unwrap()];
        let signature = config
            .sign_key(&secret_key.primary_key, &Password::empty(), public)
            .unwrap();
        let mut bytes = Vec::new();
        signature.to_writer_with_header(&mut bytes).unwrap();
        bytes
    }

    /// A certification self-signature (type 0x13) over the certificate's first
    /// user id, as `spec` states it.
    fn certification_self_signature(secret: &[u8], spec: SelfSig) -> Vec<u8> {
        use pgp::packet::{PacketTrait, SignatureConfig, Subpacket, SubpacketData};
        use pgp::types::Password;

        let secret_key = pgp::composed::SignedSecretKey::from_bytes(Cursor::new(secret)).unwrap();
        let public = secret_key.primary_key.public_key();
        let user = &secret_key.details.users[0];
        let mut config = SignatureConfig::v4(
            SignatureType::CertPositive,
            PublicKeyAlgorithm::EdDSALegacy,
            HashAlgorithm::Sha512,
        );
        config.hashed_subpackets = self_signature_subpackets(spec, &public);
        config.unhashed_subpackets =
            vec![Subpacket::regular(SubpacketData::IssuerKeyId(public.legacy_key_id())).unwrap()];
        let signature = config
            .sign_certification(
                &secret_key.primary_key,
                &public,
                &Password::empty(),
                Tag::UserId,
                &user.id,
            )
            .unwrap();
        let mut bytes = Vec::new();
        signature.to_writer_with_header(&mut bytes).unwrap();
        bytes
    }

    /// A subkey binding signature (type 0x18) the primary key makes over the
    /// certificate's first subkey, created at `created`, carrying the
    /// signing key flag, the back-signature the subkey makes, and the
    /// signature lifetime `sig_lifetime` where one is given.
    fn subkey_binding_signature(secret: &[u8], created: u64, sig_lifetime: Option<u64>) -> Vec<u8> {
        use pgp::packet::{KeyFlags, PacketTrait, SignatureConfig, Subpacket, SubpacketData};
        use pgp::types::Password;

        let secret_key = pgp::composed::SignedSecretKey::from_bytes(Cursor::new(secret)).unwrap();
        let primary = secret_key.primary_key.public_key();
        let sub = &secret_key.secret_subkeys[0];
        let sub_public = sub.key.public_key();

        let mut back = SignatureConfig::v4(
            SignatureType::KeyBinding,
            PublicKeyAlgorithm::EdDSALegacy,
            HashAlgorithm::Sha512,
        );
        back.hashed_subpackets = self_signature_subpackets(SelfSig::at(created), &sub_public);
        back.unhashed_subpackets = vec![
            Subpacket::regular(SubpacketData::IssuerKeyId(sub_public.legacy_key_id())).unwrap(),
        ];
        let back = back
            .sign_primary_key_binding(&sub.key, &sub_public, &Password::empty(), &primary)
            .unwrap();

        let mut flags = KeyFlags::default();
        flags.set_sign(true);
        let mut config = SignatureConfig::v4(
            SignatureType::SubkeyBinding,
            PublicKeyAlgorithm::EdDSALegacy,
            HashAlgorithm::Sha512,
        );
        let spec = SelfSig::at(created);
        config.hashed_subpackets = self_signature_subpackets(
            match sig_lifetime {
                Some(lifetime) => spec.expiring_after(lifetime),
                None => spec,
            },
            &primary,
        );
        config
            .hashed_subpackets
            .push(Subpacket::regular(SubpacketData::KeyFlags(flags)).unwrap());
        config.unhashed_subpackets = vec![
            Subpacket::regular(SubpacketData::IssuerKeyId(primary.legacy_key_id())).unwrap(),
            Subpacket::regular(SubpacketData::EmbeddedSignature(Box::new(back))).unwrap(),
        ];
        let signature = config
            .sign_subkey_binding(
                &secret_key.primary_key,
                &primary,
                &Password::empty(),
                &sub_public,
            )
            .unwrap();
        let mut bytes = Vec::new();
        signature.to_writer_with_header(&mut bytes).unwrap();
        bytes
    }

    /// Replace the one subkey binding signature a certificate carries with
    /// `packet`.
    fn replace_subkey_binding(cert: &[u8], packet: &[u8]) -> Vec<u8> {
        let mut inserted = split_packets(packet);
        assert_eq!(inserted.len(), 1);
        let replacement = inserted.remove(0);
        let mut out: Vec<(u8, Vec<u8>)> = Vec::new();
        let mut replaced = 0;
        for (tag, body) in split_packets(cert) {
            if tag == 2 && body[0] == 4 && body[1] == 0x18 {
                out.push(replacement.clone());
                replaced += 1;
            } else {
                out.push((tag, body));
            }
        }
        assert_eq!(replaced, 1, "one binding signature was replaced");
        join_packets(&out)
    }

    /// Insert one packet right after the signatures that stand under the user
    /// id `id`, which is where a certification over that user id belongs.
    fn insert_after_user_id(cert: &[u8], id: &str, packet: &[u8]) -> Vec<u8> {
        let packets = split_packets(cert);
        let at = packets
            .iter()
            .position(|(tag, body)| *tag == 13 && body == id.as_bytes())
            .expect("the certificate holds the user id");
        let mut end = at + 1;
        while end < packets.len() && packets[end].0 == 2 {
            end += 1;
        }
        let mut inserted = split_packets(packet);
        assert_eq!(inserted.len(), 1);
        let mut out = packets[..end].to_vec();
        out.push(inserted.remove(0));
        out.extend_from_slice(&packets[end..]);
        join_packets(&out)
    }

    /// A direct-key self-signature created at `created` and stating the key
    /// lifetime `lifetime`.
    fn direct_key_signature(secret: &[u8], created: u64, lifetime: u64) -> Vec<u8> {
        direct_self_signature(secret, SelfSig::at(created).key_lifetime(Some(lifetime)))
    }

    /// A signature by a primary key is valid where the key is live, is not
    /// revoked, and the digest is allowed.
    #[test]
    fn good_primary_key_signature_is_valid() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Good <good@ostrya.example>");
        let keyring = home.keyring();
        let blob = home.sign(&home.primary, PAYLOAD);
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(reference[0].valid);
        assert!(outcome.signatures[0].valid);
        assert!(outcome.valid);
        assert!(!outcome.signatures[0].expired);
        assert!(!outcome.signatures[0].revoked);
        assert_eq!(outcome.signatures[0].key_expires, None);
    }

    /// A signature by a signing subkey is valid where the binding signature
    /// the primary key made carries the back-signature the subkey made.
    #[test]
    fn cross_certified_subkey_signature_is_valid() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Cross <cross@ostrya.example>");
        let subkey = home.add_signing_subkey();
        let keyring = home.keyring();
        let blob = home.sign(&subkey, PAYLOAD);
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(reference[0].valid);
        assert!(outcome.signatures[0].valid);
        assert_eq!(outcome.signatures[0].fingerprint.as_deref(), Some(&*subkey));
    }

    /// A subkey stapled onto a certificate signs for nothing. Three shapes
    /// state it: a binding signature the primary key made with the
    /// back-signature removed, the same binding with a back-signature that
    /// stands and verifies against nothing, and a subkey taken from another
    /// certificate together with the binding it carried there. The first two
    /// are what an attacker who holds no subkey secret can produce.
    #[test]
    fn stapled_subkey_is_refused() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Staple <staple@ostrya.example>");
        let subkey = home.add_signing_subkey();
        let whole = home.keyring();
        let blob = home.sign(&subkey, PAYLOAD);
        // The intact certificate is the control: the same signature verifies.
        let control =
            verify_signatures(&certs_of(&whole), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        assert!(control.valid);

        let stripped = strip_backsig(&whole);
        let outcome =
            verify_signatures(&certs_of(&stripped), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&stripped, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(!info.valid);
        assert!(!outcome.valid);
        // The binding signature still verifies, so the subkey is a key the
        // certificate holds; the back-signature is what is missing.
        assert!(!info.key_missing);
        assert_eq!(info.fingerprint.as_deref(), Some(&*subkey));
        assert_eq!(info.user_name, None);

        // The back-signature is present and verifies against nothing. The
        // binding signature still verifies, since the subpacket stands in its
        // unhashed area, so presence alone must not answer for it.
        let bad = alter_backsig(&whole);
        let outcome =
            verify_signatures(&certs_of(&bad), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&bad, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(!outcome.valid);
        assert!(!outcome.signatures[0].key_missing);
        assert_eq!(outcome.signatures[0].fingerprint.as_deref(), Some(&*subkey));
        assert_eq!(outcome.signatures[0].user_name, None);

        // The same subkey attached to another certificate, with the binding
        // signature it carried. The binding does not verify under the other
        // primary key, so the subkey belongs to no loaded certificate.
        let other = Fixture::new("Host <host@ostrya.example>");
        let attached = attach_subkey(&other.keyring(), &whole);
        let outcome =
            verify_signatures(&certs_of(&attached), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = other.gpgv_records(&attached, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(!outcome.valid);
        assert!(outcome.signatures[0].key_missing);
        assert_eq!(
            outcome.signatures[0].fingerprint.as_deref(),
            Some(&*subkey),
            "the fingerprint the signature packet names"
        );
    }

    /// An expired key states the instant it expired and is not valid. The
    /// instant is the key creation time plus the lifetime the self-signature
    /// states.
    #[test]
    fn expired_key_agrees_with_gpgv() {
        if !tools_available() {
            return;
        }
        let home = Fixture::at("Old <old@ostrya.example>", "1d");
        let keyring = home.keyring();
        let blob = home.sign(&home.primary, PAYLOAD);
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(info.expired);
        assert!(!info.valid);
        assert!(!outcome.valid);
        assert_eq!(info.key_expires, Some(KEY_CREATED + ONE_DAY));
        assert_eq!(reference[0].key_expires, Some(KEY_CREATED + ONE_DAY));
        // The signature was made while the key was live, and the key state is
        // read against the current clock, not against that instant.
        assert_eq!(info.created, Some(KEY_CREATED));
    }

    /// A signing subkey does not outlive its certificate. The primary key
    /// below expired and the subkey's binding signature states no expiry of
    /// its own, and `gpgv` reports the primary key's instant.
    #[test]
    fn expired_primary_key_expires_its_subkey() {
        if !tools_available() {
            return;
        }
        let home = Fixture::at("Both <both@ostrya.example>", "1d");
        let subkey = home.add_signing_subkey();
        let keyring = home.keyring();
        let blob = home.sign(&subkey, PAYLOAD);
        let outcome =
            verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(info.expired);
        assert!(!info.valid);
        assert_eq!(info.key_expires, Some(KEY_CREATED + ONE_DAY));
        assert_eq!(info.fingerprint.as_deref(), Some(&*subkey));

        // A subkey that states a lifetime of its own does not outlive the
        // certificate either: the earlier of the two instants answers.
        let later = Fixture::at("Later <later@ostrya.example>", "1d");
        let subkey = later.add_signing_subkey_expiring("10y");
        let keyring = later.keyring();
        let blob = later.sign(&subkey, PAYLOAD);
        let outcome =
            verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = later.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(outcome.signatures[0].expired);
        assert_eq!(
            outcome.signatures[0].key_expires,
            Some(KEY_CREATED + ONE_DAY)
        );
    }

    /// A key expiration time of zero on a direct-key self-signature states no
    /// lifetime, so the certification self-signature answers. The certificate
    /// below states one day there, which has passed, and the direct-key
    /// signature states zero; `gpgv` reports the expiry the one day names.
    #[test]
    fn zero_direct_key_expiration_reads_as_absent() {
        if !tools_available() {
            return;
        }
        let home = Fixture::at("Zero <zero@ostrya.example>", "1d");
        let blob = home.sign(&home.primary, PAYLOAD);
        let secret = home.secret_key();
        let keyring = insert_after_primary(
            &home.keyring(),
            &direct_key_signature(&secret, KEY_CREATED + 10, 0),
        );
        let outcome =
            verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(!info.valid);
        assert!(info.expired);
        assert_eq!(info.key_expires, Some(KEY_CREATED + ONE_DAY));
        // The control states that the direct-key signature is read at all: the
        // same signature stating ten years makes the same key live.
        let live = insert_after_primary(
            &home.keyring(),
            &direct_key_signature(&secret, KEY_CREATED + 10, TEN_YEARS),
        );
        let outcome =
            verify_signatures(&certs_of(&live), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&live, &blob, PAYLOAD);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(outcome.signatures[0].valid);
        assert_eq!(outcome.signatures[0].key_expires, None);
    }

    /// The key expiration time of a primary key comes from the direct-key
    /// self-signature where the certificate carries one that verifies, and
    /// from the certification self-signature otherwise. The three states below
    /// are what `gpgv` answers over the same three certificates.
    #[test]
    fn direct_key_signature_states_the_key_expiry() {
        if !tools_available() {
            return;
        }
        // The certification self-signature states one day, which has passed,
        // and the direct-key signature states ten years.
        let home = Fixture::at("Live <live@ostrya.example>", "1d");
        let blob = home.sign(&home.primary, PAYLOAD);
        let secret = home.secret_key();
        let keyring = insert_after_primary(
            &home.keyring(),
            &direct_key_signature(&secret, KEY_CREATED + 10, TEN_YEARS),
        );
        let outcome =
            verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(
            outcome.signatures[0].valid,
            "the direct-key signature is read"
        );
        assert_eq!(outcome.signatures[0].key_expires, None);

        // A direct-key signature whose bytes were altered verifies against
        // nothing and is passed over, so the certification self-signature
        // answers and the key is expired.
        let mut altered = direct_key_signature(&secret, KEY_CREATED + 10, TEN_YEARS);
        let last = altered.len() - 1;
        altered[last] ^= 0xff;
        let keyring = insert_after_primary(&home.keyring(), &altered);
        let outcome =
            verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(outcome.signatures[0].expired);
        assert_eq!(
            outcome.signatures[0].key_expires,
            Some(KEY_CREATED + ONE_DAY)
        );

        // The certification self-signature states ten years and the direct-key
        // signature states one day, so the key is expired.
        let live = Fixture::at("Dead <dead@ostrya.example>", "10y");
        let blob = live.sign(&live.primary, PAYLOAD);
        let keyring = insert_after_primary(
            &live.keyring(),
            &direct_key_signature(&live.secret_key(), KEY_CREATED + 10, ONE_DAY),
        );
        let outcome =
            verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = live.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(outcome.signatures[0].expired);
        assert!(!outcome.signatures[0].valid);
        assert_eq!(
            outcome.signatures[0].key_expires,
            Some(KEY_CREATED + ONE_DAY)
        );
    }

    /// A revoked primary key is reported revoked and is not valid.
    #[test]
    fn revoked_primary_key_agrees_with_gpgv() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Gone <gone@ostrya.example>");
        let blob = home.sign(&home.primary, PAYLOAD);
        home.revoke_primary();
        let keyring = home.keyring();
        let outcome =
            verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(info.revoked);
        assert!(!info.valid);
        assert!(!outcome.valid);
        // The record still names the key and the user id, which is what the
        // `REVKEYSIG` and `VALIDSIG` pair carries.
        assert_eq!(info.fingerprint.as_deref(), Some(&*home.primary));
        assert_eq!(info.user_email.as_deref(), Some("gone@ostrya.example"));
    }

    /// A revoked signing subkey is reported revoked and is not valid, and its
    /// certificate's primary key is not.
    #[test]
    fn revoked_subkey_agrees_with_gpgv() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("SubGone <subgone@ostrya.example>");
        let subkey = home.add_signing_subkey();
        let by_subkey = home.sign(&subkey, PAYLOAD);
        let by_primary = home.sign(&home.primary, PAYLOAD);
        home.revoke_subkey();
        let keyring = home.keyring();
        let outcome = verify_signatures(
            &certs_of(&keyring),
            PAYLOAD,
            std::slice::from_ref(&by_subkey),
        )
        .unwrap();
        let reference = home.gpgv_records(&keyring, &by_subkey, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(info.revoked);
        assert!(!info.valid);
        assert_eq!(info.fingerprint.as_deref(), Some(&*subkey));
        // The revocation stands over the subkey alone.
        let outcome = verify_signatures(
            &certs_of(&keyring),
            PAYLOAD,
            std::slice::from_ref(&by_primary),
        )
        .unwrap();
        let reference = home.gpgv_records(&keyring, &by_primary, PAYLOAD);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(outcome.signatures[0].valid);
        assert!(!outcome.signatures[0].revoked);
    }

    /// A revoked user id leaves the signature valid and sets no field of its
    /// own. The user id the record names is one that is not revoked, and the
    /// primary-user-id subpacket on a revoked user id counts for nothing.
    /// Where every user id is revoked, a revoked one is named.
    #[test]
    fn revoked_user_id_agrees_with_gpgv() {
        if !tools_available() {
            return;
        }
        const ALPHA: &str = "Alpha <alpha@ostrya.example>";
        const BRAVO: &str = "Bravo <bravo@ostrya.example>";
        let home = Fixture::new(ALPHA);
        home.add_uid(BRAVO);
        home.set_primary_uid(ALPHA);
        home.revoke_uid(ALPHA);
        let keyring = home.keyring();
        let blob = home.sign(&home.primary, PAYLOAD);
        let outcome =
            verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(info.valid);
        assert!(!info.revoked);
        assert_eq!(info.user_email.as_deref(), Some("bravo@ostrya.example"));

        // `gpg` refuses to revoke the last valid user id, so the state where
        // every user id is revoked is reached by removing the other one.
        let alone = remove_user_id(&keyring, BRAVO);
        let outcome =
            verify_signatures(&certs_of(&alone), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&alone, &blob, PAYLOAD);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(outcome.signatures[0].valid);
        assert_eq!(
            outcome.signatures[0].user_email.as_deref(),
            Some("alpha@ostrya.example")
        );
    }

    /// An MD5 data signature is refused. The port and `gpgv` 2.4.9 agree here,
    /// and the port parts from the cryptography under it: rPGP verifies an MD5
    /// signature as good, so the refusal is the port's own policy. GnuPG's
    /// digest policy is configurable and moves between versions, so the port
    /// states its own and the divergence to record is that class rather than a
    /// version number.
    #[test]
    fn md5_data_signature_is_refused() {
        if !tools_available() {
            return;
        }
        let home = Fixture::rsa("Md5 <md5@ostrya.example>");
        let keyring = home.keyring();
        let blob = home.sign_with(&home.primary, PAYLOAD, &["--digest-algo", "MD5"]);
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(!info.valid);
        assert!(!outcome.valid);
        assert_eq!(info.hash_algorithm.as_deref(), Some("MD5"));
        // The digest answered before the key did, so the record carries the
        // signature packet's own fields and no user id, and the key it names
        // is in the keyring.
        assert!(!info.key_missing);
        assert_eq!(info.fingerprint.as_deref(), Some(&*home.primary));
        assert_eq!(info.user_name, None);
        // The same key over the same payload with an allowed digest is valid,
        // so the digest policy is what refused this signature and not the
        // cryptography under it.
        let allowed = home.sign(&home.primary, PAYLOAD);
        let outcome = verify_signatures(&home.certs(), PAYLOAD, &[allowed]).unwrap();
        assert!(outcome.valid);
    }

    /// A SHA-1 data signature is accepted. The port and `gpgv` 2.4.9 agree.
    /// The key is RSA, because rPGP holds a rule of its own over an Ed25519
    /// key: a digest under 256 bits "is too weak for Ed25519", so a SHA-1
    /// signature by an Ed25519 key verifies against nothing. That is a
    /// divergence from `gpgv`, which reports `GOODSIG`, and the case below
    /// states it.
    #[test]
    fn sha1_data_signature_is_accepted() {
        if !tools_available() {
            return;
        }
        let home = Fixture::rsa("Sha1 <sha1@ostrya.example>");
        let keyring = home.keyring();
        let blob = home.sign_with(&home.primary, PAYLOAD, &["--digest-algo", "SHA1"]);
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(reference[0].valid);
        assert!(outcome.signatures[0].valid);
        assert_eq!(
            outcome.signatures[0].hash_algorithm.as_deref(),
            Some("SHA1")
        );

        // The divergence, declared: the same digest with an Ed25519 key. The
        // reference accepts the signature and the port reports it as one that
        // verified against nothing, because rPGP refuses the digest for that
        // algorithm before any policy of the port is reached.
        let eddsa = Fixture::new("Ed <ed@ostrya.example>");
        let ring = eddsa.keyring();
        let blob = eddsa.sign_with(&eddsa.primary, PAYLOAD, &["--digest-algo", "SHA1"]);
        let outcome =
            verify_signatures(&eddsa.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = eddsa.gpgv_records(&ring, &blob, PAYLOAD);
        assert_eq!(reference.len(), 1);
        assert!(reference[0].valid, "the reference accepts it");
        assert!(!outcome.signatures[0].valid, "the port does not");
        // The record takes the shape a signature that verified against nothing
        // takes: the resolved signing key, its certificate, and the
        // certificate's user id. The primary key signed here, so both
        // fingerprints name it.
        assert_eq!(
            outcome.signatures[0].fingerprint.as_deref(),
            Some(&*eddsa.primary)
        );
        assert_eq!(
            outcome.signatures[0].primary_fingerprint.as_deref(),
            Some(&*eddsa.primary)
        );
        assert_eq!(
            outcome.signatures[0].user_email.as_deref(),
            Some("ed@ostrya.example")
        );
    }

    /// A key revocation signature another key made, stapled onto a
    /// certificate, revokes nothing. A revocation is verified before it is
    /// honored, so a packet anyone can attach carries no weight.
    #[test]
    fn a_stapled_revocation_does_not_revoke() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Keep <keep@ostrya.example>");
        let other = Fixture::new("Other <other@ostrya.example>");
        let blob = home.sign(&home.primary, PAYLOAD);
        let keyring = insert_after_primary(&home.keyring(), &other.revocation_packet());
        let certs = certs_of(&keyring);
        // The stapled packet reached the parsed certificate, so it is the
        // verification that refused it and not the parse.
        assert_eq!(certs.len(), 1);
        assert_eq!(certs[0].details.revocation_signatures.len(), 1);
        let outcome = verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(!outcome.signatures[0].revoked);
        assert!(outcome.signatures[0].valid);
        assert!(outcome.valid);
        // The same packet over the certificate it was made for revokes it.
        let own = other.keyring();
        let own_blob = other.sign(&other.primary, PAYLOAD);
        let revoked = insert_after_primary(&own, &other.revocation_packet());
        let outcome = verify_signatures(
            &certs_of(&revoked),
            PAYLOAD,
            std::slice::from_ref(&own_blob),
        )
        .unwrap();
        assert!(outcome.signatures[0].revoked);
        assert!(!outcome.valid);
    }

    /// The signature and the keyrings the designated-revoker cases stand on.
    ///
    /// Two keys are generated: the signing key, which makes the data
    /// signature, and the revoker, which the signing key designates through
    /// signature subpacket 12. `gpg --desig-revoke` writes the class 0x20
    /// revocation the revoker makes over the signing key, and the four
    /// keyrings below hold the states the cases read.
    struct Designated {
        /// The signing key's home. Its key made [`Designated::blob`] and its
        /// `gv` directory is the `--homedir` of every `gpgv` run.
        home: Fixture,
        /// The revoker's primary key fingerprint, uppercase hex.
        revoker: String,
        /// The revoker's exported certificate.
        revoker_cert: Vec<u8>,
        /// The detached signature the signing key made over [`PAYLOAD`].
        blob: Vec<u8>,
        /// The signing key carrying the designation, with the revocation the
        /// designated revoker made.
        designated: Vec<u8>,
        /// The same, with the revoker's certificate beside it.
        designated_with_revoker: Vec<u8>,
        /// The signing key carrying the same revocation and no designation.
        undesignated: Vec<u8>,
        /// The same, with the revoker's certificate beside it.
        undesignated_with_revoker: Vec<u8>,
    }

    impl Designated {
        fn build() -> Designated {
            let home = Fixture::new("Signing K <k@ostrya.example>");
            let revoker = Fixture::new("Revoker R <r@ostrya.example>");
            let blob = home.sign(&home.primary, PAYLOAD);
            let plain = home.export_keys(&[&home.primary]);
            let revoker_cert = revoker.export_keys(&[&revoker.primary]);
            // The designation names the revoker by fingerprint, so the signing
            // key's home holds the revoker's certificate while it writes the
            // self-signature that carries the designation.
            home.import(&revoker_cert);
            home.add_revoker(&revoker.primary);
            let designating = home.export_keys(&[&home.primary]);
            // The revocation is made in a home holding the revoker's secret
            // key and the certificate that designates it.
            revoker.import(&designating);
            let revocation = revoker.desig_revoke(&home.primary);

            // Each keyring is built the way the states were measured: a home
            // imports the certificates the state names and exports them.
            let with_designation = Fixture::bare();
            with_designation.import(&designating);
            with_designation.import_merging(&revocation);
            let designated = with_designation.export_keys(&[&home.primary]);
            let and_revoker = Fixture::bare();
            and_revoker.import(&designating);
            and_revoker.import_merging(&revocation);
            and_revoker.import(&revoker_cert);
            let designated_with_revoker =
                and_revoker.export_keys(&[&home.primary, &revoker.primary]);

            // An import of the revocation merges the self-signature that
            // carries the designation along with it, so the state holding the
            // revocation and no designation is spliced: the revocation packet
            // stands after the primary key packet of a certificate that
            // carries no subpacket 12.
            let undesignated = insert_after_primary(&plain, &key_revocation_packet(&designated));
            let undesignated_with_revoker = [&undesignated[..], &revoker_cert[..]].concat();
            Designated {
                home,
                revoker: revoker.primary.clone(),
                revoker_cert,
                blob,
                designated,
                designated_with_revoker,
                undesignated,
                undesignated_with_revoker,
            }
        }

        /// Assert that `keyring` holds `certs` certificates, that the first of
        /// them carries one key revocation signature, and that it names
        /// `designations` revokers. This states the shape each case reads, so
        /// a case fails where its fixture is not the state it names.
        fn assert_state(keyring: &[u8], certs: usize, designations: usize) -> Vec<SignedPublicKey> {
            let parsed = certs_of(keyring);
            assert_eq!(parsed.len(), certs, "the trusted set");
            assert_eq!(
                parsed[0].details.revocation_signatures.len(),
                1,
                "the key revocation signature reached the parsed certificate"
            );
            assert_eq!(
                designated_revokers(&parsed[0]).len(),
                designations,
                "the designations the certificate carries"
            );
            parsed
        }
    }

    /// A key revocation a designated revoker made is passed over where the
    /// revoker's certificate is absent from the trusted set, so the signature
    /// stands good. `gpgv` 2.4.9 answers the same way: over this keyring it
    /// reports `GOODSIG`, and it prints no `KEY_CONSIDERED` line for the
    /// revoker, so the revoker was not resolved.
    #[test]
    fn an_unloaded_designated_revoker_does_not_revoke() {
        if !tools_available() {
            return;
        }
        let state = Designated::build();
        let certs = Designated::assert_state(&state.designated, 1, 1);
        let outcome =
            verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&state.blob)).unwrap();
        let reference = state
            .home
            .gpgv_records(&state.designated, &state.blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(!outcome.signatures[0].revoked);
        assert!(outcome.signatures[0].valid);
        assert!(outcome.valid);
    }

    /// A key revocation a designated revoker made revokes the key where the
    /// revoker's certificate is loaded, so the signature is refused. `gpgv`
    /// 2.4.9 reports `REVKEYSIG` over this keyring.
    ///
    /// The keyring holds the same bytes for the signing key as the keyring
    /// the case above reads, so the revoker's certificate is the whole
    /// difference between the two states.
    #[test]
    fn a_loaded_designated_revoker_revokes_the_key() {
        if !tools_available() {
            return;
        }
        let state = Designated::build();
        assert_eq!(
            &state.designated_with_revoker[..state.designated.len()],
            &state.designated[..],
            "the keyring holds the signing key as the unloaded state holds it"
        );
        let certs = Designated::assert_state(&state.designated_with_revoker, 2, 1);
        assert_eq!(format!("{:X}", certs[1].fingerprint()), state.revoker);
        let outcome =
            verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&state.blob)).unwrap();
        let reference =
            state
                .home
                .gpgv_records(&state.designated_with_revoker, &state.blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(info.revoked);
        assert!(!info.valid);
        assert!(!outcome.valid);
        // The record still names the key and the user id, which is what the
        // `REVKEYSIG` and `VALIDSIG` pair carries.
        assert_eq!(
            info.fingerprint.as_deref(),
            Some(&*state.home.primary),
            "the signing key"
        );
        assert_eq!(info.user_email.as_deref(), Some("k@ostrya.example"));
    }

    /// The designation is what admits the revocation. The byte-identical
    /// revocation over a certificate that designates no revoker revokes
    /// nothing, whether the revoker's certificate is loaded or not, so the
    /// signature stands good. `gpgv` 2.4.9 reports `GOODSIG` over both
    /// keyrings.
    #[test]
    fn an_undesignated_revocation_does_not_revoke() {
        if !tools_available() {
            return;
        }
        let state = Designated::build();
        assert_eq!(
            key_revocation_packet(&state.undesignated),
            key_revocation_packet(&state.designated),
            "the two states carry the same revocation packet"
        );
        for (label, keyring, certs) in [
            ("the revoker absent", &state.undesignated, 1),
            ("the revoker loaded", &state.undesignated_with_revoker, 2),
        ] {
            let certs = Designated::assert_state(keyring, certs, 0);
            let outcome =
                verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&state.blob)).unwrap();
            let reference = state.home.gpgv_records(keyring, &state.blob, PAYLOAD);
            assert_eq!(outcome.signatures.len(), 1, "{label}");
            assert_eq!(reference.len(), 1, "{label}");
            assert_agrees(&outcome.signatures[0], &reference[0]);
            assert!(!outcome.signatures[0].revoked, "{label}");
            assert!(outcome.signatures[0].valid, "{label}");
            assert!(outcome.valid, "{label}");
        }
    }

    /// A designation the self-signature does not cover names no revoker. The
    /// unhashed subpacket area stands outside the bytes the signature covers,
    /// so anyone can staple a subpacket 12 onto a certificate and leave the
    /// self-signature verifying. The hashed area alone is read, so the
    /// revocation the named key made revokes nothing and the signature stands
    /// good. `gpgv` 2.4.9 answers the same way: over a keyring holding the
    /// revocation, the revoker's certificate, and the designation stapled into
    /// the unhashed area, it reports `GOODSIG`.
    #[test]
    fn a_stapled_designation_names_no_revoker() {
        if !tools_available() {
            return;
        }
        let state = Designated::build();
        let stapled = staple_revocation_key(&state.undesignated, &state.revoker);
        let keyring = [&stapled[..], &state.revoker_cert[..]].concat();
        let certs = Designated::assert_state(&keyring, 2, 0);
        assert_eq!(format!("{:X}", certs[1].fingerprint()), state.revoker);
        let outcome =
            verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&state.blob)).unwrap();
        let reference = state.home.gpgv_records(&keyring, &state.blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(!outcome.signatures[0].revoked);
        assert!(outcome.signatures[0].valid);
        assert!(outcome.valid);
    }

    /// A designation on a self-signature that does not verify names no
    /// revoker, so the revocation the designated revoker made revokes nothing
    /// and the signature stands good. `gpgv` 2.4.9 answers the same way: over
    /// the state that reports `REVKEYSIG`, with the last byte of the
    /// designating self-signature flipped, it reports `GOODSIG` and prints no
    /// `KEY_CONSIDERED` line for the revoker.
    #[test]
    fn an_unverified_designation_names_no_revoker() {
        if !tools_available() {
            return;
        }
        let state = Designated::build();
        // `gpg` writes the designation into a direct-key self-signature, which
        // is the one class 0x1f signature the state carries.
        let keyring = alter_signature(&state.designated_with_revoker, 0x1f);
        let certs = Designated::assert_state(&keyring, 2, 0);
        let outcome =
            verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&state.blob)).unwrap();
        let reference = state.home.gpgv_records(&keyring, &state.blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(!outcome.signatures[0].revoked);
        assert!(outcome.signatures[0].valid);
        assert!(outcome.valid);
    }

    /// A key that reaches the trusted set through two certificates, one of
    /// them revoked, is refused whichever order the two stand in.
    ///
    /// Two certificates for one key reach the trusted set on ordinary paths: a
    /// repository's `<remote>.trustedkeys.gpg` beside the global trusted
    /// directory, two `gpgkeypath` entries, or one keyring file holding two
    /// exports of one key. The verdict therefore reads every certificate that
    /// answers for the issuer, and a revocation any of them carries refuses
    /// the signature.
    ///
    /// `gpgv` 2.4.9 answers on the load order here, so the verdict is not
    /// compared against it: over the keyring whose unrevoked certificate
    /// stands first it reports `GOODSIG`, and over the reverse order
    /// `REVKEYSIG`. The engine reports the revocation in both. The case states
    /// what the reference answers, so it fails where the reference stops
    /// answering that way, and each certificate on its own is a control the
    /// two engines do agree on.
    #[test]
    fn a_revocation_on_a_duplicate_certificate_refuses_the_signature() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Dup <dup@ostrya.example>");
        let blob = home.sign(&home.primary, PAYLOAD);
        let unrevoked = home.keyring();
        home.revoke_primary();
        let revoked = home.keyring();
        for (label, keyring, is_revoked) in [
            ("the unrevoked certificate", &unrevoked, false),
            ("the revoked certificate", &revoked, true),
        ] {
            let certs = certs_of(keyring);
            assert_eq!(certs.len(), 1, "{label}: the trusted set");
            let outcome = verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&blob)).unwrap();
            let reference = home.gpgv_records(keyring, &blob, PAYLOAD);
            assert_eq!(outcome.signatures.len(), 1);
            assert_eq!(reference.len(), 1);
            assert_agrees(&outcome.signatures[0], &reference[0]);
            assert_eq!(outcome.signatures[0].revoked, is_revoked, "{label}");
            assert_eq!(outcome.signatures[0].valid, !is_revoked, "{label}");
        }
        for (label, first, second, reference_revoked) in [
            ("the revocation second", &unrevoked, &revoked, false),
            ("the revocation first", &revoked, &unrevoked, true),
        ] {
            let mut keyring = first.clone();
            keyring.extend_from_slice(second);
            let certs = certs_of(&keyring);
            // Both certificates reached the trusted set, so it is the verdict
            // that reads them and not the parse that dropped one.
            assert_eq!(certs.len(), 2, "{label}: the trusted set");
            let outcome = verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&blob)).unwrap();
            assert_eq!(outcome.signatures.len(), 1);
            let info = &outcome.signatures[0];
            assert!(info.revoked, "{label}: the revocation was not read");
            assert!(!info.valid, "{label}: a revoked key reported valid");
            assert!(!outcome.valid, "{label}: the outcome");
            // The fields the report names come from the first match, and the
            // two certificates state the same key and the same user id.
            assert_eq!(info.fingerprint.as_deref(), Some(&*home.primary), "{label}");
            assert_eq!(
                info.user_email.as_deref(),
                Some("dup@ostrya.example"),
                "{label}"
            );
            let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
            assert_eq!(reference.len(), 1, "{label}: the reference record count");
            assert_eq!(
                reference[0].revoked, reference_revoked,
                "{label}: gpgv no longer answers on the load order, so this \
                 case states the wrong thing about the reference",
            );
        }
    }

    /// Two exports of one certificate are read as one certificate, so the key
    /// expiry the newest self-signature of either export states answers,
    /// whichever order the two stand in.
    ///
    /// Two exports of one certificate reach the trusted set on ordinary paths:
    /// a repository's `<remote>.trustedkeys.gpg` beside the global trusted
    /// directory, two `gpgkeypath` entries, or one keyring file holding two
    /// exports of one key. An expiry is renewable, so an export the key's owner
    /// has replaced states a lifetime the newer export answers for.
    ///
    /// Each fixture's key was created at [`KEY_CREATED`]. The second export is
    /// written with `gpg` standing a day later, so its fresh self-signature
    /// carries a creation time of its own and stands as the newer statement.
    ///
    /// `gpgv` 2.4.9 answers on the load order here, so the verdict is not
    /// compared against it: it reads the first certificate its keyrings hold
    /// for the key. `gpg --import` merges the two exports into one keyblock and
    /// answers on the newest statement, which is the answer this engine reaches
    /// over the two exports in either order. Measured over the three pairs
    /// below, imported in both orders, `gpgv` reports `GOODSIG` over the merged
    /// keyring of the first two pairs and `EXPKEYSIG` over the third.
    #[test]
    fn a_duplicate_certificate_states_the_newest_expiry() {
        if !tools_available() {
            return;
        }
        /// One pair of exports of one certificate.
        struct Case {
            /// The lifetime the key was created with.
            created: &'static str,
            /// Whether that lifetime has passed.
            created_expired: bool,
            /// The lifetime the second export states, written a day later.
            replaced: &'static str,
            /// Whether that lifetime has passed.
            replaced_expired: bool,
            /// The instant the two exports together state the key expires at,
            /// absent where they leave it live.
            expires: Option<u64>,
        }
        let cases = [
            // An expiry already past, extended by ten years.
            Case {
                created: "1d",
                created_expired: true,
                replaced: "10y",
                replaced_expired: false,
                expires: None,
            },
            // The same expiry, lifted altogether.
            Case {
                created: "1d",
                created_expired: true,
                replaced: "never",
                replaced_expired: false,
                expires: None,
            },
            // A key that stated no expiry, given one that has passed. The
            // newest statement answers and not the widest one.
            Case {
                created: "never",
                created_expired: false,
                replaced: "1d",
                replaced_expired: true,
                expires: Some(KEY_CREATED + 2 * ONE_DAY),
            },
        ];
        for (index, case) in cases.iter().enumerate() {
            let email = format!("twice{index}@ostrya.example");
            let home = Fixture::at(&format!("Twice{index} <{email}>"), case.created);
            let blob = home.sign(&home.primary, PAYLOAD);
            let created = home.keyring();
            home.set_expire_at("20250102T000000!", case.replaced);
            let replaced = home.keyring();
            for (label, first, second, reference_expired) in [
                (
                    "the replacement second",
                    &created,
                    &replaced,
                    case.created_expired,
                ),
                (
                    "the replacement first",
                    &replaced,
                    &created,
                    case.replaced_expired,
                ),
            ] {
                let mut keyring = first.clone();
                keyring.extend_from_slice(second);
                let certs = certs_of(&keyring);
                assert_eq!(certs.len(), 2, "case {index}, {label}: the trusted set");
                let outcome =
                    verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&blob)).unwrap();
                assert_eq!(outcome.signatures.len(), 1);
                let info = &outcome.signatures[0];
                assert_eq!(
                    info.key_expires, case.expires,
                    "case {index}, {label}: the instant reported"
                );
                assert_eq!(
                    info.expired,
                    case.expires.is_some(),
                    "case {index}, {label}: the expired flag"
                );
                assert_eq!(
                    info.valid,
                    case.expires.is_none(),
                    "case {index}, {label}: the verdict"
                );
                // The fields the report names come from the first match, and
                // the two exports state the same key and the same user id.
                assert_eq!(
                    info.user_email.as_deref(),
                    Some(&*email),
                    "case {index}, {label}"
                );
                let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
                assert_eq!(
                    reference.len(),
                    1,
                    "case {index}, {label}: the reference record count"
                );
                assert_eq!(
                    reference[0].expired, reference_expired,
                    "case {index}, {label}: gpgv no longer answers on the load \
                     order, so this case states the wrong thing about the \
                     reference",
                );
            }
        }
    }

    /// The direct-key tier answers over two exports of one certificate: a
    /// direct-key self-signature one export carries states the key expiry where
    /// the other export carries a certification self-signature that stands
    /// newer and states another.
    ///
    /// The tier outranks recency inside one certificate, and it outranks it
    /// over the union of two exports of one certificate the same way. The
    /// direct-key self-signature here states ten years and the newer
    /// certification self-signature states a lifetime already past, so the
    /// union leaves the key live where each copy read on its own would bound
    /// it and where recency alone would bound it.
    ///
    /// `gpgv` 2.4.9 answers on the load order over the pair, so the verdict is
    /// not compared against it: over the keyring whose export carrying the
    /// direct-key self-signature stands first it reports `GOODSIG`, and over
    /// the reverse order `EXPKEYSIG`.
    #[test]
    fn the_direct_key_tier_answers_over_a_duplicate_certificate() {
        if !tools_available() {
            return;
        }
        let home = Fixture::at("Tier <tier@ostrya.example>", "10y");
        let blob = home.sign(&home.primary, PAYLOAD);
        // One export carries a direct-key self-signature stating ten years.
        let direct = insert_after_primary(
            &home.keyring(),
            &direct_key_signature(&home.secret_key(), KEY_CREATED + 10, TEN_YEARS),
        );
        // The other export carries a certification self-signature that stands
        // newer than that direct-key self-signature and states a lifetime
        // already past.
        home.set_expire_at("20250102T000000!", "1d");
        let bounded = home.keyring();
        // The controls: each export on its own states what the tiered rule
        // reads over it.
        let outcome =
            verify_signatures(&certs_of(&direct), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        assert!(
            outcome.signatures[0].valid,
            "the export carrying the direct-key self-signature leaves the key live"
        );
        let outcome =
            verify_signatures(&certs_of(&bounded), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        assert!(
            outcome.signatures[0].expired,
            "the newer certification self-signature bounds the key over one export"
        );
        for (label, first, second, reference_expired) in [
            ("the direct-key export second", &bounded, &direct, true),
            ("the direct-key export first", &direct, &bounded, false),
        ] {
            let mut keyring = first.clone();
            keyring.extend_from_slice(second);
            let certs = certs_of(&keyring);
            assert_eq!(certs.len(), 2, "{label}: the trusted set");
            let outcome = verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&blob)).unwrap();
            assert_eq!(outcome.signatures.len(), 1);
            let info = &outcome.signatures[0];
            assert!(!info.expired, "{label}: the direct-key tier did not answer");
            assert!(info.valid, "{label}: a live key reported not valid");
            assert_eq!(info.key_expires, None, "{label}: the instant reported");
            let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
            assert_eq!(reference.len(), 1, "{label}: the reference record count");
            assert_eq!(
                reference[0].expired, reference_expired,
                "{label}: gpgv no longer answers on the load order, so this \
                 case states the wrong thing about the reference",
            );
        }
    }

    /// A certificate that holds the signing key as its primary key and one that
    /// binds it as a subkey are two certificates and not two copies of one, so
    /// the key state is read over each of them and the earlier expiry answers.
    /// Their self-signatures verify under different primary keys, which is what
    /// keeps their signatures out of one set.
    ///
    /// The certificate that states no expiry does not extend the life the other
    /// one bounds, so the signature is refused whichever order the two stand
    /// in.
    #[test]
    fn a_subkey_and_a_primary_key_certificate_state_two_key_states() {
        if !tools_available() {
            return;
        }
        let home = Fixture::at("Split <split@ostrya.example>", "1d");
        let subkey = home.add_signing_subkey();
        let full = home.keyring();
        let blob = home.sign(&subkey, PAYLOAD);
        // The subkey as a certificate of its own. A v4 fingerprint is over the
        // key material, so this certificate holds the key the subkey is, and
        // it carries no signature and therefore states no expiry.
        let alone = subkey_as_certificate(&full);
        // The control: over that certificate alone the key is live, since
        // nothing states an expiry for it.
        let outcome =
            verify_signatures(&certs_of(&alone), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        assert_eq!(
            outcome.signatures[0].fingerprint.as_deref(),
            Some(&*subkey),
            "the subkey certificate answers for the signature"
        );
        assert!(
            outcome.signatures[0].valid,
            "the subkey certificate states no expiry"
        );
        for (label, first, second) in [
            ("the subkey certificate second", &full, &alone),
            ("the subkey certificate first", &alone, &full),
        ] {
            let mut keyring = first.clone();
            keyring.extend_from_slice(second);
            let certs = certs_of(&keyring);
            assert_eq!(certs.len(), 2, "{label}: the trusted set");
            let outcome = verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&blob)).unwrap();
            assert_eq!(outcome.signatures.len(), 1);
            let info = &outcome.signatures[0];
            assert!(info.expired, "{label}: the expiry was not read");
            assert!(!info.valid, "{label}: an expired key reported valid");
            assert_eq!(
                info.key_expires,
                Some(KEY_CREATED + ONE_DAY),
                "{label}: the instant reported"
            );
        }
    }

    /// A certification self-signature over the certificate's first user id,
    /// created at `created`, stating the key lifetime `lifetime` where one is
    /// given and carrying no key-expiration-time subpacket where none is.
    ///
    /// `gpg` 2.4.9 keeps one certification self-signature per user id, so a
    /// certificate carrying two is built by signing the second one here.
    fn certification_signature(secret: &[u8], created: u64, lifetime: Option<u64>) -> Vec<u8> {
        certification_self_signature(secret, SelfSig::at(created).key_lifetime(lifetime))
    }

    /// A signature of the class `typ` over one byte of `payload`, which is what
    /// a class the stored blob may not hold looks like. Such a signature is
    /// built here because `gpg` writes a document signature alone.
    fn other_class_signature(secret: &[u8], typ: SignatureType, payload: &[u8]) -> Vec<u8> {
        use pgp::packet::{PacketTrait, SignatureConfig, Subpacket, SubpacketData};
        use pgp::types::{Password, SigningKey};

        let secret_key = pgp::composed::SignedSecretKey::from_bytes(Cursor::new(secret)).unwrap();
        let public = secret_key.primary_key.public_key();
        let mut config =
            SignatureConfig::v4(typ, PublicKeyAlgorithm::EdDSALegacy, HashAlgorithm::Sha512);
        config.hashed_subpackets = vec![
            Subpacket::regular(SubpacketData::SignatureCreationTime(Timestamp::from_secs(
                u32::try_from(KEY_CREATED).unwrap(),
            )))
            .unwrap(),
            Subpacket::regular(SubpacketData::IssuerFingerprint(public.fingerprint())).unwrap(),
        ];
        config.unhashed_subpackets =
            vec![Subpacket::regular(SubpacketData::IssuerKeyId(public.legacy_key_id())).unwrap()];
        let mut hasher = config.hash_alg.new_hasher().unwrap();
        hasher.update(&payload[..1]);
        let len = config.hash_signature_data(&mut hasher).unwrap();
        hasher.update(&config.trailer(len).unwrap());
        let hash = hasher.finalize();
        let raw = secret_key
            .primary_key
            .sign(&Password::empty(), config.hash_alg, &hash)
            .unwrap();
        let signature = Signature::from_config(config, [hash[0], hash[1]], raw).unwrap();
        let mut bytes = Vec::new();
        signature.to_writer_with_header(&mut bytes).unwrap();
        bytes
    }

    /// Append one packet to the end of a certificate.
    fn append_packet(cert: &[u8], packet: &[u8]) -> Vec<u8> {
        let mut packets = split_packets(cert);
        let mut extra = split_packets(packet);
        assert_eq!(extra.len(), 1);
        packets.push(extra.remove(0));
        join_packets(&packets)
    }

    /// Flip the last byte of the one signature of class `class` a certificate
    /// carries, so that the signature verifies against nothing.
    fn alter_signature(cert: &[u8], class: u8) -> Vec<u8> {
        let mut packets = split_packets(cert);
        let mut altered = 0;
        for (tag, body) in &mut packets {
            if *tag == 2 && body[0] == 4 && body[1] == class {
                let last = body.len() - 1;
                body[last] ^= 0xff;
                altered += 1;
            }
        }
        assert_eq!(
            altered, 1,
            "one signature of class {class:#04x} was altered"
        );
        join_packets(&packets)
    }

    /// Assert one record states what `gpgv` states about the same signature,
    /// apart from the user id. The status stream carries the user id on the
    /// verdict line for the keywords [`parse_status`] matches, and a case whose
    /// verdict keyword it does not match leaves the reference record without
    /// one; the engine reads the user id off the certificate and reports it.
    fn assert_agrees_but_user_id(port: &SignatureInfo, reference: &SignatureInfo) {
        let mut port = port.clone();
        port.user_name = reference.user_name.clone();
        port.user_email = reference.user_email.clone();
        assert_agrees(&port, reference);
    }

    /// A signature past its own expiry is not valid. `gpgv` reports `EXPSIG`
    /// and no `GOODSIG` for it, and names no field of its own, so the record
    /// carries the instant the signature expires and nothing more.
    #[test]
    fn expired_signature_is_not_valid() {
        if !tools_available() {
            return;
        }
        let home = Fixture::at("Sigexp <sigexp@ostrya.example>", "never");
        let keyring = home.keyring();
        let blob = home.sign_with(&home.primary, PAYLOAD, &["--default-sig-expire", "1d"]);
        let outcome =
            verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees_but_user_id(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(!reference[0].valid, "the reference refuses it");
        assert!(!info.valid);
        assert!(!outcome.valid);
        assert_eq!(info.expires, Some(KEY_CREATED + ONE_DAY));
        // The key itself is live and is not revoked, so the signature's own
        // expiry is what refused it.
        assert!(!info.expired);
        assert!(!info.revoked);
        assert_eq!(info.key_expires, None);
        // The control is the same key over the same payload with no expiry on
        // the signature.
        let fresh = home.sign(&home.primary, PAYLOAD);
        let outcome = verify_signatures(&home.certs(), PAYLOAD, &[fresh]).unwrap();
        assert!(outcome.valid);
        assert_eq!(outcome.signatures[0].expires, None);
    }

    /// A signature of a class other than a document signature is refused. Such
    /// a signature covers one payload byte, so one of them would otherwise
    /// answer for every payload that starts with that byte.
    #[test]
    fn signature_of_another_class_is_refused() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("Class <class@ostrya.example>");
        let keyring = home.keyring();
        let secret = home.secret_key();
        for class in [SignatureType::Standalone, SignatureType::Timestamp] {
            let blob = other_class_signature(&secret, class, PAYLOAD);
            let outcome =
                verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
            let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
            assert_eq!(outcome.signatures.len(), 1);
            assert_eq!(reference.len(), 1);
            assert_agrees(&outcome.signatures[0], &reference[0]);
            let info = &outcome.signatures[0];
            assert!(!info.valid, "{class:?}");
            assert!(!outcome.valid);
            // The key is in the keyring and the record names it, so the class
            // is what refused the signature.
            assert!(!info.key_missing);
            assert_eq!(info.fingerprint.as_deref(), Some(&*home.primary));
            assert_eq!(info.user_name, None);
            // The same signature over another payload that starts with the same
            // byte is refused as well.
            let other = b"ostrya other payload".to_vec();
            assert_eq!(other[0], PAYLOAD[0]);
            let outcome = verify_signatures(&home.certs(), &other, &[blob]).unwrap();
            assert!(!outcome.valid, "{class:?} over another payload");
        }
        // The control is a document signature by the same key, which is valid.
        let blob = home.sign(&home.primary, PAYLOAD);
        assert!(
            verify_signatures(&home.certs(), PAYLOAD, &[blob])
                .unwrap()
                .valid
        );
    }

    /// An MD5 data signature whose issuer no loaded certificate holds is
    /// refused, and the record names the absent key. The digest policy cannot
    /// be reached around: a record no key answered for is never valid.
    #[test]
    fn md5_signature_with_an_unknown_issuer_is_refused() {
        if !tools_available() {
            return;
        }
        let signer = Fixture::rsa("Md5x <md5x@ostrya.example>");
        let other = Fixture::new("Other <other@ostrya.example>");
        let blob = signer.sign_with(&signer.primary, PAYLOAD, &["--digest-algo", "MD5"]);
        let outcome =
            verify_signatures(&other.certs(), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = signer.gpgv_records(&other.keyring(), &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(!info.valid);
        assert!(info.key_missing);
        assert_eq!(info.hash_algorithm.as_deref(), Some("MD5"));
    }

    /// A key stands live at the instant it expires and expires from the second
    /// after it. Polled second by second across its expiry instant, `gpgv`
    /// reports `GOODSIG` through that instant and `EXPKEYSIG` from the next
    /// second. The pair of certificates below states both sides of that
    /// boundary, and the run is repeated where the clock moved while it was
    /// being read.
    #[test]
    fn a_key_stands_live_at_the_instant_it_expires() {
        if !tools_available() {
            return;
        }
        let home = Fixture::at("Edge <edge@ostrya.example>", "10y");
        let keyring = home.keyring();
        let blob = home.sign(&home.primary, PAYLOAD);
        let secret = home.secret_key();
        for _ in 0..5 {
            let instant = now();
            let at = insert_after_primary(
                &keyring,
                &direct_key_signature(&secret, KEY_CREATED + 10, instant - KEY_CREATED),
            );
            let before = insert_after_primary(
                &keyring,
                &direct_key_signature(&secret, KEY_CREATED + 10, instant - KEY_CREATED - 1),
            );
            let live = verify_signatures(&certs_of(&at), PAYLOAD, std::slice::from_ref(&blob))
                .unwrap()
                .signatures
                .remove(0);
            let live_reference = home.gpgv_records(&at, &blob, PAYLOAD).remove(0);
            let past = verify_signatures(&certs_of(&before), PAYLOAD, std::slice::from_ref(&blob))
                .unwrap()
                .signatures
                .remove(0);
            let past_reference = home.gpgv_records(&before, &blob, PAYLOAD).remove(0);
            if now() != instant {
                // The second turned over while the four records were read, so
                // they state nothing about the boundary.
                continue;
            }
            assert_agrees(&live, &live_reference);
            assert_agrees(&past, &past_reference);
            assert!(!live.expired, "live at the instant it expires");
            assert!(live.valid);
            assert_eq!(live.key_expires, None);
            assert!(past.expired, "expired one second after");
            assert!(!past.valid);
            assert_eq!(past.key_expires, Some(instant - 1));
            return;
        }
        panic!("the clock turned over on every attempt");
    }

    /// The newest certification self-signature that verifies states the key
    /// expiry on its own terms. An older one does not stand in for it where it
    /// states no lifetime, and an altered newest one is passed over.
    #[test]
    fn the_newest_certification_self_signature_states_the_key_expiry() {
        if !tools_available() {
            return;
        }
        /// What each certificate states, and whether the key is then expired.
        struct Case {
            /// The lifetime the fixture's own self-signature states.
            first: &'static str,
            /// The lifetime the spliced newer self-signature states, in
            /// seconds, or `None` for a signature carrying no lifetime.
            second: Option<u64>,
            /// Whether the newer self-signature's bytes are altered.
            altered: bool,
            /// The instant the key expires, absent where it does not.
            expires: Option<u64>,
        }
        let cases = [
            // The newest self-signature answers, in both directions.
            Case {
                first: "10y",
                second: Some(ONE_DAY),
                altered: false,
                expires: Some(KEY_CREATED + ONE_DAY),
            },
            Case {
                first: "1d",
                second: Some(TEN_YEARS),
                altered: false,
                expires: None,
            },
            // A zero lifetime and an absent one both state no expiry, and the
            // older self-signature does not answer in place of either.
            Case {
                first: "1d",
                second: Some(0),
                altered: false,
                expires: None,
            },
            Case {
                first: "1d",
                second: None,
                altered: false,
                expires: None,
            },
            // An altered newest self-signature verifies against nothing, so the
            // older one answers.
            Case {
                first: "1d",
                second: Some(TEN_YEARS),
                altered: true,
                expires: Some(KEY_CREATED + ONE_DAY),
            },
        ];
        for (index, case) in cases.iter().enumerate() {
            let home = Fixture::at(
                &format!("Cert{index} <cert{index}@ostrya.example>"),
                case.first,
            );
            let blob = home.sign(&home.primary, PAYLOAD);
            let mut newer =
                certification_signature(&home.secret_key(), KEY_CREATED + 20, case.second);
            if case.altered {
                let last = newer.len() - 1;
                newer[last] ^= 0xff;
            }
            let keyring = append_packet(&home.keyring(), &newer);
            let outcome =
                verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob))
                    .unwrap();
            let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
            assert_eq!(reference.len(), 1, "case {index}");
            assert_agrees(&outcome.signatures[0], &reference[0]);
            let info = &outcome.signatures[0];
            assert_eq!(info.key_expires, case.expires, "case {index}");
            assert_eq!(info.expired, case.expires.is_some(), "case {index}");
            assert_eq!(info.valid, case.expires.is_none(), "case {index}");
        }
    }

    /// A signature lifetime that is spent, in seconds after the signature
    /// creation time. The cases below make a self-signature within a minute of
    /// [`KEY_CREATED`], so a signature carrying this lifetime expired long
    /// before the clock every `gpgv` run reads.
    const SPENT_LIFETIME: u64 = 100;

    /// The first signature packet of a detached signature blob.
    fn signature_of(blob: &[u8]) -> DetachedSignature {
        DetachedSignature::from_bytes_many(Cursor::new(blob))
            .expect("the blob opens as a packet stream")
            .next()
            .expect("the blob holds a signature packet")
            .expect("the signature packet is whole")
    }

    /// A certification self-signature whose own expiration time has passed
    /// states no key lifetime, and no older certification self-signature
    /// answers in its place.
    #[test]
    fn an_expired_certification_self_signature_states_no_key_lifetime() {
        if !tools_available() {
            return;
        }
        /// What one certificate carries and what it states.
        struct Case {
            /// The lifetime the fixture's own certification self-signature
            /// states.
            own: &'static str,
            /// The key lifetime the spliced newer certification states.
            spliced: Option<u64>,
            /// Whether the spliced certification has itself expired.
            expired: bool,
            /// The instant the key expires at, absent where it does not.
            expires: Option<u64>,
        }
        let cases = [
            // The spliced certification states no lifetime. The older one
            // states a lifetime already past and does not answer in its
            // place, whether the spliced one has expired or not.
            Case {
                own: "1d",
                spliced: Some(0),
                expired: true,
                expires: None,
            },
            Case {
                own: "1d",
                spliced: Some(0),
                expired: false,
                expires: None,
            },
            // The spliced certification states a lifetime already past. It
            // answers where it is live, and it states nothing where it has
            // itself expired.
            Case {
                own: "10y",
                spliced: Some(ONE_DAY),
                expired: true,
                expires: None,
            },
            Case {
                own: "10y",
                spliced: Some(ONE_DAY),
                expired: false,
                expires: Some(KEY_CREATED + ONE_DAY),
            },
        ];
        for (index, case) in cases.iter().enumerate() {
            let home = Fixture::at(
                &format!("Cexp{index} <cexp{index}@ostrya.example>"),
                case.own,
            );
            let blob = home.sign(&home.primary, PAYLOAD);
            let mut spec = SelfSig::at(KEY_CREATED + 20).key_lifetime(case.spliced);
            if case.expired {
                spec = spec.expiring_after(SPENT_LIFETIME);
            }
            let spliced = certification_self_signature(&home.secret_key(), spec);
            let keyring = append_packet(&home.keyring(), &spliced);
            let outcome =
                verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob))
                    .unwrap();
            let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
            assert_eq!(outcome.signatures.len(), 1, "case {index}");
            assert_eq!(reference.len(), 1, "case {index}");
            assert_agrees(&outcome.signatures[0], &reference[0]);
            let info = &outcome.signatures[0];
            assert_eq!(info.key_expires, case.expires, "case {index}");
            assert_eq!(info.expired, case.expires.is_some(), "case {index}");
            assert_eq!(info.valid, case.expires.is_none(), "case {index}");
        }
    }

    /// A direct-key self-signature whose own expiration time has passed states
    /// no key lifetime. The newest live one that states a lifetime answers,
    /// and where every direct-key self-signature has expired the certification
    /// self-signature answers.
    #[test]
    fn an_expired_direct_key_self_signature_states_no_key_lifetime() {
        if !tools_available() {
            return;
        }
        /// What one certificate carries and what it states. Every fixture's
        /// own certification self-signature states one day, an instant
        /// already past.
        struct Case {
            /// The direct-key self-signatures spliced onto the certificate:
            /// the creation time after [`KEY_CREATED`], the key lifetime, and
            /// whether the signature has itself expired.
            spliced: &'static [(u64, u64, bool)],
            /// The instant the key expires at, absent where it does not.
            expires: Option<u64>,
        }
        let cases = [
            // One direct-key self-signature that has expired. It states
            // nothing, so the certification self-signature answers. A zero
            // key lifetime already states nothing, so the first case holds
            // whether the signature has expired or not and the second case is
            // the one the expiration time decides.
            Case {
                spliced: &[(20, 0, true)],
                expires: Some(KEY_CREATED + ONE_DAY),
            },
            Case {
                spliced: &[(20, TEN_YEARS, true)],
                expires: Some(KEY_CREATED + ONE_DAY),
            },
            // The same signature while it is live answers, and the key stands
            // live for ten years.
            Case {
                spliced: &[(20, TEN_YEARS, false)],
                expires: None,
            },
            // A live older direct-key self-signature beside an expired newer
            // one answers, so the tier does not fall through where one of its
            // signatures is live.
            Case {
                spliced: &[(10, TEN_YEARS, false), (20, TEN_YEARS, true)],
                expires: None,
            },
        ];
        for (index, case) in cases.iter().enumerate() {
            let home = Fixture::at(&format!("Dexp{index} <dexp{index}@ostrya.example>"), "1d");
            let blob = home.sign(&home.primary, PAYLOAD);
            let secret = home.secret_key();
            let mut keyring = home.keyring();
            for (created, lifetime, expired) in case.spliced {
                let mut spec = SelfSig::at(KEY_CREATED + created).key_lifetime(Some(*lifetime));
                if *expired {
                    spec = spec.expiring_after(SPENT_LIFETIME);
                }
                keyring = insert_after_primary(&keyring, &direct_self_signature(&secret, spec));
            }
            let outcome =
                verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob))
                    .unwrap();
            let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
            assert_eq!(outcome.signatures.len(), 1, "case {index}");
            assert_eq!(reference.len(), 1, "case {index}");
            assert_agrees(&outcome.signatures[0], &reference[0]);
            let info = &outcome.signatures[0];
            assert_eq!(info.key_expires, case.expires, "case {index}");
            assert_eq!(info.expired, case.expires.is_some(), "case {index}");
            assert_eq!(info.valid, case.expires.is_none(), "case {index}");
        }
    }

    /// A subkey binding signature whose own expiration time has passed binds
    /// nothing, so a signature the subkey made resolves to no key and reports
    /// `key_missing`. A live older binding beside it still binds.
    #[test]
    fn an_expired_subkey_binding_signature_binds_nothing() {
        if !tools_available() {
            return;
        }
        let home = Fixture::at("Bexp <bexp@ostrya.example>", "never");
        let subkey = home.add_signing_subkey();
        let blob = home.sign(&subkey, PAYLOAD);
        let secret = home.secret_key();

        // The control: the binding built here, carrying no expiration time,
        // binds the subkey, so the expiration time is what the case below
        // states and not the way the binding was made.
        let live = replace_subkey_binding(
            &home.keyring(),
            &subkey_binding_signature(&secret, KEY_CREATED + 20, None),
        );
        let certs = certs_of(&live);
        let outcome = verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&live, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(outcome.signatures[0].valid);
        assert_eq!(outcome.signatures[0].fingerprint.as_deref(), Some(&*subkey));
        assert!(resolve_issuers(&certs, &signature_of(&blob).signature).is_some());

        // The same binding, expired. The subkey belongs to no loaded
        // certificate.
        let expired = replace_subkey_binding(
            &home.keyring(),
            &subkey_binding_signature(&secret, KEY_CREATED + 20, Some(SPENT_LIFETIME)),
        );
        let certs = certs_of(&expired);
        let outcome = verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&expired, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        let info = &outcome.signatures[0];
        assert!(info.key_missing, "the subkey resolved to a certificate");
        assert!(!info.valid);
        assert!(!outcome.valid);
        assert_eq!(
            info.fingerprint.as_deref(),
            Some(&*subkey),
            "the fingerprint the signature packet names"
        );
        assert_eq!(info.user_name, None);
        assert!(resolve_issuers(&certs, &signature_of(&blob).signature).is_none());

        // The expired binding beside the live one `gpg` wrote. The live one
        // binds, so one expired binding does not unbind a subkey.
        let both = append_packet(
            &home.keyring(),
            &subkey_binding_signature(&secret, KEY_CREATED + 20, Some(SPENT_LIFETIME)),
        );
        let outcome =
            verify_signatures(&certs_of(&both), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&both, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(outcome.signatures[0].valid);
        assert!(!outcome.signatures[0].key_missing);
    }

    /// A certification self-signature whose own expiration time has passed
    /// ranks no user id and marks none primary, so the report names the user
    /// id whose own certification is live.
    #[test]
    fn an_expired_certification_self_signature_ranks_no_user_id() {
        if !tools_available() {
            return;
        }
        const ALPHA: &str = "Alpha <alpha@ostrya.example>";
        const BRAVO: &str = "Bravo <bravo@ostrya.example>";
        /// What the certification spliced onto the first user id carries.
        struct Case {
            /// The instant it was made, after [`KEY_CREATED`].
            created: u64,
            /// Whether it marks the user id primary.
            marks_primary: bool,
        }
        let cases = [
            // The mark outranks recency, so a live signature older than the
            // second user id's own certification names the first user id.
            Case {
                created: 20,
                marks_primary: true,
            },
            // Recency alone ranks, so a live signature newer than the second
            // user id's own certification names the first user id.
            Case {
                created: 40,
                marks_primary: false,
            },
        ];
        for (index, case) in cases.iter().enumerate() {
            let home = Fixture::at(ALPHA, "never");
            // The second user id's own certification stands 30 seconds after
            // the key creation time, between the two instants the cases use.
            home.add_uid_at("20250101T000030!", BRAVO);
            let blob = home.sign(&home.primary, PAYLOAD);
            let secret = home.secret_key();
            for expired in [false, true] {
                let mut spec = SelfSig::at(KEY_CREATED + case.created);
                if case.marks_primary {
                    spec = spec.marking_primary();
                }
                if expired {
                    spec = spec.expiring_after(SPENT_LIFETIME);
                }
                let keyring = insert_after_user_id(
                    &home.keyring(),
                    ALPHA,
                    &certification_self_signature(&secret, spec),
                );
                let outcome =
                    verify_signatures(&certs_of(&keyring), PAYLOAD, std::slice::from_ref(&blob))
                        .unwrap();
                let reference = home.gpgv_records(&keyring, &blob, PAYLOAD);
                assert_eq!(outcome.signatures.len(), 1, "case {index}");
                assert_eq!(reference.len(), 1, "case {index}");
                assert_agrees(&outcome.signatures[0], &reference[0]);
                let info = &outcome.signatures[0];
                let named = if expired { "bravo" } else { "alpha" };
                assert_eq!(
                    info.user_email.as_deref(),
                    Some(&*format!("{named}@ostrya.example")),
                    "case {index}, expired {expired}"
                );
                assert!(info.valid, "case {index}, expired {expired}");
            }
        }
    }

    /// A subkey revocation that verifies against nothing revokes nothing, so
    /// the subkey still speaks for its certificate. The revocation the
    /// certificate carries is altered, which is what an attacker who cannot
    /// make the primary key's signatures can produce.
    #[test]
    fn an_altered_subkey_revocation_does_not_revoke() {
        if !tools_available() {
            return;
        }
        let home = Fixture::new("SubAlt <subalt@ostrya.example>");
        let subkey = home.add_signing_subkey();
        let blob = home.sign(&subkey, PAYLOAD);
        home.revoke_subkey();
        let revoked = home.keyring();
        // The control states that the intact revocation is honored.
        let outcome =
            verify_signatures(&certs_of(&revoked), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        assert!(outcome.signatures[0].revoked);
        assert!(!outcome.valid);

        let altered = alter_signature(&revoked, 0x28);
        let outcome =
            verify_signatures(&certs_of(&altered), PAYLOAD, std::slice::from_ref(&blob)).unwrap();
        let reference = home.gpgv_records(&altered, &blob, PAYLOAD);
        assert_eq!(outcome.signatures.len(), 1);
        assert_eq!(reference.len(), 1);
        assert_agrees(&outcome.signatures[0], &reference[0]);
        assert!(!outcome.signatures[0].revoked);
        assert!(outcome.signatures[0].valid);
        assert_eq!(outcome.signatures[0].fingerprint.as_deref(), Some(&*subkey));
    }

    /// A signature expires at the instant it names. Polled second by second
    /// across its expiry instant, `gpgv` reports `GOODSIG` through the second
    /// before that instant and `EXPSIG` from the instant on. The pair of
    /// signatures below states both sides of the boundary, and the run is
    /// repeated where the clock moved while it was being read.
    #[test]
    fn a_signature_expires_at_the_instant_it_names() {
        if !tools_available() {
            return;
        }
        let home = Fixture::at("Sedge <sedge@ostrya.example>", "never");
        let keyring = home.keyring();
        for _ in 0..5 {
            let instant = now();
            let at = home.sign_with(
                &home.primary,
                PAYLOAD,
                &[
                    "--default-sig-expire",
                    &format!("seconds={}", instant - KEY_CREATED),
                ],
            );
            let later = home.sign_with(
                &home.primary,
                PAYLOAD,
                &[
                    "--default-sig-expire",
                    &format!("seconds={}", instant - KEY_CREATED + 1),
                ],
            );
            let gone = verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&at))
                .unwrap()
                .signatures
                .remove(0);
            let gone_reference = home.gpgv_records(&keyring, &at, PAYLOAD).remove(0);
            let live = verify_signatures(&home.certs(), PAYLOAD, std::slice::from_ref(&later))
                .unwrap()
                .signatures
                .remove(0);
            let live_reference = home.gpgv_records(&keyring, &later, PAYLOAD).remove(0);
            if now() != instant {
                // The second turned over while the four records were read, so
                // they state nothing about the boundary.
                continue;
            }
            assert_eq!(gone.expires, Some(instant));
            assert_eq!(live.expires, Some(instant + 1));
            assert_agrees_but_user_id(&gone, &gone_reference);
            assert_agrees(&live, &live_reference);
            assert!(!gone.valid, "expired at the instant it names");
            assert!(live.valid, "live one second before that instant");
            return;
        }
        panic!("the clock turned over on every attempt");
    }

    /// Parse the machine-readable status stream of one `gpgv` run into
    /// per-signature records. Each `NEWSIG` starts a record; the verdict
    /// keywords and the `VALIDSIG` and `ERRSIG` detail lines fill it.
    ///
    /// This is the reference reader the cases above compare the engine
    /// against, so it states what `gpgv` reports in the same shape the engine
    /// answers in.
    fn parse_status(stdout: &[u8]) -> Vec<SignatureInfo> {
        let text = String::from_utf8_lossy(stdout);
        let mut infos: Vec<SignatureInfo> = Vec::new();
        let mut current: Option<SignatureInfo> = None;
        for line in text.lines() {
            let Some(rest) = line.strip_prefix(STATUS_PREFIX) else {
                continue;
            };
            let mut fields = rest.split(' ');
            let keyword = fields.next().unwrap_or("");
            match keyword {
                "NEWSIG" => {
                    if let Some(info) = current.take() {
                        infos.push(info);
                    }
                    current = Some(SignatureInfo::default());
                }
                "GOODSIG" | "EXPKEYSIG" | "REVKEYSIG" | "BADSIG" => {
                    let info = current.get_or_insert_with(SignatureInfo::default);
                    let _keyid = fields.next();
                    let uid = fields.collect::<Vec<_>>().join(" ");
                    let (name, email) = split_uid(&uid);
                    info.user_name = name;
                    info.user_email = email;
                    match keyword {
                        "GOODSIG" => info.valid = true,
                        "EXPKEYSIG" => info.expired = true,
                        "REVKEYSIG" => info.revoked = true,
                        _ => {}
                    }
                }
                // VALIDSIG <fpr> <date> <sig-epoch> <sig-expire-epoch> <version>
                //          <reserved> <pk-algo> <hash-algo> <class> [<primary-fpr>]
                "VALIDSIG" => {
                    let info = current.get_or_insert_with(SignatureInfo::default);
                    let fpr = fields.next().map(str::to_owned);
                    let _date = fields.next();
                    info.created = fields.next().and_then(parse_epoch);
                    info.expires = fields.next().and_then(parse_epoch);
                    let _version = fields.next();
                    let _reserved = fields.next();
                    info.pubkey_algorithm = fields.next().map(pubkey_algo_name);
                    info.hash_algorithm = fields.next().map(hash_algo_name);
                    let _class = fields.next();
                    info.primary_fingerprint =
                        fields.next().map(str::to_owned).or_else(|| fpr.clone());
                    info.fingerprint = fpr;
                }
                // ERRSIG <keyid> <pk-algo> <hash-algo> <class> <epoch> <rc> <fpr>
                "ERRSIG" => {
                    let info = current.get_or_insert_with(SignatureInfo::default);
                    let _keyid = fields.next();
                    info.pubkey_algorithm = fields.next().map(pubkey_algo_name);
                    info.hash_algorithm = fields.next().map(hash_algo_name);
                    let _class = fields.next();
                    info.created = fields.next().and_then(parse_epoch);
                    let _rc = fields.next();
                    info.fingerprint = fields.next().filter(|f| *f != "-").map(str::to_owned);
                }
                "NO_PUBKEY" => {
                    current
                        .get_or_insert_with(SignatureInfo::default)
                        .key_missing = true;
                }
                "KEYEXPIRED" => {
                    let info = current.get_or_insert_with(SignatureInfo::default);
                    info.key_expires = fields.next().and_then(parse_epoch);
                }
                _ => {}
            }
        }
        if let Some(info) = current.take() {
            infos.push(info);
        }
        infos
    }

    /// The OpenPGP public-key algorithm name for a status-line algorithm id.
    fn pubkey_algo_name(id: &str) -> String {
        match id {
            "1" | "2" | "3" => "RSA".to_owned(),
            "17" => "DSA".to_owned(),
            "18" => "ECDH".to_owned(),
            "19" => "ECDSA".to_owned(),
            "22" => "EdDSA".to_owned(),
            "27" => "Ed25519".to_owned(),
            "28" => "Ed448".to_owned(),
            other => other.to_owned(),
        }
    }

    /// The OpenPGP hash algorithm name for a status-line algorithm id.
    fn hash_algo_name(id: &str) -> String {
        match id {
            "1" => "MD5".to_owned(),
            "2" => "SHA1".to_owned(),
            "3" => "RIPEMD160".to_owned(),
            "8" => "SHA256".to_owned(),
            "9" => "SHA384".to_owned(),
            "10" => "SHA512".to_owned(),
            "11" => "SHA224".to_owned(),
            other => other.to_owned(),
        }
    }

    #[test]
    fn reference_reads_a_good_signature_group() {
        let status = b"[GNUPG:] NEWSIG\n\
[GNUPG:] KEY_CONSIDERED A8F57B71FCDE8767005FED7BD1960140B3A73EF1 0\n\
[GNUPG:] SIG_ID JFFMsT+jReslGyUGdsIHB0VWYmc 2026-07-23 1784843948\n\
[GNUPG:] GOODSIG D1960140B3A73EF1 Ostrya Obs <obs@ostrya.example>\n\
[GNUPG:] VALIDSIG A8F57B71FCDE8767005FED7BD1960140B3A73EF1 2026-07-23 1784843948 0 4 0 22 10 00 A8F57B71FCDE8767005FED7BD1960140B3A73EF1\n\
[GNUPG:] TRUST_ULTIMATE 0 pgp\n";
        let infos = parse_status(status);
        assert_eq!(infos.len(), 1);
        let info = &infos[0];
        assert!(info.valid);
        assert_eq!(
            info.fingerprint.as_deref(),
            Some("A8F57B71FCDE8767005FED7BD1960140B3A73EF1")
        );
        assert_eq!(
            info.primary_fingerprint.as_deref(),
            Some("A8F57B71FCDE8767005FED7BD1960140B3A73EF1")
        );
        assert_eq!(info.created, Some(1_784_843_948));
        assert_eq!(info.expires, None);
        assert_eq!(info.pubkey_algorithm.as_deref(), Some("EdDSA"));
        assert_eq!(info.hash_algorithm.as_deref(), Some("SHA512"));
        assert_eq!(info.user_name.as_deref(), Some("Ostrya Obs"));
        assert_eq!(info.user_email.as_deref(), Some("obs@ostrya.example"));
        assert!(!info.expired && !info.revoked && !info.key_missing);
    }

    #[test]
    fn reference_reads_a_missing_key_group() {
        let status = b"[GNUPG:] NEWSIG\n\
[GNUPG:] ERRSIG D1960140B3A73EF1 22 10 00 1784843948 9 A8F57B71FCDE8767005FED7BD1960140B3A73EF1\n\
[GNUPG:] NO_PUBKEY D1960140B3A73EF1\n";
        let infos = parse_status(status);
        assert_eq!(infos.len(), 1);
        let info = &infos[0];
        assert!(!info.valid);
        assert!(info.key_missing);
        assert_eq!(
            info.fingerprint.as_deref(),
            Some("A8F57B71FCDE8767005FED7BD1960140B3A73EF1")
        );
        assert_eq!(info.created, Some(1_784_843_948));
        assert_eq!(info.pubkey_algorithm.as_deref(), Some("EdDSA"));
        assert_eq!(info.hash_algorithm.as_deref(), Some("SHA512"));
    }

    #[test]
    fn reference_reads_a_bad_signature_group() {
        let status = b"[GNUPG:] NEWSIG\n\
[GNUPG:] KEY_CONSIDERED A8F57B71FCDE8767005FED7BD1960140B3A73EF1 0\n\
[GNUPG:] BADSIG D1960140B3A73EF1 Ostrya Obs <obs@ostrya.example>\n";
        let infos = parse_status(status);
        assert_eq!(infos.len(), 1);
        assert!(!infos[0].valid);
        assert!(!infos[0].key_missing);
        assert_eq!(infos[0].user_email.as_deref(), Some("obs@ostrya.example"));
    }

    #[test]
    fn reference_reads_an_expired_key_group() {
        let status = b"[GNUPG:] NEWSIG\n\
[GNUPG:] KEY_CONSIDERED 6AD5971478704B77113ADBB848D090AA43A2A526 0\n\
[GNUPG:] KEYEXPIRED 1704153600\n\
[GNUPG:] SIG_ID +XcyGaLbMGu3b/KdjZwUEMjugoA 2024-01-01 1704070800\n\
[GNUPG:] EXPKEYSIG 48D090AA43A2A526 Expired <exp@ostrya.example>\n\
[GNUPG:] VALIDSIG 6AD5971478704B77113ADBB848D090AA43A2A526 2024-01-01 1704070800 0 4 0 22 10 00 6AD5971478704B77113ADBB848D090AA43A2A526\n";
        let infos = parse_status(status);
        assert_eq!(infos.len(), 1);
        let info = &infos[0];
        assert!(!info.valid);
        assert!(info.expired);
        assert_eq!(info.key_expires, Some(1_704_153_600));
        assert_eq!(info.created, Some(1_704_070_800));
    }

    #[test]
    fn reference_reads_a_revoked_key_group() {
        let status = b"[GNUPG:] NEWSIG\n\
[GNUPG:] KEY_CONSIDERED 159446FE5B9606A44046DCE5A3106528346CA760 0\n\
[GNUPG:] SIG_ID 9+MSlwFSpYu41OSggWc6zYgnd5Y 2026-07-23 1784844103\n\
[GNUPG:] REVKEYSIG A3106528346CA760 Obs Two <obs2@ostrya.example>\n\
[GNUPG:] VALIDSIG 159446FE5B9606A44046DCE5A3106528346CA760 2026-07-23 1784844103 0 4 0 22 10 00 159446FE5B9606A44046DCE5A3106528346CA760\n";
        let infos = parse_status(status);
        assert_eq!(infos.len(), 1);
        assert!(!infos[0].valid);
        assert!(infos[0].revoked);
    }

    #[test]
    fn reference_reads_two_signature_groups() {
        let status = b"[GNUPG:] NEWSIG\n\
[GNUPG:] GOODSIG A3106528346CA760 Obs Two <obs2@ostrya.example>\n\
[GNUPG:] VALIDSIG 159446FE5B9606A44046DCE5A3106528346CA760 2026-07-23 1784844103 0 4 0 22 10 00 159446FE5B9606A44046DCE5A3106528346CA760\n\
[GNUPG:] NEWSIG\n\
[GNUPG:] ERRSIG A6E1C7D5D3E3ECB2 22 10 00 1784844139 9 778742FE807AADB2F6419736A6E1C7D5D3E3ECB2\n\
[GNUPG:] NO_PUBKEY A6E1C7D5D3E3ECB2\n";
        let infos = parse_status(status);
        assert_eq!(infos.len(), 2);
        assert!(infos[0].valid);
        assert!(!infos[1].valid);
        assert!(infos[1].key_missing);
    }

    #[test]
    fn reference_reads_an_empty_status_as_no_records() {
        assert!(parse_status(b"").is_empty());
        assert!(parse_status(b"gpgv: verification error\n").is_empty());
    }

    #[test]
    fn splits_uids() {
        assert_eq!(
            split_uid("Ostrya Obs <obs@ostrya.example>"),
            (
                Some("Ostrya Obs".to_owned()),
                Some("obs@ostrya.example".to_owned())
            )
        );
        assert_eq!(
            split_uid("no-address"),
            (Some("no-address".to_owned()), None)
        );
        assert_eq!(
            split_uid("<only@address>"),
            (None, Some("only@address".to_owned()))
        );
    }
}