ostrya 0.2.3

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
//! GPG (OpenPGP) commit-signing engine (Phase 13d).
//!
//! Behind the `verify-gpg` feature: keyrings are parsed, signatures are
//! verified, and a remote's trusted keyring is managed in the process with the
//! `pgp` crate (rPGP). The `sign-gpg` feature adds signing through
//! `gpg --detach-sign` and turns on `verify-gpg` with it. That signing run is a
//! short-lived subprocess through [`ostrya_rt::Command`], and it is the one
//! `gpg` run the library makes. The private key stays with GnuPG and its agent
//! and never passes through the library.
//!
//! Format (`format-reference.md`, "Signing details -- GPG"):
//!
//! - The `ostree.gpgsigs` value is an `aay`; each `ay` element is one detached
//!   OpenPGP signature (the binary signature packet stream, unarmored). A blob
//!   may hold more than one signature packet.
//! - The signed payload is the same commit bytes as the other engines.
//!
//! [`GpgSigner`] addresses its key the way the `gpg` binary does: a
//! fingerprint, key id, or user id resolved in a GnuPG home directory
//! (`--local-user`, with an optional `--homedir` override). `gpg` performs
//! the private-key operation itself, consulting its `gpg-agent` -- and any
//! hardware token behind it -- as needed.
//!
//! [`GpgVerifier`] holds the certificates its keyrings parse to. Keyrings are
//! loaded through [`from_keyring_bytes`](GpgVerifier::from_keyring_bytes) and
//! [`from_keyring_files`](GpgVerifier::from_keyring_files) (armored input is
//! decoded to the binary packet stream the parser reads, and Trust packets are
//! dropped from that stream, so a legacy GnuPG keyring and the `gpg --export`
//! stream of the same keys parse to the same certificates).
//! [`from_system_trust`](GpgVerifier::from_system_trust) loads the global
//! trusted set -- every `*.gpg` keyring in the directory named by the
//! `OSTREE_GPG_HOME` environment variable, or `<datadir>/ostree/trusted.gpg.d/`
//! when it is unset. [`for_remote`](GpgVerifier::for_remote) adds the
//! per-remote keyring (`<remote>.trustedkeys.gpg` in the repo or under
//! `/etc/ostree/remotes.d/`) on top of that global set, and
//! [`for_remote_keyrings`](GpgVerifier::for_remote_keyrings) takes the
//! repository's keyring as bytes and adds the keyrings a remote's `gpgkeypath`
//! names, which is what a pull trusts. Every keyring file reaches the trusted
//! set through one reader: only a regular file is read, and only up to four
//! mebibytes, so a path naming a fifo and a keyring over that ceiling are each
//! refused by that path's own name.
//!
//! A keyring is untrusted input, so its load is bounded and its parse is
//! contained. The four-mebibyte ceiling holds over a keyring supplied as bytes
//! as well, and one keyring holds at most 256 certificates; each refusal names
//! the cap it reached. A GnuPG keybox, which carries the `KBXf` magic, is
//! refused by the name of the file or the blob that holds it, since rPGP reads
//! OpenPGP packet streams and a keybox is a container of another kind. A
//! keyring the parser rejects fails the load, and so does a keyring whose
//! packet stream does not frame to its end, so the trusted set a verification
//! works over is one that was read whole.
//!
//! Verification reads the stored blobs and the loaded certificates and answers
//! in the process, on the blocking pool. The `verify` module holds the engine,
//! the trust and validity policy it applies, and the input caps a stored blob
//! is held to. No process is spawned and no scratch directory is written.
//!
//! A remote's own trusted keyring is managed in the process:
//! [`Repo::gpg_import_keys`] adds certificates to `<remote>.trustedkeys.gpg`
//! and reports how many the keyring did not already hold, and
//! [`Repo::gpg_list_keys`] reads back the keys it holds as
//! [`GpgKey`] records. The keyring the import writes keeps the packet stream it
//! already held and carries the packets of each added certificate as the
//! offered stream wrote them, with the Trust packets dropped. The keyring is
//! written in the binary form, so an armored keyring keeps its packets and
//! loses its armor. `gpg` and the `ostree` tool both read a keyring of that
//! form. A certificate for a key the keyring already holds is left as the
//! keyring holds it, so a new user id or a new subkey for a held key reaches
//! the keyring through [`Repo::remove_remote_keyring`] and a fresh import. Two
//! statements are the exceptions, and each replaces the held certificate, which
//! rewrites the keyring: a key revocation that verifies under the key it
//! revokes, so a revoked key stops speaking for the remote, and a key expiry
//! later than the held certificate states, so a key whose owner has extended
//! its life speaks again. A keyring offered for import is untrusted input and
//! is held to the same caps and the same containment a keyring loaded for
//! verification is. Both streams reach the reader a verification load uses,
//! the offered one and the one the keyring already holds, so a stream that
//! reader does not read whole fails the import and leaves the keyring as it
//! was.
//!
//! A signature is valid only where it verifies against a trusted key whose
//! bindings hold and which is neither expired nor revoked. An expired key, a
//! revoked key, a bad signature, and an absent key are each reported per
//! signature in [`SignatureInfo`](crate::sign::SignatureInfo). Trust is
//! membership in the verifier's keyrings; GnuPG's ownertrust model plays no
//! part.

use std::collections::BTreeMap;
use std::io::Cursor;
use std::ops::Range;
use std::os::fd::OwnedFd;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use ostrya_core::base64;
use pgp::composed::{Deserializable, SignedPublicKey};
use pgp::packet::PacketHeader;
use pgp::types::{KeyDetails, PacketLength, Tag};

use crate::config::remote_keyring_name;
use crate::error::{Error, Result};
use crate::repo::Repo;
#[cfg(feature = "sign-gpg")]
use crate::sign::{SignFuture, Signer};
use crate::sign::{Verifier, VerifyFuture, VerifyOutcome, read_key_path, read_key_source};

mod verify;

/// The GPG engine's short name.
#[cfg(feature = "sign-gpg")]
const GPG_SIGN_TYPE: &str = "gpg";
/// The GPG engine's detached-metadata dict key. Unlike the sign-api engines,
/// GPG signatures live under `ostree.gpgsigs`, not `ostree.sign.<type>`.
const GPG_METADATA_KEY: &str = "ostree.gpgsigs";
/// The system directory holding keyrings trusted for every remote.
const GLOBAL_TRUSTED_GPG_D: &str = "/usr/share/ostree/trusted.gpg.d";
/// The environment variable that overrides the global trusted-keyring
/// directory, as the `ostree` tool honors it.
const OSTREE_GPG_HOME_ENV: &str = "OSTREE_GPG_HOME";
/// The system directory holding per-remote configuration and keyrings.
const SYSTEM_REMOTES_D: &str = "/etc/ostree/remotes.d";
/// The prefix of a machine-readable status line on the status fd.
#[cfg(any(feature = "sign-gpg", test))]
const STATUS_PREFIX: &str = "[GNUPG:] ";
/// The ceiling on one keyring file, whose whole content is read into memory.
/// One exported ed25519 certificate is a few hundred bytes, so four mebibytes
/// holds thousands of them, and a remote's trusted set is a handful.
pub(crate) const MAX_KEYRING: u64 = 4 * 1024 * 1024;
/// The ceiling on the certificates one keyring may hold. A remote's trusted
/// set is a handful of certificates, and the ceiling bounds the work a keyring
/// from a remote or from `trusted.gpg.d` can ask the parser for.
const MAX_KEYRING_CERTS: usize = 256;
/// The magic a GnuPG keybox carries, and the offset it stands at. A keybox
/// opens with a header blob: a four-byte length, a one-byte blob type, a
/// one-byte version, and two bytes of flags stand before the magic.
const KEYBOX_MAGIC: &[u8] = b"KBXf";
const KEYBOX_MAGIC_OFFSET: usize = 8;

/// The GPG commit-signing engine.
///
/// Holds the key selector `gpg --local-user` resolves -- a fingerprint, a key
/// id, or a user id -- and an optional GnuPG home directory. Signing runs
/// `gpg --detach-sign` with the payload on stdin and reads the binary
/// signature from stdout.
#[cfg(feature = "sign-gpg")]
#[derive(Debug, Clone)]
pub struct GpgSigner {
    key: String,
    homedir: Option<PathBuf>,
}

#[cfg(feature = "sign-gpg")]
impl GpgSigner {
    /// A signer for the key `gpg` resolves from `key` (a fingerprint, key id,
    /// or user id) in the default GnuPG home directory.
    pub fn new(key: impl Into<String>) -> GpgSigner {
        GpgSigner {
            key: key.into(),
            homedir: None,
        }
    }

    /// Resolve the signing key in `dir` instead of the default GnuPG home
    /// directory.
    pub fn with_homedir(mut self, dir: impl Into<PathBuf>) -> GpgSigner {
        self.homedir = Some(dir.into());
        self
    }

    /// The GnuPG home directory this signer resolves its key in, or `None` for
    /// gpg's own default.
    pub fn homedir(&self) -> Option<&Path> {
        self.homedir.as_deref()
    }

    /// The fingerprints of the secret keys `gpg` resolves this signer's
    /// selector to, in listing order.
    ///
    /// Runs `gpg --list-secret-keys` over the selector, which reports the keys
    /// without touching the private material or starting a signing operation. A
    /// home directory that does not exist, one that cannot be read, and one
    /// holding no matching key all answer an empty list, so a caller reports one
    /// "no such key" refusal for the three. More than one fingerprint means the
    /// selector names more than one key and a caller that needs a single signing
    /// key refuses it.
    ///
    /// The selector stands after `--`, so gpg reads it as a key name alone.
    /// Without the terminator gpg reads an option-shaped selector as one of its
    /// own options, and a selector such as `--homedir=<path>` moves the lookup
    /// to another home directory and creates a keybox and a trust database
    /// there.
    pub async fn secret_key_fingerprints(&self) -> Result<Vec<String>> {
        let mut cmd = ostrya_rt::Command::new("gpg");
        if let Some(dir) = &self.homedir {
            cmd.arg("--homedir").arg(dir);
        }
        cmd.arg("--batch")
            .arg("--with-colons")
            .arg("--list-secret-keys")
            .arg("--")
            .arg(&self.key);
        let output = cmd.output(&[]).await.map_err(|e| spawn_err("gpg", &e))?;
        if !output.status.success() {
            return Ok(Vec::new());
        }
        Ok(primary_fingerprints(&output.stdout))
    }
}

/// The primary-key fingerprints in a `--with-colons` secret-key listing, in
/// listing order.
///
/// Each `sec` record opens one key and the `fpr` record that follows it carries
/// that key's fingerprint in field ten. A `ssb` record opens a subkey, whose own
/// `fpr` record names the subkey and is skipped.
#[cfg(feature = "sign-gpg")]
fn primary_fingerprints(listing: &[u8]) -> Vec<String> {
    let mut found = Vec::new();
    let mut wanted = false;
    for line in listing.split(|&b| b == b'\n') {
        let mut fields = line.split(|&b| b == b':');
        match fields.next() {
            Some(b"sec") => wanted = true,
            Some(b"fpr") if wanted => {
                wanted = false;
                if let Some(fpr) = fields.nth(8)
                    && let Ok(text) = std::str::from_utf8(fpr)
                    && !text.is_empty()
                {
                    found.push(text.to_owned());
                }
            }
            Some(b"ssb") => wanted = false,
            _ => {}
        }
    }
    found
}

#[cfg(feature = "sign-gpg")]
impl Signer for GpgSigner {
    fn name(&self) -> &str {
        GPG_SIGN_TYPE
    }

    fn metadata_key(&self) -> &str {
        GPG_METADATA_KEY
    }

    fn sign<'a>(&'a self, data: &'a [u8]) -> SignFuture<'a> {
        Box::pin(async move {
            let mut cmd = ostrya_rt::Command::new("gpg");
            if let Some(dir) = &self.homedir {
                cmd.arg("--homedir").arg(dir);
            }
            cmd.arg("--batch")
                .arg("--status-fd")
                .arg("2")
                .arg("--detach-sign")
                .arg("--local-user")
                .arg(&self.key);
            let output = cmd.output(data).await.map_err(|e| spawn_err("gpg", &e))?;
            if !output.status.success() || output.stdout.is_empty() {
                return Err(Error::Signature(format!(
                    "gpg --detach-sign failed: {}",
                    failure_text(&output)
                )));
            }
            Ok(output.stdout)
        })
    }
}

/// The GPG commit-verifying engine, holding the trusted certificates its
/// keyrings parse to.
#[derive(Debug, Clone, Default)]
pub struct GpgVerifier {
    /// The certificates the loaded keyrings hold, in load order. The parse
    /// happens as a keyring is loaded, so a keyring the parser rejects fails
    /// the load rather than a verification made over it.
    ///
    /// A key the sources hold several certificates for keeps every one of
    /// them here. The verdict reads all the certificates that answer for a
    /// signature's issuer, so a revocation any of them carries refuses the
    /// signature whatever order the sources loaded in.
    ///
    /// One reference count holds the set. A verification hands the set to the
    /// blocking pool through a count of its own. The certificates are parsed
    /// once and shared by every commit a pull verifies.
    certs: Arc<Vec<SignedPublicKey>>,
}

impl GpgVerifier {
    /// Build a verifier trusting every certificate in the given keyring
    /// blobs. Each blob is a binary or ASCII-armored OpenPGP keyring and may
    /// hold several certificates; armored input is decoded to the binary
    /// form, and all blobs merge into one trusted set.
    ///
    /// Each blob is held to four mebibytes and to 256 certificates, and a blob
    /// carrying a GnuPG keybox is refused. A refusal names the blob by its
    /// position in the sequence and states the cap it reached.
    pub fn from_keyring_bytes<I, B>(keyrings: I) -> Result<GpgVerifier>
    where
        I: IntoIterator<Item = B>,
        B: AsRef<[u8]>,
    {
        let mut verifier = GpgVerifier::default();
        for (index, keyring) in keyrings.into_iter().enumerate() {
            verifier.add_keyring(keyring.as_ref(), &format!("the keyring blob {index}"))?;
        }
        Ok(verifier)
    }

    /// Build a verifier from keyring files on disk (binary or armored). A
    /// missing file is skipped rather than an error, so an absent optional
    /// keyring does not fail the build. Only a regular file is read, and only
    /// up to four mebibytes; a path of another kind and a keyring over that
    /// ceiling are each refused by the path's own name.
    pub fn from_keyring_files<I, P>(paths: I) -> Result<GpgVerifier>
    where
        I: IntoIterator<Item = P>,
        P: AsRef<Path>,
    {
        let mut verifier = GpgVerifier::default();
        verifier.add_keyring_files(paths)?;
        Ok(verifier)
    }

    /// Build a verifier from the keyrings trusted for `remote` in the
    /// repository at `repo_path`: `<remote>.trustedkeys.gpg` in the repository
    /// and under `/etc/ostree/remotes.d/`, plus the global trusted set
    /// (see [`from_system_trust`](GpgVerifier::from_system_trust)). Missing
    /// paths are skipped.
    pub fn for_remote(repo_path: &Path, remote: &str) -> Result<GpgVerifier> {
        let keyring = repo_path.join(format!("{remote}.trustedkeys.gpg"));
        let repo_keyring = read_keyring_path(&keyring)?;
        GpgVerifier::for_remote_keyrings(repo_keyring, remote, &[])
    }

    /// Build a verifier from a remote's whole trusted set, with the
    /// repository's own keyring supplied as bytes.
    ///
    /// `repo_keyring` is the repository's `<remote>.trustedkeys.gpg`, which a
    /// caller holding a descriptor rather than a path reads for itself. On top
    /// of it come the system per-remote keyring
    /// (`/etc/ostree/remotes.d/<remote>.trustedkeys.gpg`), the global trusted
    /// set (see [`from_system_trust`](GpgVerifier::from_system_trust)), and
    /// every entry of `keypath`, which is what a remote's `gpgkeypath` names.
    ///
    /// A `keypath` entry is a keyring file or a directory of `*.gpg` keyrings,
    /// and an entry that names neither fails the build, so a keyring path that
    /// has gone missing is reported rather than silently reducing the trusted
    /// set. The other sources are optional and a missing one is skipped.
    pub fn for_remote_keyrings(
        repo_keyring: Option<Vec<u8>>,
        remote: &str,
        keypath: &[String],
    ) -> Result<GpgVerifier> {
        let mut paths: Vec<PathBuf> = Vec::new();
        paths.push(Path::new(SYSTEM_REMOTES_D).join(format!("{remote}.trustedkeys.gpg")));
        paths.extend(keyring_files_in(&global_trusted_dir())?);
        for entry in keypath {
            let path = Path::new(entry);
            let meta = std::fs::metadata(path).map_err(|e| {
                Error::Signature(format!("gpgkeypath entry '{entry}' cannot be read: {e}"))
            })?;
            if meta.is_dir() {
                paths.extend(keyring_files_in(path)?);
            } else {
                paths.push(path.to_owned());
            }
        }
        let mut verifier = GpgVerifier::default();
        if let Some(bytes) = repo_keyring {
            verifier.add_keyring(&bytes, &format!("the keyring '{remote}.trustedkeys.gpg'"))?;
        }
        verifier.add_keyring_files(paths)?;
        Ok(verifier)
    }

    /// Build a verifier from the global trusted keyrings alone: every `*.gpg`
    /// keyring in the directory named by the `OSTREE_GPG_HOME` environment
    /// variable, or, when that variable is unset or empty, the system
    /// `/usr/share/ostree/trusted.gpg.d/` directory. No per-remote keyring
    /// participates. This is the trust applied to a commit named with no
    /// remote. A missing directory yields an empty trusted set.
    pub fn from_system_trust() -> Result<GpgVerifier> {
        GpgVerifier::from_keyring_files(keyring_files_in(&global_trusted_dir())?)
    }

    /// Add every keyring `paths` names to the trusted set, in the order given.
    /// A path naming no file is skipped.
    fn add_keyring_files<I, P>(&mut self, paths: I) -> Result<()>
    where
        I: IntoIterator<Item = P>,
        P: AsRef<Path>,
    {
        for path in paths {
            let path = path.as_ref();
            if let Some(bytes) = read_keyring_path(path)? {
                self.add_keyring(&bytes, &format!("the keyring '{}'", path.display()))?;
            }
        }
        Ok(())
    }

    /// Add one keyring to the trusted set: decode armor, hold the blob to the
    /// input caps, refuse a keybox, and parse the certificates it carries.
    /// `subject` names the source, so a refusal states which keyring reached
    /// which cap.
    ///
    /// The extend runs in place. Every constructor calls this on a value it
    /// owns alone, so the count over the set is one and no certificate is
    /// copied. A caller holding a second count would extend a copy, which is
    /// why this stays private.
    fn add_keyring(&mut self, bytes: &[u8], subject: &str) -> Result<()> {
        let binary = keyring_stream(bytes, subject)?;
        let certs = parse_keyring(&binary, subject)?;
        Arc::make_mut(&mut self.certs).extend(certs.into_iter().map(|(cert, _)| cert));
        Ok(())
    }
}

/// The binary packet stream one keyring blob carries: armor decoded, the blob
/// held to [`MAX_KEYRING`], and a GnuPG keybox refused. `subject` names the
/// source, so a refusal states which keyring reached which cap.
fn keyring_stream(bytes: &[u8], subject: &str) -> Result<Vec<u8>> {
    if bytes.len() as u64 > MAX_KEYRING {
        return Err(Error::Signature(format!(
            "{subject} is over the {MAX_KEYRING}-byte ceiling"
        )));
    }
    let binary = dearmor(bytes)?;
    if binary.len() >= KEYBOX_MAGIC_OFFSET + KEYBOX_MAGIC.len()
        && &binary[KEYBOX_MAGIC_OFFSET..KEYBOX_MAGIC_OFFSET + KEYBOX_MAGIC.len()] == KEYBOX_MAGIC
    {
        return Err(Error::Signature(format!(
            "{subject} is a GnuPG keybox, and a keyring is read as an OpenPGP \
             packet stream"
        )));
    }
    Ok(binary)
}

/// The packets a binary OpenPGP stream carries, each as its tag and the byte
/// range it occupies, together with the length of the prefix that framed.
///
/// The walk frames each packet with rPGP's own header parser, which is the
/// parser the packet stream is read with, so a packet boundary here is a packet
/// boundary there. A header the parser refuses, a length form other than a
/// fixed one, and a length that runs past the end each stop the walk, and the
/// reported prefix length then falls short of the input.
fn packet_spans(binary: &[u8]) -> (Vec<(Tag, Range<usize>)>, usize) {
    let mut spans: Vec<(Tag, Range<usize>)> = Vec::new();
    let mut at = 0usize;
    while at < binary.len() {
        let rest = &binary[at..];
        let mut reader = rest;
        let Ok(header) = PacketHeader::try_from_reader(&mut reader) else {
            break;
        };
        let PacketLength::Fixed(body) = header.packet_length() else {
            break;
        };
        let total = (rest.len() - reader.len()).saturating_add(body as usize);
        if total == 0 || total > rest.len() {
            break;
        }
        spans.push((header.tag(), at..at + total));
        at += total;
    }
    (spans, at)
}

/// The certificates a binary keyring stream carries, each as the packets of one
/// transferable public key with the Trust packets dropped.
///
/// A Public-Key packet opens a certificate and every packet up to the next one
/// belongs to it. A packet standing before the first Public-Key packet belongs
/// to no certificate, and it is dropped.
///
/// A Trust packet (tag 12) holds a GnuPG-local trust value and carries no part
/// of a transferable public key, so it is dropped as well. A legacy GnuPG
/// keyring writes one after the primary key packet, after each user id packet,
/// and after each signature packet. rPGP's certificate parser reads the packets
/// of one certificate through runs of tag tests, and a packet of any other tag
/// ends a run, so a Trust packet standing after the primary key leaves the
/// certificate with no user id and no subkey. With the Trust packets gone, a
/// legacy keyring parses to the certificates the `gpg --export` form of the
/// same keys parses to.
///
/// `None` where the packet stream does not frame to its end, which is what a
/// truncated keyring reaches, and which the `ostree` tool refuses as well. The
/// result is at most as long as the input, which [`keyring_stream`] has already
/// held to [`MAX_KEYRING`].
fn certificate_chunks(binary: &[u8]) -> Option<Vec<Vec<u8>>> {
    let (spans, framed) = packet_spans(binary);
    if framed != binary.len() {
        return None;
    }
    let mut chunks: Vec<Vec<u8>> = Vec::new();
    for (tag, span) in spans {
        match tag {
            Tag::Trust => {}
            Tag::PublicKey => chunks.push(binary[span].to_vec()),
            _ => {
                if let Some(chunk) = chunks.last_mut() {
                    chunk.extend_from_slice(&binary[span]);
                }
            }
        }
    }
    Some(chunks)
}

/// Parse a binary OpenPGP keyring into the certificates it carries, each with
/// the packets it is made of, holding the result to [`MAX_KEYRING_CERTS`].
///
/// The stream is split into one packet run per certificate and each run is
/// parsed on its own (see [`certificate_chunks`]), so the Trust packets and a
/// packet standing ahead of the first certificate reach no parser: a legacy
/// GnuPG keyring and a `gpg --export` stream of the same keys parse to the same
/// certificates. A keyring carrying no packet parses to no certificate.
///
/// A stream that does not frame to its end and a certificate the parser rejects
/// each fail the read by the name of the source, so a keyring reaches a caller
/// whole. `subject` names the source, so a refusal states which keyring was
/// read. Every path that reads a keyring reads it here: a verification load, a
/// key listing, and both streams of an import.
///
/// The parse runs inside [`contained`], since a keyring is untrusted input.
fn parse_keyring(binary: &[u8], subject: &str) -> Result<Vec<(SignedPublicKey, Vec<u8>)>> {
    let refusal = format!("{subject} is not readable as an OpenPGP keyring: the parser panicked");
    contained(&refusal, || {
        let Some(chunks) = certificate_chunks(binary) else {
            return Err(Error::Signature(format!(
                "{subject} is not readable as an OpenPGP keyring"
            )));
        };
        if chunks.len() > MAX_KEYRING_CERTS {
            return Err(Error::Signature(format!(
                "{subject} holds more than {MAX_KEYRING_CERTS} certificates"
            )));
        }
        let mut certs = Vec::with_capacity(chunks.len());
        for chunk in chunks {
            let cert = SignedPublicKey::from_bytes(Cursor::new(&chunk)).map_err(|e| {
                Error::Signature(format!(
                    "{subject} is not readable as an OpenPGP keyring: {e}"
                ))
            })?;
            certs.push((cert, chunk));
        }
        Ok(certs)
    })
}

/// Run `work`, which reads OpenPGP packets, with a panic inside it converted to
/// the refusal `refusal` states.
///
/// A keyring is untrusted input, so every read over one runs here and a caught
/// panic reads as input 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 contained<T>(refusal: &str, work: impl FnOnce() -> Result<T>) -> Result<T> {
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)) {
        Ok(result) => result,
        Err(_) => Err(Error::Signature(refusal.to_owned())),
    }
}

impl Verifier for GpgVerifier {
    fn metadata_key(&self) -> &str {
        GPG_METADATA_KEY
    }

    fn verify<'a>(&'a self, data: &'a [u8], signatures: &'a [Vec<u8>]) -> VerifyFuture<'a> {
        Box::pin(async move {
            if signatures.is_empty() {
                return Ok(VerifyOutcome::default());
            }
            // Public-key cryptography over untrusted input, so it runs on the
            // blocking pool. The pool holds each input for itself: the payload
            // and the signature blobs as copies, the trusted set as a
            // reference count over the one parse.
            let certs = Arc::clone(&self.certs);
            let payload = data.to_vec();
            let blobs = signatures.to_vec();
            ostrya_rt::unblock(move || verify::verify_signatures(&certs, &payload, &blobs)).await
        })
    }
}

/// One key in a remote's trusted keyring, as `remote gpg-list-keys` reports it.
///
/// The fields are what a certificate states about its primary key: the
/// fingerprint, the instant it was created, and its user ids in listing order.
/// Subkeys are not reported on their own; a subkey's parent carries it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GpgKey {
    /// The primary key fingerprint, uppercase hex.
    pub fingerprint: String,
    /// When the key was created, in seconds since the Unix epoch.
    pub created: Option<u64>,
    /// The user ids bound to the key, in listing order.
    pub user_ids: Vec<String>,
}

impl Repo {
    /// Import the OpenPGP certificates `keys` holds into `remote`'s trusted
    /// keyring, `<remote>.trustedkeys.gpg`, and report how many the keyring did
    /// not already hold.
    ///
    /// `keys` is a binary or ASCII-armored certificate stream, which is what an
    /// exported public keyring is. With `key_ids` non-empty only the keys those
    /// selectors name are imported (a fingerprint, a key id, or a user id
    /// substring); a selector that names nothing in `keys` fails the import and
    /// the keyring is left as it was, as does a `keys` holding no certificate.
    ///
    /// The keyring is replaced atomically at the repository root. It keeps the
    /// packet stream it already held and carries the packets of each added
    /// certificate as `keys` wrote them, with the Trust packets dropped (see
    /// `merge_keyring`). It is written in the binary form, so an armored
    /// keyring keeps its packets and loses its armor.
    ///
    /// A certificate for a key the keyring already holds is left as the keyring
    /// holds it, and is counted as a key the keyring already held. So a new user
    /// id or a new subkey for a held key reaches the keyring through
    /// [`Repo::remove_remote_keyring`] and a fresh import, and not through a
    /// second call here. `docs/conformance/cli-surface.md`, "P3", records what
    /// the `ostree` tool does instead.
    ///
    /// A key revocation and a later key expiry are the exceptions. A
    /// certificate carrying a key revocation signature that verifies under the
    /// key it revokes replaces the held certificate, so a revoked key stops
    /// speaking for the remote. A certificate stating a later key expiry than
    /// the held one states, an absent expiry counting as later than any instant,
    /// replaces it as well, so a key whose owner has extended its life speaks
    /// again. Each replacement rewrites the keyring and drops the Trust packets
    /// it carried (see `merge_keyring`), and the key is still counted as one
    /// the keyring already held. The offered stream and the keyring the remote
    /// already holds reach one keyring reader, so a keyring carrying bytes past
    /// its last framed packet is refused by the name of the keyring, which
    /// leaves the keyring as it was.
    ///
    /// A bare revocation certificate carries no public-key packet
    /// and holds no certificate, so it is refused; the re-export of the revoked
    /// key is the stream that carries a revocation in.
    pub async fn gpg_import_keys(
        &self,
        remote: &str,
        keys: &[u8],
        key_ids: &[String],
    ) -> Result<usize> {
        let name = remote_keyring_name(remote);
        let existing = self.read_root_file(&name).await?.unwrap_or_default();
        // Parsing untrusted certificate streams is CPU work over owned copies
        // of its inputs, so it runs on the blocking pool.
        let offered = keys.to_vec();
        let ids = key_ids.to_vec();
        let subject = format!("the keyring '{name}'");
        let (imported, keyring) =
            ostrya_rt::unblock(move || merge_keyring(&existing, &offered, &ids, &subject)).await?;
        let fsync = self.config().fsync()?;
        self.write_root_file(&name, keyring, fsync).await?;
        Ok(imported)
    }

    /// The keys `remote`'s trusted keyring holds. An absent keyring holds none.
    pub async fn gpg_list_keys(&self, remote: &str) -> Result<Vec<GpgKey>> {
        let name = remote_keyring_name(remote);
        let Some(keyring) = self.read_root_file(&name).await? else {
            return Ok(Vec::new());
        };
        let subject = format!("the keyring '{name}'");
        ostrya_rt::unblock(move || keyring_keys(&keyring, &subject)).await
    }
}

/// Merge the certificates `offered` holds into the keyring `existing` holds and
/// report how many certificates the keyring did not already hold.
///
/// The packet stream `existing` carries is kept as it stands and the packets of
/// each certificate the keyring does not hold are appended, so a keyring another
/// implementation wrote keeps its own packets and an added certificate stands as
/// the offered stream wrote it. The result is a binary packet stream: an armored
/// `existing` decodes to the packets it holds, the merge keeps those packets,
/// and the result carries no armor. The keyring carries no Trust packet of this
/// import's making.
///
/// A certificate whose fingerprint the keyring already holds is left as the
/// keyring holds it, with two exceptions, each of which replaces the held
/// certificate with the offered one (see [`replaces`]): an offered certificate
/// carrying a key revocation that verifies, so a revoked key stops speaking for
/// the remote, and an offered certificate stating a later key expiry, so a key
/// whose owner has extended its life speaks again. A designated revoker is
/// resolved among every certificate the two streams hold, so a revocation such
/// a revoker made carries in where either stream states the revoker (see
/// [`KeyState`]). The replacement rewrites the
/// keyring, since a keyring is a run of packets per certificate and a signature
/// written at the end of the stream would attach to the last certificate in it,
/// and the rewrite drops the Trust packets the keyring carried (see
/// [`replace_certificates`]). Either way the certificate is counted as a key the
/// keyring already held.
///
/// The same two rules hold inside one offered stream: where a stream carries
/// several states of one key, the first state stands unless a later one revokes
/// the key or states a later expiry, and the key is counted once.
///
/// Each stream is read with [`parse_keyring`], the reader a verification load
/// uses, so each of them frames to its end. A keyring carrying bytes past its
/// last framed packet fails the merge by its own name, and the file keeps the
/// bytes it held.
///
/// Both streams are untrusted input, so each is held to [`MAX_KEYRING`] and to
/// [`MAX_KEYRING_CERTS`], a keybox is refused, and every packet read runs inside
/// [`contained`]. `subject` names the keyring the repository holds, so a refusal
/// over it states which file was read.
fn merge_keyring(
    existing: &[u8],
    offered: &[u8],
    key_ids: &[String],
    subject: &str,
) -> Result<(usize, Vec<u8>)> {
    let source = "the keyring to import";
    let mut keyring = keyring_stream(existing, subject)?;
    let stream = keyring_stream(offered, source)?;
    let refusal = format!("{source} cannot be merged into {subject}: the parser panicked");
    let (imported, rewritten, appended) = contained(&refusal, || {
        // The certificate runs the keyring holds, in the order they stand in,
        // and the state of every key it holds, by fingerprint. A keyring
        // holding one key through two certificates answers once here, over both
        // of them, which is the reach the verify path gives them.
        let mut runs: Vec<(String, Vec<u8>)> = Vec::new();
        let mut copies: BTreeMap<String, Vec<SignedPublicKey>> = BTreeMap::new();
        for (cert, packets) in parse_keyring(&keyring, subject)? {
            let fingerprint = fingerprint_hex(&cert);
            runs.push((fingerprint.clone(), packets));
            copies.entry(fingerprint).or_default().push(cert);
        }
        let offered = parse_keyring(&stream, source)?;
        if offered.is_empty() {
            return Err(Error::Signature(format!(
                "{source} holds no OpenPGP certificate"
            )));
        }
        // The set a designated revoker is resolved among: every certificate the
        // two streams hold, whatever key each of them states and whether or not
        // the selector names it (see [`KeyState`]).
        let known: Vec<&SignedPublicKey> = copies
            .values()
            .flatten()
            .chain(offered.iter().map(|(cert, _)| cert))
            .collect();
        let mut held: BTreeMap<String, KeyState> = copies
            .iter()
            .map(|(fingerprint, copies)| (fingerprint.clone(), KeyState::over(copies, &known)))
            .collect();
        // The certificates to append, in append order, each with the state it
        // states, and the held certificates a replacement rewrites.
        let mut added: Vec<(String, KeyState, Vec<u8>)> = Vec::new();
        let mut replaced: BTreeMap<String, Vec<u8>> = BTreeMap::new();
        let mut imported = 0;
        for index in select_keys(&offered, key_ids)? {
            let (cert, packets) = &offered[index];
            let fingerprint = fingerprint_hex(cert);
            let state = KeyState::of(cert, &known);
            if let Some(entry) = held.get_mut(&fingerprint) {
                if replaces(entry, &state) {
                    *entry = state;
                    replaced.insert(fingerprint, packets.clone());
                }
            } else if let Some(entry) = added.iter_mut().find(|(f, _, _)| *f == fingerprint) {
                if replaces(&entry.1, &state) {
                    entry.1 = state;
                    entry.2 = packets.clone();
                }
            } else {
                added.push((fingerprint, state, packets.clone()));
                imported += 1;
            }
        }
        let rewritten = if replaced.is_empty() {
            None
        } else {
            Some(replace_certificates(&runs, &replaced))
        };
        let appended: Vec<u8> = added
            .into_iter()
            .flat_map(|(_, _, packets)| packets)
            .collect();
        Ok((imported, rewritten, appended))
    })?;
    if let Some(bytes) = rewritten {
        keyring = bytes;
    }
    keyring.extend_from_slice(&appended);
    Ok((imported, keyring))
}

/// What the certificates for one key state about it.
#[derive(Clone, Copy)]
struct KeyState {
    /// Whether a verified key revocation signature stands over the key: one the
    /// key itself made, or one a key the certificate designates as a revoker
    /// made, where the certificate of that revoker is among the ones the import
    /// knows.
    ///
    /// A revocation is read through the verify engine, so the import reads the
    /// signature the verdict reads. The engine resolves a designated revoker
    /// among the certificates it is given, and the import gives it every
    /// certificate the two streams it was handed hold: the certificates of the
    /// keyring under edit and the certificates of the offered stream. A
    /// selector governs what the import writes and not what it knows, so a
    /// certificate the selector leaves out still resolves a revoker.
    ///
    /// Two states stand outside that set, and in each of them the keyring keeps
    /// trusting a key the `ostree` tool's own keyring stops trusting
    /// (`docs/conformance/cli-surface.md`, "P3"): a revoker whose certificate
    /// stands in the global trusted directory or in a `gpgkeypath` entry rather
    /// than in the keyring under edit, and a revoker imported after the
    /// revocation was offered. The import is a function of the two byte streams
    /// it is given, so one import writes the same bytes on every host, and it
    /// writes no revocation it cannot verify, so an offered keyring is no way
    /// to strike a held certificate out.
    revoked: bool,
    /// The instant the key expires at, absent where they state no expiry. The
    /// instant is read through the verify engine, so the import and the verdict
    /// answer off the same signature.
    expires: Option<u64>,
}

impl KeyState {
    /// What `cert` states, with a designated revoker resolved among `known`.
    fn of(cert: &SignedPublicKey, known: &[&SignedPublicKey]) -> KeyState {
        KeyState::over(std::slice::from_ref(cert), known)
    }

    /// What the copies of one certificate state together: a revocation any copy
    /// carries, and the key expiry the newest self-signature of the union
    /// states. This is the reach the verify path gives a keyring that holds one
    /// key through several certificates.
    ///
    /// `known` is the set a designated revoker is resolved among, which is the
    /// reach [`KeyState::revoked`] states. The copies of the key under decision
    /// are one thing and that set is another: a revocation stands over the key
    /// these copies state, and the revoker is a key of its own.
    fn over(copies: &[SignedPublicKey], known: &[&SignedPublicKey]) -> KeyState {
        KeyState {
            revoked: copies
                .iter()
                .any(|cert| verify::key_revoked(cert, known.iter().copied())),
            expires: verify::key_expiry_over(copies),
        }
    }
}

/// Whether an offered certificate stating `offered` replaces a held
/// certificate stating `held`.
///
/// Two statements are carried into a held certificate, and each of them is one
/// the keyring has no other way to take in:
///
/// - a key revocation the held certificate does not carry. A revocation is
///   permanent, so a keyring holding a certificate that states none takes it;
/// - a key expiry later than the held certificate states, where an absent
///   expiry counts as later than any instant. An expiry is renewable, so a held
///   certificate can state a lifetime the key's owner has replaced.
///
/// A held certificate that revokes its key takes no expiry replacement. The
/// replacement writes the offered packets where the held run stood, so an
/// offered certificate carrying no revocation would leave the keyring stating
/// none.
///
/// Two consequences follow from the direction of the expiry rule. A shortened
/// expiry does not reach the keyring. An older certificate that states a longer
/// expiry replaces a shorter statement the keyring holds.
fn replaces(held: &KeyState, offered: &KeyState) -> bool {
    let revocation = offered.revoked && !held.revoked;
    let extension = !held.revoked && states_later(offered.expires, held.expires);
    revocation || extension
}

/// Whether `offered` states a later key expiry than `held`. An absent instant
/// is the later statement, since a key stating no expiry outlives one that
/// states any instant.
fn states_later(offered: Option<u64>, held: Option<u64>) -> bool {
    match (offered, held) {
        (None, Some(_)) => true,
        (Some(offered), Some(held)) => offered > held,
        (_, None) => false,
    }
}

/// The keyring the certificate runs `runs` hold, with the run of each
/// fingerprint `replaced` names written as those packets state it.
///
/// A keyring is a run of packets per certificate, so a certificate is replaced
/// where it stands and every other run passes through as it stands. A keyring
/// holding one key through two runs takes the replacement in both, which leaves
/// the offered packets twice over and the key in the state those packets state.
///
/// `runs` comes from [`parse_keyring`], which drops the Trust packets and a
/// packet standing ahead of the first Public-Key packet: the keyring the rewrite
/// writes is of the same form the import writes for a certificate it adds.
fn replace_certificates(
    runs: &[(String, Vec<u8>)],
    replaced: &BTreeMap<String, Vec<u8>>,
) -> Vec<u8> {
    let mut rewritten: Vec<u8> = Vec::new();
    for (fingerprint, packets) in runs {
        rewritten.extend_from_slice(replaced.get(fingerprint).unwrap_or(packets));
    }
    rewritten
}

/// The offered certificates `key_ids` names, by index, in selector order. An
/// empty `key_ids` names every offered certificate, and a selector that names
/// none is refused by name, which leaves the keyring as it was.
fn select_keys(offered: &[(SignedPublicKey, Vec<u8>)], key_ids: &[String]) -> Result<Vec<usize>> {
    if key_ids.is_empty() {
        return Ok((0..offered.len()).collect());
    }
    let mut selected = Vec::new();
    for id in key_ids {
        let matched = offered
            .iter()
            .enumerate()
            .filter(|(_, (cert, _))| selector_matches(cert, id))
            .map(|(index, _)| index);
        let before = selected.len();
        selected.extend(matched);
        if selected.len() == before {
            return Err(Error::Signature(format!(
                "no key matching '{id}' among the keys to import"
            )));
        }
    }
    Ok(selected)
}

/// Whether `selector` names `cert`.
///
/// A selector names a key, a user id, or nothing, per [`read_selector`]. A key
/// selector is read over the primary key and over every subkey; a user id
/// selector is a case-insensitive substring of one of the certificate's user
/// ids, folded over ASCII alone.
fn selector_matches(cert: &SignedPublicKey, selector: &str) -> bool {
    match read_selector(selector) {
        Selector::Key(hex) => {
            key_matches(cert, &hex)
                || cert
                    .public_subkeys
                    .iter()
                    .any(|subkey| key_matches(subkey, &hex))
        }
        Selector::UserId(wanted) => cert.details.users.iter().any(|user| {
            String::from_utf8_lossy(user.id.id())
                .to_ascii_lowercase()
                .contains(&wanted)
        }),
        Selector::Nothing => false,
    }
}

/// What a `KEY-ID` selector names.
enum Selector {
    /// A key, by the lowercase hex a key id or a fingerprint holds.
    Key(String),
    /// A substring of a user id, ASCII-lowercased.
    UserId(String),
    /// Nothing.
    Nothing,
}

/// What `selector` names, read as `gpg --export` reads a key name.
///
/// Measured against `gpg` 2.4.9 over `gpg --export -- <selector>`, where a
/// selector read as a key exports nothing when no key answers to it and a
/// selector read as a user id substring exports the key whose user id holds it:
///
/// - Hex digits alone name a key at five lengths: 8 digits a short key id, 16 a
///   key id, and 32, 40, or 64 a fingerprint. Any other length is a user id
///   substring -- `0123456789ab` exports the key whose user id holds those
///   twelve digits.
/// - A `0x` prefix names a key and never a user id: `0xhello` reports
///   `key "0xhello" not found: Invalid user ID` over a certificate whose user id
///   holds `0xhello`. The prefix is read in lower case alone, so `0X1234` is a
///   user id substring and exports the key whose user id holds `0X1234`.
/// - Interior spaces are admitted in one shape, the printed v4 fingerprint: ten
///   groups of four hex digits with one space between them. Every other spaced
///   shape is a user id substring -- forty hex digits in groups of two, and
///   thirty-two or sixty-four in groups of four, each export the key whose user
///   id holds them, and a `0x` prefix with a space reports `Invalid user ID`.
/// - Leading and trailing whitespace around a key selector is dropped, and
///   leading whitespace before a user id selector is dropped as well.
/// - A selector holding no character other than whitespace names nothing:
///   `gpg --export -- ''` reports `key "" not found: Invalid user ID`.
/// - The user id search folds ASCII case alone. Over the user id `Ärger`,
///   `ÄRGER` exports the key and `ärger` exports nothing.
fn read_selector(selector: &str) -> Selector {
    // `gpg` reads a space and a tab as the whitespace it drops, and no other
    // character, so a selector opening with one of those loses it here.
    let space = |c: char| c == ' ' || c == '\t';
    let head = selector.trim_start_matches(space);
    if let Some(rest) = head.strip_prefix("0x") {
        return match key_hex(rest.trim_end_matches(space)) {
            Some(hex) => Selector::Key(hex),
            None => Selector::Nothing,
        };
    }
    if head.is_empty() {
        return Selector::Nothing;
    }
    let bare = head.trim_end_matches(space);
    if let Some(hex) = key_hex(bare).or_else(|| spaced_fingerprint(bare)) {
        return Selector::Key(hex);
    }
    Selector::UserId(head.to_ascii_lowercase())
}

/// The lowercase hex `text` holds, where it is hex digits alone of a key id's or
/// a fingerprint's length.
fn key_hex(text: &str) -> Option<String> {
    let named = matches!(text.len(), 8 | 16 | 32 | 40 | 64);
    (named && text.chars().all(|c| c.is_ascii_hexdigit())).then(|| text.to_ascii_lowercase())
}

/// The lowercase hex a printed v4 fingerprint holds: ten groups of four hex
/// digits with one space between them.
fn spaced_fingerprint(text: &str) -> Option<String> {
    let groups: Vec<&str> = text.split(' ').collect();
    let shaped = groups.len() == 10
        && groups
            .iter()
            .all(|group| group.len() == 4 && group.chars().all(|c| c.is_ascii_hexdigit()));
    shaped.then(|| groups.concat().to_ascii_lowercase())
}

/// Whether one key answers to the hex a key selector holds.
fn key_matches<K: KeyDetails>(key: &K, hex: &str) -> bool {
    let id = key.legacy_key_id().to_string();
    match hex.len() {
        8 => id.ends_with(hex),
        16 => id == hex,
        _ => format!("{:x}", key.fingerprint()) == hex,
    }
}

/// The primary key fingerprint of a certificate, uppercase hex.
fn fingerprint_hex(cert: &SignedPublicKey) -> String {
    format!("{:X}", cert.fingerprint())
}

/// The keys a keyring holds, in the order its certificates stand in. The read
/// runs inside [`contained`], since a keyring is untrusted input.
fn keyring_keys(keyring: &[u8], subject: &str) -> Result<Vec<GpgKey>> {
    let binary = keyring_stream(keyring, subject)?;
    let refusal = format!("{subject} is not readable as an OpenPGP keyring: the parser panicked");
    contained(&refusal, || {
        let keys = parse_keyring(&binary, subject)?
            .into_iter()
            .map(|(cert, _)| {
                let created = cert.primary_key.created_at().as_secs();
                GpgKey {
                    fingerprint: fingerprint_hex(&cert),
                    created: (created != 0).then(|| u64::from(created)),
                    user_ids: cert
                        .details
                        .users
                        .iter()
                        .map(|user| String::from_utf8_lossy(user.id.id()).into_owned())
                        .collect(),
                }
            })
            .collect();
        Ok(keys)
    })
}

/// Decode ASCII-armored OpenPGP data (RFC 4880 radix-64) into the binary
/// packet stream, concatenating every armored block found. Binary input
/// passes through unchanged. The optional armor headers and the `=XXXX`
/// checksum line are skipped.
fn dearmor(bytes: &[u8]) -> Result<Vec<u8>> {
    let is_armored = bytes
        .iter()
        .position(|b| !b.is_ascii_whitespace())
        .is_some_and(|i| bytes[i..].starts_with(b"-----BEGIN PGP"));
    if !is_armored {
        return Ok(bytes.to_vec());
    }
    let text = std::str::from_utf8(bytes)
        .map_err(|_| Error::Signature("gpg keyring: armored data is not valid UTF-8".into()))?;
    let mut out = Vec::new();
    let mut lines = text.lines().map(str::trim_end);
    while let Some(line) = lines.next() {
        if !line.starts_with("-----BEGIN PGP") {
            continue;
        }
        let mut body = String::new();
        let mut in_headers = true;
        for line in lines.by_ref() {
            if line.starts_with("-----END") {
                break;
            }
            if in_headers {
                if line.trim().is_empty() {
                    in_headers = false;
                    continue;
                }
                // An armor header is `Key: Value`; a line without a colon is
                // already body (the blank separator was absent).
                if line.contains(':') {
                    continue;
                }
                in_headers = false;
            }
            // The `=XXXX` line is the radix-64 checksum, not body.
            if line.starts_with('=') {
                continue;
            }
            body.push_str(line.trim());
        }
        out.extend_from_slice(&base64::decode(&body)?);
    }
    Ok(out)
}

/// The directory of keyrings trusted for every remote: the value of the
/// `OSTREE_GPG_HOME` environment variable when set to a non-empty value,
/// otherwise the system `/usr/share/ostree/trusted.gpg.d` directory.
fn global_trusted_dir() -> PathBuf {
    match std::env::var_os(OSTREE_GPG_HOME_ENV) {
        Some(dir) if !dir.is_empty() => PathBuf::from(dir),
        _ => PathBuf::from(GLOBAL_TRUSTED_GPG_D),
    }
}

/// The `*.gpg` keyring files in `dir`, sorted by name. A missing directory
/// yields an empty list rather than an error.
fn keyring_files_in(dir: &Path) -> Result<Vec<PathBuf>> {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e.into()),
    };
    let mut files = Vec::new();
    for entry in entries {
        let entry = entry?;
        if entry.file_type()?.is_file() && entry.path().extension().is_some_and(|ext| ext == "gpg")
        {
            files.push(entry.path());
        }
    }
    files.sort();
    Ok(files)
}

/// Read the keyring at `path`, up to [`MAX_KEYRING`], or `None` where no file
/// is there. This is how every keyring source reaches the trusted set.
fn read_keyring_path(path: &Path) -> Result<Option<Vec<u8>>> {
    let subject = format!("the keyring '{}'", path.display());
    read_key_path(path, &subject, MAX_KEYRING)
}

/// Read an opened keyring, holding it to its kind and to [`MAX_KEYRING`] through
/// [`read_key_source`], the reader every key source is read under. `name` is
/// what a refusal reports, so an operator can find the entry that named it.
///
/// The ceiling a keyring is held to is its own: a keyring carries certificates
/// rather than base64 lines, and refusing one over the ceiling by name rather
/// than reading the part it admits is the rule `gpgkeypath` already states for
/// an entry that names nothing.
pub(crate) fn read_keyring_fd(fd: OwnedFd, name: &str) -> Result<Vec<u8>> {
    read_key_source(fd, &format!("the keyring '{name}'"), MAX_KEYRING)
}

/// A process-unique scratch directory path for one test fixture: the GnuPG home
/// directory its `gpg` runs work in, or a directory of keyring files. The
/// fixtures of this module and of [`verify`] both take their paths from it.
#[cfg(test)]
fn scratch_dir() -> PathBuf {
    use std::sync::atomic::{AtomicU64, Ordering};

    static COUNTER: AtomicU64 = AtomicU64::new(0);
    std::env::temp_dir().join(format!(
        "ostrya-gpg-{}-{}",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    ))
}

/// Parse a status-line epoch field, treating `0` as absent. The reference
/// reader the differential cases in [`verify`] compare against reads the
/// `gpgv` status stream through it.
#[cfg(test)]
fn parse_epoch(field: &str) -> Option<u64> {
    match field.parse::<u64>() {
        Ok(0) => None,
        Ok(secs) => Some(secs),
        Err(_) => None,
    }
}

/// Wrap a spawn failure, naming the missing program when that is the cause.
#[cfg(feature = "sign-gpg")]
fn spawn_err(program: &str, err: &std::io::Error) -> Error {
    if err.kind() == std::io::ErrorKind::NotFound {
        Error::Signature(format!("{program}: program not found in PATH"))
    } else {
        Error::Signature(format!("{program}: {err}"))
    }
}

/// The human-readable failure text of a finished gpg run: the non-status
/// stderr lines, or the exit status when gpg said nothing.
#[cfg(feature = "sign-gpg")]
fn failure_text(output: &std::process::Output) -> String {
    let stderr = String::from_utf8_lossy(&output.stderr);
    let text = stderr
        .lines()
        .filter(|line| !line.starts_with(STATUS_PREFIX))
        .collect::<Vec<_>>()
        .join("; ");
    if text.trim().is_empty() {
        format!("exit status {}", output.status)
    } else {
        text
    }
}

/// The GPG public types move freely across tasks and threads.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    #[cfg(feature = "sign-gpg")]
    assert_send_sync::<GpgSigner>();
    assert_send_sync::<GpgVerifier>();
};

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

    #[test]
    fn dearmor_passes_binary_through() {
        let binary = [0x99, 0x01, 0x0d, 0x04];
        assert_eq!(dearmor(&binary).unwrap(), binary);
    }

    #[test]
    fn dearmor_decodes_an_armored_block() {
        let armored = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\
Comment: a header\n\
\n\
aGVsbG8=\n\
=abcd\n\
-----END PGP PUBLIC KEY BLOCK-----\n";
        assert_eq!(dearmor(armored.as_bytes()).unwrap(), b"hello");
    }

    #[test]
    fn dearmor_concatenates_blocks_and_tolerates_missing_blank_line() {
        let armored = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\
aGVs\n\
bG8=\n\
-----END PGP PUBLIC KEY BLOCK-----\n\
-----BEGIN PGP PUBLIC KEY BLOCK-----\n\
\n\
IHdvcmxk\n\
-----END PGP PUBLIC KEY BLOCK-----\n";
        assert_eq!(dearmor(armored.as_bytes()).unwrap(), b"hello world");
    }

    #[test]
    fn keyring_files_in_selects_gpg_and_sorts() {
        let dir = scratch_dir();
        std::fs::create_dir_all(&dir).unwrap();
        for name in ["b.gpg", "a.gpg", "notes.txt", "keyring"] {
            std::fs::write(dir.join(name), b"").unwrap();
        }
        let names: Vec<String> = keyring_files_in(&dir)
            .unwrap()
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(names, ["a.gpg", "b.gpg"]);
    }

    #[test]
    fn keyring_files_in_missing_dir_is_empty() {
        assert!(keyring_files_in(&scratch_dir()).unwrap().is_empty());
    }

    /// Whether the `gpg` binary answers. The keyring cases below build their
    /// fixtures with it, so an absent binary skips them and never passes one.
    fn gpg_available() -> bool {
        std::process::Command::new("gpg")
            .arg("--version")
            .output()
            .is_ok_and(|out| out.status.success())
    }

    /// A private GnuPG home holding freshly generated, passphrase-free ed25519
    /// signing keys, under the test scratch tree. Every `gpg` run names this
    /// directory with `--homedir`, 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 directory.
    struct KeyFixture {
        dir: PathBuf,
        /// Whether every `gpg` run in this home stands at [`FAKED_CLOCK`].
        faked: bool,
    }

    impl KeyFixture {
        /// A new home directory holding one key for `uid` that never expires.
        fn new(uid: &str) -> KeyFixture {
            let fixture = KeyFixture {
                dir: KeyFixture::make_dir(),
                faked: false,
            };
            fixture.add_key(uid);
            fixture
        }

        /// A new home directory holding one key for `uid` that was created at
        /// the instant [`FAKED_CLOCK`] names and lives for `expiry` from it.
        ///
        /// Every `gpg` run in this home stands at that instant, so a signature
        /// it makes was made while the key was live. The verify path reads the
        /// real clock, which is what makes an expired key expired.
        fn expiring(uid: &str, expiry: &str) -> KeyFixture {
            let fixture = KeyFixture {
                dir: KeyFixture::make_dir(),
                faked: true,
            };
            fixture.generate(uid, expiry);
            fixture
        }

        /// A fresh directory under the test scratch tree, readable by its owner
        /// alone, which is what `gpg` asks of a home directory.
        fn make_dir() -> PathBuf {
            use std::os::unix::fs::DirBuilderExt;
            let dir = scratch_dir();
            std::fs::DirBuilder::new().mode(0o700).create(&dir).unwrap();
            dir
        }

        /// Generate one more key, for `uid`, in the same home directory.
        fn add_key(&self, uid: &str) {
            self.generate(uid, "never");
        }

        /// Generate one key for `uid` with the lifetime `expiry`.
        fn generate(&self, uid: &str, expiry: &str) {
            let status = self
                .gpg()
                .args(["--pinentry-mode", "loopback", "--passphrase", ""])
                .args(["--quick-gen-key", uid, "ed25519", "sign", expiry])
                .status()
                .unwrap();
            assert!(status.success(), "gpg --quick-gen-key failed");
        }

        /// Set the first 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 primary = self.fingerprint();
            let status = self
                .gpg()
                .args(["--pinentry-mode", "loopback", "--passphrase", ""])
                .args(["--faked-system-time", when])
                .args(["--quick-set-expire", &primary, expiry])
                .status()
                .unwrap();
            assert!(status.success(), "gpg --quick-set-expire failed");
        }

        /// One detached signature over `payload` by the home's first key.
        fn sign(&self, payload: &[u8]) -> Vec<u8> {
            let file = self.dir.join("payload");
            std::fs::write(&file, payload).unwrap();
            let out = self
                .gpg()
                .args(["--pinentry-mode", "loopback", "--passphrase", ""])
                .args(["--detach-sign", "--output", "-", "--local-user"])
                .arg(format!("{}!", self.fingerprint()))
                .arg(&file)
                .output()
                .unwrap();
            assert!(out.status.success() && !out.stdout.is_empty());
            out.stdout
        }

        /// Add a signing subkey to the home's first key.
        fn add_signing_subkey(&self) {
            let primary = self.fingerprint();
            let status = self
                .gpg()
                .args(["--pinentry-mode", "loopback", "--passphrase", ""])
                .args(["--quick-add-key", &primary, "ed25519", "sign", "never"])
                .status()
                .unwrap();
            assert!(status.success(), "gpg --quick-add-key failed");
        }

        /// The fingerprint of the home's first key, uppercase hex.
        fn fingerprint(&self) -> 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))
                .next()
                .unwrap()
        }

        /// A `gpg` command bound to this home directory, batch mode.
        fn gpg(&self) -> std::process::Command {
            let mut cmd = std::process::Command::new("gpg");
            cmd.arg("--homedir").arg(&self.dir).arg("--batch");
            if self.faked {
                cmd.args(["--faked-system-time", FAKED_CLOCK]);
            }
            cmd
        }

        /// The exported public keyring, binary or ASCII-armored.
        fn export(&self, armored: bool) -> Vec<u8> {
            let mut cmd = self.gpg();
            cmd.arg("--export");
            if armored {
                cmd.arg("--armor");
            }
            let out = cmd.output().unwrap();
            assert!(out.status.success() && !out.stdout.is_empty());
            out.stdout
        }

        /// The keybox `gpg` keeps this home directory's public keys in.
        fn keybox(&self) -> Vec<u8> {
            std::fs::read(self.dir.join("pubring.kbx")).unwrap()
        }

        /// Bind one more user id to the home's first key.
        fn add_uid(&self, uid: &str) {
            let primary = self.fingerprint();
            let status = self
                .gpg()
                .args(["--pinentry-mode", "loopback", "--passphrase", ""])
                .args(["--quick-add-uid", &primary, uid])
                .status()
                .unwrap();
            assert!(status.success(), "gpg --quick-add-uid failed");
        }

        /// The `--with-colons` key listing of this home, as `gpg` writes it.
        /// The differential listing case reads its `pub`, `fpr`, and `uid`
        /// records as the reference.
        fn listing(&self) -> String {
            let out = self
                .gpg()
                .args(["--with-colons", "--fixed-list-mode", "--list-keys"])
                .output()
                .unwrap();
            assert!(out.status.success(), "gpg --list-keys failed");
            String::from_utf8_lossy(&out.stdout).into_owned()
        }

        /// The primary-key fingerprints `gpg` reports over `keyring`, in
        /// listing order. This is the reader the `ostree` tool drives through
        /// gpgme, so a keyring it lists is a keyring the tool reads.
        fn fingerprints_of(&self, keyring: &[u8]) -> Vec<String> {
            let path = self.dir.join("listed.gpg");
            std::fs::write(&path, keyring).unwrap();
            let out = std::process::Command::new("gpg")
                .arg("--homedir")
                .arg(&self.dir)
                .arg("--batch")
                .arg("--no-default-keyring")
                .arg("--keyring")
                .arg(&path)
                .args(["--with-colons", "--list-keys"])
                .output()
                .unwrap();
            assert!(
                out.status.success(),
                "gpg --list-keys over a keyring failed"
            );
            let text = String::from_utf8_lossy(&out.stdout).into_owned();
            let mut found = Vec::new();
            let mut wanted = false;
            for line in text.lines() {
                let mut fields = line.split(':');
                match fields.next() {
                    Some("pub") => wanted = true,
                    Some("fpr") if wanted => {
                        wanted = false;
                        found.push(fields.nth(8).unwrap().to_owned());
                    }
                    Some("sub") => wanted = false,
                    _ => {}
                }
            }
            found
        }

        /// The `gpg --export-secret-keys` stream of this home's keys, which
        /// carries no transferable public key.
        fn export_secret(&self) -> Vec<u8> {
            let out = self
                .gpg()
                .args(["--pinentry-mode", "loopback", "--passphrase", ""])
                .arg("--export-secret-keys")
                .output()
                .unwrap();
            assert!(out.status.success() && !out.stdout.is_empty());
            out.stdout
        }

        /// The `gpg --export` stream of the one key `selector` names.
        fn export_one(&self, selector: &str) -> Vec<u8> {
            let out = self
                .gpg()
                .arg("--export")
                .arg("--")
                .arg(selector)
                .output()
                .unwrap();
            assert!(out.status.success() && !out.stdout.is_empty());
            out.stdout
        }

        /// The legacy keyring `gpg --import` writes for this home's own keys.
        /// GnuPG puts a Trust packet after the primary key packet, after each
        /// user id packet, and after each signature packet of such a keyring,
        /// which is the form the `ostree` tool's own import leaves at the
        /// repository root.
        fn legacy_keyring(&self) -> Vec<u8> {
            self.imported_keyring("legacy", &[&self.export(false)])
        }

        /// The legacy keyring `gpg --import` writes for `streams`, imported in
        /// the order they stand in. `name` names the home directory the import
        /// runs in, so one fixture builds more than one such keyring.
        ///
        /// `gpg` writes a keybox when it creates a keyring file itself, and a
        /// legacy keyring when the file is already there, so the import runs
        /// in a home of its own over an empty keyring file.
        fn imported_keyring(&self, name: &str, streams: &[&[u8]]) -> Vec<u8> {
            use std::os::unix::fs::DirBuilderExt;
            let home = self.dir.join(name);
            std::fs::DirBuilder::new()
                .mode(0o700)
                .create(&home)
                .unwrap();
            let ring = home.join("ring.gpg");
            std::fs::write(&ring, b"").unwrap();
            for (index, stream) in streams.iter().enumerate() {
                let source = home.join(format!("offered-{index}.gpg"));
                std::fs::write(&source, stream).unwrap();
                let status = std::process::Command::new("gpg")
                    .arg("--homedir")
                    .arg(&home)
                    .arg("--batch")
                    .arg("--no-default-keyring")
                    .arg("--keyring")
                    .arg(&ring)
                    .arg("--import")
                    .arg(&source)
                    .status()
                    .unwrap();
                assert!(status.success(), "gpg --import into a keyring failed");
            }
            std::fs::read(&ring).unwrap()
        }

        /// Revoke the home's first key by importing the revocation certificate
        /// `gpg` stored when it generated it.
        fn revoke_primary(&self) {
            let path = self.dir.join("revocation.asc");
            std::fs::write(&path, self.revocation_armor()).unwrap();
            let status = self.gpg().arg("--import").arg(&path).status().unwrap();
            assert!(status.success(), "gpg --import of the revocation failed");
        }

        /// The key revocation signature packet `gpg` stored for the home's
        /// first key, in the binary form.
        fn revocation_packet(&self) -> Vec<u8> {
            let packet = dearmor(&self.revocation_armor()).unwrap();
            let (spans, framed) = packet_spans(&packet);
            assert_eq!((spans.len(), framed), (1, packet.len()));
            packet
        }

        /// Import a certificate stream into this home.
        fn import(&self, bytes: &[u8]) {
            let path = self.dir.join("import.gpg");
            std::fs::write(&path, bytes).unwrap();
            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 the stream `gpg --desig-revoke` writes,
        /// and it does so whether or not the home holds the revoker's
        /// certificate: without it the run reports "no public key - can't apply
        /// revocation certificate", and with it "invalid revocation
        /// certificate: Bad signature - rejected" against the revoker's own key
        /// id. Either way it reports "revocation certificate added" for the
        /// revoked key and merges the class 0x20 signature into the certificate
        /// it holds, so the export of the home carries the packet.
        fn import_merging(&self, bytes: &[u8]) {
            let path = self.dir.join("import.gpg");
            std::fs::write(&path, bytes).unwrap();
            self.gpg().arg("--import").arg(&path).status().unwrap();
        }

        /// Designate the key `revoker` names as a revoker of this home's first
        /// 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.fingerprint());
            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");
            dearmor(&std::fs::read(&path).unwrap()).unwrap()
        }

        /// A `gpg` command bound to this home that reads its answers from
        /// standard input, for the commands that take no batch form.
        fn gpg_interactive(&self) -> std::process::Command {
            let mut cmd = std::process::Command::new("gpg");
            cmd.arg("--homedir").arg(&self.dir).args([
                "--no-tty",
                "--no-batch",
                "--command-fd",
                "0",
                "--pinentry-mode",
                "loopback",
                "--passphrase",
                "",
            ]);
            cmd
        }

        /// The armored block of the revocation certificate `gpg` stored for
        /// the home's first key. The stored file carries prose before the
        /// block, and a colon before the block's first dash so that an
        /// accidental import does nothing.
        fn revocation_armor(&self) -> Vec<u8> {
            let stored = self
                .dir
                .join("openpgp-revocs.d")
                .join(format!("{}.rev", self.fingerprint()));
            let text = std::fs::read_to_string(&stored).unwrap();
            let at = text.find("-----BEGIN PGP").unwrap();
            text.as_bytes()[at..].to_vec()
        }
    }

    /// 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: std::process::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");
    }

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

    /// A binary keyring holding one certificate loads to that certificate.
    #[test]
    fn loads_a_binary_keyring() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Binary <binary@ostrya.example>");
        let verifier = GpgVerifier::from_keyring_bytes([home.export(false)]).unwrap();
        assert_eq!(verifier.certs.len(), 1);
    }

    /// An armored keyring loads to the same certificate as the binary form,
    /// and the armor decoder reaches the binary export byte for byte, so the
    /// parser reads the same packet stream out of either form.
    #[test]
    fn loads_an_armored_keyring() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Armored <armored@ostrya.example>");
        let exported = home.export(false);
        assert_eq!(dearmor(&home.export(true)).unwrap(), exported);
        let binary = GpgVerifier::from_keyring_bytes([&exported]).unwrap();
        let armored = GpgVerifier::from_keyring_bytes([home.export(true)]).unwrap();
        assert_eq!(armored.certs.len(), 1);
        assert_eq!(armored.certs, binary.certs);
    }

    /// A keyring holding two certificates loads both.
    #[test]
    fn loads_a_two_certificate_keyring() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("First <first@ostrya.example>");
        home.add_key("Second <second@ostrya.example>");
        let verifier = GpgVerifier::from_keyring_bytes([home.export(false)]).unwrap();
        assert_eq!(verifier.certs.len(), 2);
    }

    /// An empty keyring loads and holds no certificate. An optional keyring
    /// that is there and holds nothing is not a failure.
    #[test]
    fn loads_an_empty_keyring() {
        let verifier = GpgVerifier::from_keyring_bytes([b""]).unwrap();
        assert!(verifier.certs.is_empty());
    }

    /// A truncated keyring is refused by the name of the blob that carried it.
    #[test]
    fn refuses_a_truncated_keyring() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Cut <cut@ostrya.example>");
        let keyring = home.export(false);
        let cut = &keyring[..keyring.len() / 2];
        let err = GpgVerifier::from_keyring_bytes([cut]).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("keyring blob 0")
                && m.contains("OpenPGP keyring")),
            "{err}"
        );
    }

    /// A GnuPG keybox is refused by name. rPGP reads an OpenPGP packet stream,
    /// and a keybox is a container of another kind, so reading it as a keyring
    /// would leave the trusted set empty with nothing said about it.
    #[test]
    fn refuses_a_keybox() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Box <box@ostrya.example>");
        let keybox = home.keybox();
        assert_eq!(
            &keybox[KEYBOX_MAGIC_OFFSET..KEYBOX_MAGIC_OFFSET + KEYBOX_MAGIC.len()],
            KEYBOX_MAGIC
        );
        let err = GpgVerifier::from_keyring_bytes([keybox]).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("keyring blob 0")
                && m.contains("keybox")),
            "{err}"
        );
    }

    /// A keyring over the four-mebibyte ceiling is refused by name, and the
    /// refusal states the ceiling. The blob is bounded before it is parsed.
    #[test]
    fn refuses_an_oversized_keyring() {
        let oversized = vec![0u8; MAX_KEYRING as usize + 1];
        let err = GpgVerifier::from_keyring_bytes([oversized]).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("keyring blob 0")
                && m.contains("ceiling")),
            "{err}"
        );
    }

    /// A keyring holding more than 256 certificates is refused by name, and
    /// the refusal states the cap. The keyring is one certificate repeated,
    /// which is 257 transferable public keys in one packet stream.
    #[test]
    fn refuses_too_many_certificates() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Many <many@ostrya.example>");
        let one = home.export(false);
        let many = one.repeat(MAX_KEYRING_CERTS + 1);
        assert!(many.len() as u64 <= MAX_KEYRING);
        let err = GpgVerifier::from_keyring_bytes([&many]).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("keyring blob 0")
                && m.contains("256 certificates")),
            "{err}"
        );
        // One certificate short of the cap loads, so the cap is what refused.
        let allowed = one.repeat(MAX_KEYRING_CERTS);
        let verifier = GpgVerifier::from_keyring_bytes([&allowed]).unwrap();
        assert_eq!(verifier.certs.len(), MAX_KEYRING_CERTS);
    }
    /// The user ids each certificate carries, one list per certificate, with
    /// both the certificates and the ids sorted, so two trusted sets compare as
    /// one value whatever order their keyrings held them in.
    fn user_ids(verifier: &GpgVerifier) -> Vec<Vec<String>> {
        let mut all: Vec<Vec<String>> = verifier
            .certs
            .iter()
            .map(|cert| {
                let mut ids: Vec<String> = cert
                    .details
                    .users
                    .iter()
                    .map(|user| String::from_utf8_lossy(user.id.id()).into_owned())
                    .collect();
                ids.sort();
                ids
            })
            .collect();
        all.sort();
        all
    }

    /// A legacy keyring, which carries a Trust packet after the primary key
    /// packet and after each user id and signature packet, parses to what the
    /// `gpg --export` stream of the same keys parses to: the same certificate
    /// count, the same user ids, and the same subkeys.
    #[test]
    fn loads_a_trust_packet_keyring() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Trust <trust@ostrya.example>");
        home.add_key("Second <second@ostrya.example>");
        let exported = home.export(false);
        let legacy = home.legacy_keyring();
        // The fixture is the shape under test: the two forms differ in bytes.
        assert_ne!(legacy, exported);
        assert!(legacy.len() > exported.len());

        let from_export = GpgVerifier::from_keyring_bytes([&exported]).unwrap();
        let from_legacy = GpgVerifier::from_keyring_bytes([&legacy]).unwrap();
        assert_eq!(from_legacy.certs.len(), 2);
        assert_eq!(from_legacy.certs.len(), from_export.certs.len());
        assert_eq!(user_ids(&from_legacy), user_ids(&from_export));
        assert_eq!(
            user_ids(&from_legacy),
            [
                ["Second <second@ostrya.example>"],
                ["Trust <trust@ostrya.example>"]
            ]
        );
        let subkeys = |v: &GpgVerifier| -> usize {
            v.certs.iter().map(|cert| cert.public_subkeys.len()).sum()
        };
        assert_eq!(subkeys(&from_legacy), subkeys(&from_export));
    }

    /// A signing subkey reaches the trusted set out of a legacy keyring. The
    /// subkey packet stands after the primary key's Trust packet, so this is
    /// what a keyring holding Trust packets loses when they reach the parser.
    #[test]
    fn loads_a_subkey_from_a_trust_packet_keyring() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Subkey <subkey@ostrya.example>");
        home.add_signing_subkey();
        let verifier = GpgVerifier::from_keyring_bytes([home.legacy_keyring()]).unwrap();
        assert_eq!(verifier.certs.len(), 1);
        assert_eq!(verifier.certs[0].public_subkeys.len(), 1);
    }

    /// A keyring whose packet stream stops framing part way through is refused
    /// by the name of the blob that carried it, and every certificate it holds
    /// goes with it.
    ///
    /// The stream holds one whole certificate, then a second one whose primary
    /// key packet is followed by a Trust packet written with an indeterminate
    /// length. The packet walk frames a fixed length alone, so it stops there,
    /// while the certificate parser reads the rest of the stream as the body of
    /// that packet. The second certificate stands past the point the walk
    /// framed to and carries its own Trust packets there, so it would reach the
    /// trusted set with no user id and no subkey. The refusal covers the whole
    /// keyring, so a verification works over a keyring that was read whole.
    ///
    /// The reference tools read such a keyring up to the packet they stop at
    /// and trust the certificates that stand before it. Measured over this
    /// shape, `gpgv` 2.4.9 reports `GOODSIG` at exit 0 over a signature the
    /// first certificate made and
    /// `[don't know]: indeterminate length for invalid packet type 12`,
    /// `keydb_search failed: Invalid packet`, `ERRSIG`, and `NO_PUBKEY` at
    /// exit 2 over a signature the second one made; `gpg --list-keys` over the
    /// file lists the first key alone; and `ostree show --gpg-verify-remote`
    /// reports `Good signature from "..."` for the first and
    /// `Can't check signature: public key not found` for the second.
    #[test]
    fn refuses_a_keyring_holding_a_certificate_past_its_framed_prefix() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let first = KeyFixture::new("First <first@ostrya.example>");
        let second = KeyFixture::new("Second <second@ostrya.example>");
        second.add_signing_subkey();
        // A Trust packet, tag 12, in the old header form with length type 3,
        // the indeterminate length.
        let indeterminate_trust = [0xb3];
        let legacy = second.legacy_keyring();
        let mut keyring = first.export(false);
        keyring.extend_from_slice(&insert_after_primary(&legacy, &indeterminate_trust));
        // The fixture is the shape under test: the walk stops inside the second
        // certificate and the run split answers nothing.
        assert!(packet_spans(&keyring).1 < keyring.len());
        assert!(certificate_chunks(&keyring).is_none());

        let err = GpgVerifier::from_keyring_bytes([&keyring]).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("keyring blob 0")
                && m.contains("OpenPGP keyring")),
            "{err}"
        );

        // The same two certificates, in a keyring holding that packet nowhere,
        // load with the user id and the subkey each of them states.
        let intact = [first.export(false), legacy].concat();
        let verifier = GpgVerifier::from_keyring_bytes([&intact]).unwrap();
        assert_eq!(verifier.certs.len(), 2);
        assert_eq!(verifier.certs[1].details.users.len(), 1);
        assert_eq!(verifier.certs[1].public_subkeys.len(), 1);
    }

    /// The certificate cap counts the certificates a keyring parses to,
    /// whether or not the keyring carries Trust packets: 257 legacy
    /// certificates are refused by name and 256 load.
    #[test]
    fn refuses_too_many_certificates_with_trust_packets() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Capped <capped@ostrya.example>");
        let one = home.legacy_keyring();
        let many = one.repeat(MAX_KEYRING_CERTS + 1);
        assert!(many.len() as u64 <= MAX_KEYRING);
        let err = GpgVerifier::from_keyring_bytes([&many]).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("keyring blob 0")
                && m.contains("256 certificates")),
            "{err}"
        );
        let allowed = one.repeat(MAX_KEYRING_CERTS);
        let verifier = GpgVerifier::from_keyring_bytes([&allowed]).unwrap();
        assert_eq!(verifier.certs.len(), MAX_KEYRING_CERTS);
    }

    /// A keyring carrying no Trust packet parses to the packets it holds, byte
    /// for byte, and a packet standing ahead of its first certificate is
    /// dropped. A keyring holding no packet parses to no certificate, and a
    /// stream the header parser cannot frame to its end is refused by the name
    /// of the source.
    #[test]
    fn parse_keyring_reads_the_packets_of_a_trust_free_stream() {
        assert!(parse_keyring(b"", SUBJECT).unwrap().is_empty());
        // No OpenPGP packet header opens with these bits.
        refuses_the_stream(b"\x00\x01\x02");
        if !gpg_available() {
            eprintln!("skipping the exported-keyring half: gpg not available");
            return;
        }
        let home = KeyFixture::new("Untouched <untouched@ostrya.example>");
        let exported = home.export(false);
        let read = parse_keyring(&exported, SUBJECT).unwrap();
        assert_eq!(read.len(), 1);
        assert_eq!(read[0].1, exported);
        // A packet standing ahead of the first Public-Key packet belongs to no
        // certificate, so the keyring parses to the certificate after it.
        let mut prefixed = home.revocation_packet();
        prefixed.extend_from_slice(&exported);
        let read = parse_keyring(&prefixed, SUBJECT).unwrap();
        assert_eq!(read.len(), 1);
        assert_eq!(read[0].1, exported);
        // A truncated keyring is refused by the name of the source.
        refuses_the_stream(&exported[..exported.len() / 2]);
    }

    /// Assert that [`parse_keyring`] refuses `stream` by the name of the
    /// source, which is what a keyring the certificate reader does not read
    /// whole draws.
    fn refuses_the_stream(stream: &[u8]) {
        let err = parse_keyring(stream, SUBJECT).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains(SUBJECT)
                && m.contains("OpenPGP keyring")),
            "{err}"
        );
    }

    /// The packets a keyring parses to, concatenated: the stream with its Trust
    /// packets dropped and with any packet standing ahead of its first
    /// certificate dropped.
    fn certificate_stream(keyring: &[u8]) -> Vec<u8> {
        parse_keyring(keyring, SUBJECT)
            .unwrap()
            .into_iter()
            .flat_map(|(_, packets)| packets)
            .collect()
    }

    /// The subject a refusal over the repository's own keyring names.
    const SUBJECT: &str = "the keyring 'origin.trustedkeys.gpg'";

    /// The instant a faked-clock fixture stands at, 2025-01-01T00:00:00Z.
    const FAKED_CLOCK: &str = "20250101T000000!";

    /// The payload a fixture's signature covers.
    const PAYLOAD: &[u8] = b"ostrya commit payload";

    /// Whether the certificates `keyring` holds report `blob` as a valid
    /// signature over [`PAYLOAD`]. This is the verdict a remote's trusted
    /// keyring draws after an import, read through the same engine a
    /// verification runs.
    fn signature_is_valid(keyring: &[u8], blob: &[u8]) -> bool {
        let certs = GpgVerifier::from_keyring_bytes([keyring]).unwrap().certs;
        verify::verify_signatures(&certs, PAYLOAD, &[blob.to_vec()])
            .unwrap()
            .valid
    }

    /// An import into no keyring writes the offered stream as it stands and
    /// counts each certificate, `gpg` reads the result, and a repeated import
    /// counts none and leaves the bytes alone.
    #[test]
    fn an_import_writes_the_offered_certificates() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("First <first@ostrya.example>");
        home.add_key("Second <second@ostrya.example>");
        let offered = home.export(false);

        let (imported, keyring) = merge_keyring(b"", &offered, &[], SUBJECT).unwrap();
        assert_eq!(imported, 2);
        assert_eq!(keyring, offered);
        // The keyring the import writes is one `gpg` reads, which is the
        // reader the `ostree` tool drives through gpgme.
        assert_eq!(home.fingerprints_of(&keyring).len(), 2);

        let (again, repeated) = merge_keyring(&keyring, &offered, &[], SUBJECT).unwrap();
        assert_eq!(again, 0);
        assert_eq!(repeated, keyring);
    }

    /// An import onto a keyring GnuPG wrote keeps that keyring byte for byte
    /// and appends the packets of the added certificate. `gpg` reads the
    /// result, which holds both keys, so a keyring carrying Trust packets for
    /// one key and none for another is a keyring both implementations read.
    #[test]
    fn an_import_keeps_the_keyring_it_was_given() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let held = KeyFixture::new("Held <held@ostrya.example>");
        let added = KeyFixture::new("Added <added@ostrya.example>");
        let existing = held.legacy_keyring();
        let offered = added.export(false);

        let (imported, keyring) = merge_keyring(&existing, &offered, &[], SUBJECT).unwrap();
        assert_eq!(imported, 1);
        assert_eq!(&keyring[..existing.len()], &existing[..]);
        assert_eq!(&keyring[existing.len()..], &offered[..]);
        let listed = held.fingerprints_of(&keyring);
        assert_eq!(listed, [held.fingerprint(), added.fingerprint()]);
    }

    /// An import onto an armored keyring keeps the packet stream that keyring
    /// held and writes it back in the binary form: the armor decodes to the
    /// packets the binary export of the same key holds, those packets open the
    /// result, and the added certificate's packets follow them. `gpg` reads the
    /// result and lists both keys.
    #[test]
    fn an_import_keeps_the_packet_stream_of_an_armored_keyring() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let held = KeyFixture::new("Armored <armored@ostrya.example>");
        let added = KeyFixture::new("Added <added@ostrya.example>");
        let binary = held.export(false);
        let armored = held.export(true);
        let offered = added.export(false);
        assert!(armored.starts_with(b"-----BEGIN PGP"));

        let (imported, keyring) = merge_keyring(&armored, &offered, &[], SUBJECT).unwrap();
        assert_eq!(imported, 1);
        assert_eq!(&keyring[..binary.len()], &binary[..]);
        assert_eq!(&keyring[binary.len()..], &offered[..]);
        let listed = held.fingerprints_of(&keyring);
        assert_eq!(listed, [held.fingerprint(), added.fingerprint()]);
    }

    /// The Trust packets are the whole difference between the keyring GnuPG
    /// writes and the keyring this import writes for the same keys.
    ///
    /// A legacy keyring offered for import loses its Trust packets, so the
    /// keyring the import writes carries none whichever form the offered stream
    /// took.
    #[test]
    fn the_trust_packets_are_the_whole_difference() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Same <same@ostrya.example>");
        home.add_signing_subkey();
        let exported = home.export(false);
        let legacy = home.legacy_keyring();
        assert!(legacy.len() > exported.len());
        assert_eq!(certificate_stream(&legacy), exported);
        for offered in [&exported, &legacy] {
            let (imported, keyring) = merge_keyring(b"", offered, &[], SUBJECT).unwrap();
            assert_eq!(imported, 1);
            assert_eq!(keyring, exported);
        }
        // A selection off a legacy keyring writes the selected certificate
        // without its Trust packets as well.
        let selector = [home.fingerprint()];
        let (imported, keyring) = merge_keyring(b"", &legacy, &selector, SUBJECT).unwrap();
        assert_eq!(imported, 1);
        assert_eq!(keyring, exported);
    }

    /// Splice one packet in right after a certificate's primary key packet,
    /// where a key revocation signature stands.
    fn insert_after_primary(cert: &[u8], packet: &[u8]) -> Vec<u8> {
        let (spans, framed) = packet_spans(cert);
        assert_eq!(framed, cert.len());
        assert_eq!(spans[0].0, Tag::PublicKey);
        let at = spans[0].1.end;
        let mut spliced = cert[..at].to_vec();
        spliced.extend_from_slice(packet);
        spliced.extend_from_slice(&cert[at..]);
        spliced
    }

    /// A re-export carrying a key revocation replaces the certificate the
    /// keyring holds for that key, and the import counts no key.
    ///
    /// The keyring the merge is given is the one the `ostree` tool's own import
    /// leaves at the repository root, which carries the Trust packets. The
    /// merged keyring holds the offered certificate where the held one stood,
    /// which is the shape the tool writes: measured against `ostree` 2026.1
    /// over the re-export of a revoked RSA key, the merged run carried the key
    /// revocation right after the primary key packet and ahead of the first
    /// user id packet, and the tool reported `Imported 0 GPG keys`.
    #[test]
    fn a_revoked_re_export_replaces_the_held_certificate() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Revoked <revoked@ostrya.example>");
        let unrevoked = home.export(false);
        let held = home.legacy_keyring();
        home.revoke_primary();
        let revoked = home.export(false);
        // The fixture is the shape under test: the revoked export carries the
        // revocation packet the unrevoked one does not.
        assert!(revoked.len() > unrevoked.len());

        let (imported, keyring) = merge_keyring(&held, &revoked, &[], SUBJECT).unwrap();
        assert_eq!(imported, 0);
        assert_ne!(keyring, certificate_stream(&held));
        // One certificate run per key, holding the offered packets.
        assert_eq!(keyring, revoked);
        // `gpg` reads the result, which is the reader the `ostree` tool drives
        // through gpgme, and the certificate it holds revokes the key.
        assert_eq!(home.fingerprints_of(&keyring), [home.fingerprint()]);
        let certs = GpgVerifier::from_keyring_bytes([&keyring]).unwrap().certs;
        assert_eq!(certs.len(), 1);
        assert!(verify::key_revoked(&certs[0], certs.as_slice()));

        // The Trust packets stay the whole difference against the keyring
        // GnuPG writes for the same two imports.
        let gnupg = home.imported_keyring("merged", &[&unrevoked, &revoked]);
        assert!(gnupg.len() > keyring.len());
        assert_eq!(certificate_stream(&gnupg), keyring);

        // One offered stream carrying both states of the key reaches the same
        // keyring whichever order they stand in, and counts one key. The tool
        // answers the same way: over the revoked export alone and over the two
        // exports concatenated in either order, `ostree` 2026.1 reported
        // `Imported 1 GPG key` and wrote three byte-identical keyrings, each
        // holding the revocation.
        for stream in [
            revoked.clone(),
            [unrevoked.clone(), revoked.clone()].concat(),
            [revoked.clone(), unrevoked.clone()].concat(),
        ] {
            let (imported, fresh) = merge_keyring(b"", &stream, &[], SUBJECT).unwrap();
            assert_eq!(imported, 1);
            assert_eq!(fresh, revoked);
        }
    }

    /// A key revocation signature another key made, stapled onto an offered
    /// certificate, does not strike the held key out of the keyring.
    ///
    /// A revocation is verified before it is honored, so a packet anyone can
    /// attach carries no weight and the keyring keeps the bytes it held. This
    /// is the rule the verify engine applies to the same packet.
    #[test]
    fn a_stapled_revocation_does_not_replace_the_held_certificate() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Kept <kept@ostrya.example>");
        let other = KeyFixture::new("Other <other@ostrya.example>");
        let existing = home.export(false);
        let offered = insert_after_primary(&existing, &other.revocation_packet());

        // The stapled packet reaches the parsed certificate, so it is the
        // merge that refused it and not the parse.
        let certs = GpgVerifier::from_keyring_bytes([&offered]).unwrap().certs;
        assert_eq!(certs.len(), 1);
        assert_eq!(certs[0].details.revocation_signatures.len(), 1);
        assert!(!verify::key_revoked(&certs[0], certs.as_slice()));

        let (imported, keyring) = merge_keyring(&existing, &offered, &[], SUBJECT).unwrap();
        assert_eq!(imported, 0);
        assert_eq!(keyring, existing);

        // The same packet over the certificate it was made for replaces it.
        let own = other.export(false);
        let revoked = insert_after_primary(&own, &other.revocation_packet());
        let (imported, keyring) = merge_keyring(&own, &revoked, &[], SUBJECT).unwrap();
        assert_eq!(imported, 0);
        assert_eq!(keyring, revoked);
    }

    /// The certificate streams a revocation a designated revoker made is
    /// stated over: a signing key K that designates a revoker R, R's own
    /// certificate, and the re-export of K carrying the class 0x20 signature R
    /// made over it.
    ///
    /// [`verify`] has its own builder for these states, which splices a
    /// revocation into a certificate that carries no designation. The import
    /// cases need no such state, so this builder reaches every stream it needs
    /// through `gpg` runs alone and the splicing stays where it is.
    struct Revoked {
        /// K's home, which made [`Revoked::blob`] and reads every keyring the
        /// cases build.
        home: KeyFixture,
        /// K's primary key fingerprint, uppercase hex.
        key: String,
        /// R's primary key fingerprint, uppercase hex.
        revoker: String,
        /// R's certificate.
        revoker_cert: Vec<u8>,
        /// K carrying the designation and no revocation.
        designating: Vec<u8>,
        /// The re-export of K carrying the revocation R made.
        revoked: Vec<u8>,
        /// The detached signature K made over [`PAYLOAD`].
        blob: Vec<u8>,
    }

    impl Revoked {
        fn build() -> Revoked {
            let home = KeyFixture::new("Signing K <k@ostrya.example>");
            let revoker_home = KeyFixture::new("Revoker R <r@ostrya.example>");
            let (key, revoker) = (home.fingerprint(), revoker_home.fingerprint());
            let blob = home.sign(PAYLOAD);
            let revoker_cert = revoker_home.export(false);
            // The designation names the revoker by fingerprint, so K's home
            // holds R's certificate while it writes the self-signature that
            // carries the designation.
            home.import(&revoker_cert);
            home.add_revoker(&revoker);
            let designating = home.export_one(&key);
            // The revocation is made in the home holding R's secret key and a
            // certificate of K that designates it.
            revoker_home.import(&designating);
            let revocation = revoker_home.desig_revoke(&key);
            // The re-export of K carries the class 0x20 signature `gpg`
            // merges into the certificate the home holds.
            home.import_merging(&revocation);
            let revoked = home.export_one(&key);
            let state = Revoked {
                home,
                key,
                revoker,
                revoker_cert,
                designating,
                revoked,
                blob,
            };
            state.assert_shape();
            state
        }

        /// Assert that the streams are the state the cases name: the re-export
        /// carries one key revocation signature the designating certificate
        /// does not, and that revocation is the one R made, so a case fails
        /// where its fixture is not the state it names.
        fn assert_shape(&self) {
            let designating = self.certs(&self.designating);
            assert_eq!(designating[0].details.revocation_signatures.len(), 0);
            let revoked = self.certs(&self.revoked);
            assert_eq!(revoked[0].details.revocation_signatures.len(), 1);
            let revoker = self.certs(&self.revoker_cert);
            assert!(!verify::key_revoked(&revoked[0], &designating));
            assert!(verify::key_revoked(&revoked[0], &revoker));
        }

        /// The certificates `keyring` holds.
        fn certs(&self, keyring: &[u8]) -> Vec<SignedPublicKey> {
            GpgVerifier::from_keyring_bytes([keyring])
                .unwrap()
                .certs
                .to_vec()
        }

        /// What a verifier built over `keyring` answers about the signature K
        /// made: whether it reports the key revoked, and whether the load is
        /// valid.
        fn verdict(&self, keyring: &[u8]) -> (bool, bool) {
            let certs = self.certs(keyring);
            let outcome =
                verify::verify_signatures(&certs, PAYLOAD, std::slice::from_ref(&self.blob))
                    .unwrap();
            assert_eq!(outcome.signatures.len(), 1);
            (outcome.signatures[0].revoked, outcome.valid)
        }
    }

    /// A re-export carrying a key revocation a designated revoker made
    /// replaces the certificate a keyring holding the revoker holds for the
    /// revoked key, the import counts no key, and a verifier built over the
    /// result refuses a signature that key made.
    ///
    /// The revoker is resolved among the certificates of both streams, so the
    /// import and the verdict answer off the same signature for every key one
    /// keyring holds. The `ostree` tool carries the same revocation in by
    /// merging the offered packets into its own keyblock: measured against
    /// `ostree` 2026.1, over a remote whose keyring held K and R, the import
    /// of the re-export reported `Imported 0 GPG keys` at exit 0, the keyring
    /// grew by the class 0x20 packet, and `ostree show
    /// --gpg-verify-remote=origin` then reported `Key revoked`
    /// (`docs/conformance/cli-surface.md`, "P3").
    #[test]
    fn a_designated_revokers_revocation_replaces_the_held_certificate() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let state = Revoked::build();
        // The keyring the `ostree` tool's own import leaves at the repository
        // root, holding the signing key and the revoker, in that order.
        let held = state
            .home
            .imported_keyring("held", &[&state.designating, &state.revoker_cert]);
        // Over the keyring as it stands the signature is good, so the merge is
        // what changes the answer.
        assert_eq!(state.verdict(&certificate_stream(&held)), (false, true));

        let (imported, keyring) = merge_keyring(&held, &state.revoked, &[], SUBJECT).unwrap();
        assert_eq!(imported, 0);
        // The revoked re-export stands where the held run stood, and the
        // revoker's run passes through as it stands.
        assert_eq!(
            keyring,
            [&state.revoked[..], &state.revoker_cert[..]].concat()
        );
        // `gpg` reads the result, which is the reader the `ostree` tool drives
        // through gpgme, and both keys stand in it.
        assert_eq!(
            state.home.fingerprints_of(&keyring),
            [state.key.clone(), state.revoker.clone()]
        );
        assert_eq!(state.verdict(&keyring), (true, false));
    }

    /// The offered stream is read for the revoker as well: a stream carrying
    /// the revoked re-export and the revoker's certificate revokes the key a
    /// keyring holds, whether or not the keyring held the revoker, and the
    /// count reports the revoker as the one key added.
    ///
    /// A `KEY-ID` selector governs what the import writes and not what it
    /// knows. Where the selector names the revoked key alone the revocation
    /// still carries in and the revoker's certificate is not written, so the
    /// keyring states the revocation and no key in it resolves the revoker.
    /// The `ostree` tool answers the same way over both selections: measured
    /// against `ostree` 2026.1, the unselected import reported `Imported 1 GPG
    /// key` and `ostree show --gpg-verify-remote=origin` then reported `Key
    /// revoked`, and the import naming the revoked key reported `Imported 0
    /// GPG keys`, wrote the class 0x20 packet into the keyring, and reported a
    /// good signature (`docs/conformance/cli-surface.md`, "P3").
    #[test]
    fn an_offered_revoker_certificate_resolves_the_revocation() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let state = Revoked::build();
        let held = state.home.imported_keyring("held", &[&state.designating]);
        let offered = [&state.revoked[..], &state.revoker_cert[..]].concat();

        let (imported, keyring) = merge_keyring(&held, &offered, &[], SUBJECT).unwrap();
        assert_eq!(imported, 1);
        assert_eq!(
            keyring,
            [&state.revoked[..], &state.revoker_cert[..]].concat()
        );
        assert_eq!(state.verdict(&keyring), (true, false));

        // The selector names the revoked key alone. The revocation carries in
        // and the revoker's certificate is left out, so the keyring holds one
        // key and the revocation it states resolves no revoker.
        let (imported, keyring) =
            merge_keyring(&held, &offered, std::slice::from_ref(&state.key), SUBJECT).unwrap();
        assert_eq!(imported, 0);
        assert_eq!(keyring, state.revoked);
        assert_eq!(
            state.home.fingerprints_of(&keyring),
            std::slice::from_ref(&state.key)
        );
        assert_eq!(state.verdict(&keyring), (false, true));
    }

    /// The wider set does not let one key's revoker strike another key out of
    /// the keyring. A key revocation signature R made over the key K, stapled
    /// onto an offered certificate of a third key that designates R too,
    /// leaves the keyring at the bytes it held.
    ///
    /// The designation is resolved and the revoker's certificate stands in the
    /// keyring, so the requirement the revocation verify over the key it
    /// stands on is the whole of what refuses it.
    #[test]
    fn a_revocation_over_another_key_strikes_out_no_held_key() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let state = Revoked::build();
        let packet = revocation_packet_of(&state.revoked);
        // The packet is the revocation R made: over a certificate of K it
        // stands on, with R's certificate in the trusted set, it revokes.
        let spliced = insert_after_primary(&state.designating, &packet);
        let revoker = state.certs(&state.revoker_cert);
        assert!(verify::key_revoked(&state.certs(&spliced)[0], &revoker));

        // A third key that designates R as a revoker too.
        let third = KeyFixture::new("Third <third@ostrya.example>");
        third.import(&state.revoker_cert);
        third.add_revoker(&state.revoker);
        let designating = third.export_one(&third.fingerprint());
        let stapled = insert_after_primary(&designating, &packet);
        // The stapled packet reaches the parsed certificate, so it is the merge
        // that refuses it and not the parse.
        assert_eq!(
            state.certs(&stapled)[0].details.revocation_signatures.len(),
            1
        );

        let held = third.imported_keyring("held", &[&designating, &state.revoker_cert]);
        let (imported, keyring) = merge_keyring(&held, &stapled, &[], SUBJECT).unwrap();
        assert_eq!(imported, 0);
        // No replacement is due, so the file keeps every byte it held, the
        // Trust packets the tool's own import wrote included.
        assert_eq!(keyring, held);
    }

    /// `certs` as the set a designated revoker is resolved among, which is what
    /// [`merge_keyring`] hands [`KeyState::over`] for the streams it was given.
    fn known(certs: &[SignedPublicKey]) -> Vec<&SignedPublicKey> {
        certs.iter().collect()
    }

    /// The key revocation signature packet the certificate stream `cert`
    /// carries, which `gpg --desig-revoke` writes right after the primary key
    /// packet.
    fn revocation_packet_of(cert: &[u8]) -> Vec<u8> {
        let (spans, _) = packet_spans(cert);
        let span = spans
            .iter()
            .find(|(tag, _)| *tag == Tag::Signature)
            .expect("a signature packet in the certificate")
            .1
            .clone();
        cert[span].to_vec()
    }

    /// A re-export stating a later key expiry replaces the certificate the
    /// keyring holds for that key, the import counts no key, and the key the
    /// keyring then holds verifies a signature it made.
    ///
    /// The keyring the merge is given is the one the `ostree` tool's own import
    /// leaves at the repository root, which carries the Trust packets. The
    /// merged keyring holds the offered certificate where the held one stood.
    #[test]
    fn an_expiry_extension_replaces_the_held_certificate() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::expiring("Renew <renew@ostrya.example>", "1d");
        let blob = home.sign(PAYLOAD);
        let expiring = home.export(false);
        let held = home.legacy_keyring();
        home.set_expire_at("20250102T000000!", "10y");
        let extended = home.export(false);
        // The fixture is the shape under test: the held keyring states an
        // expiry that has passed, so it refuses the signature, and the offered
        // re-export states one ten years out.
        assert_ne!(extended, expiring);
        assert!(
            !signature_is_valid(&held, &blob),
            "the held keyring must state an expiry that has passed"
        );

        let (imported, keyring) = merge_keyring(&held, &extended, &[], SUBJECT).unwrap();
        assert_eq!(imported, 0);
        assert_ne!(keyring, certificate_stream(&held));
        // One certificate run per key, holding the offered packets.
        assert_eq!(keyring, extended);
        // `gpg` reads the result, which is the reader the `ostree` tool drives
        // through gpgme, and the key it holds is live again.
        assert_eq!(home.fingerprints_of(&keyring), [home.fingerprint()]);
        assert!(
            signature_is_valid(&keyring, &blob),
            "the merged keyring must state the extended expiry"
        );

        // The keyring GnuPG writes for the same two imports states the same
        // expiry and carries one signature packet more: its merge keeps the
        // self-signature the earlier export carried, where the replacement
        // writes the offered packets alone. Both keyrings report the key live.
        let gnupg = home.imported_keyring("merged", &[&expiring, &extended]);
        let merged = certificate_stream(&gnupg);
        let signatures = |bytes: &[u8]| {
            packet_spans(bytes)
                .0
                .iter()
                .filter(|(tag, _)| *tag == Tag::Signature)
                .count()
        };
        assert_eq!(signatures(&keyring), 1, "the offered packets alone");
        assert_eq!(
            signatures(&merged),
            2,
            "GnuPG keeps the self-signature the earlier export carried"
        );
        assert!(signature_is_valid(&gnupg, &blob));
    }

    /// A keyring holding one key through two certificates states the expiry
    /// their newest self-signature states, which is the instant the verify path
    /// reads over the pair, so a re-export later than that instant replaces
    /// both runs.
    ///
    /// The two held certificates disagree in the direction that parts the newest
    /// statement from the widest one: the older one states ten years and the
    /// newer one an instant that has passed. The offered re-export states five
    /// years, which stands later than the newest held statement and earlier
    /// than the widest.
    #[test]
    fn two_held_certificates_state_their_newest_expiry() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::expiring("Pair <pair@ostrya.example>", "10y");
        let blob = home.sign(PAYLOAD);
        let widest = home.export(false);
        home.set_expire_at("20250102T000000!", "1d");
        let newest = home.export(false);
        home.set_expire_at("20250103T000000!", "5y");
        let offered = home.export(false);
        let mut held = widest.clone();
        held.extend_from_slice(&newest);
        // The fixture is the shape under test: the pair reads as expired, so
        // the widest statement does not answer for it.
        assert!(
            !signature_is_valid(&held, &blob),
            "the pair must read as expired"
        );
        assert!(
            signature_is_valid(&widest, &blob),
            "the older certificate must state a lifetime that has not passed"
        );

        let (imported, keyring) = merge_keyring(&held, &offered, &[], SUBJECT).unwrap();
        assert_eq!(imported, 0);
        // A keyring holding one key through two runs takes the replacement in
        // both.
        assert_eq!(keyring, [&offered[..], &offered[..]].concat());
        assert!(
            signature_is_valid(&keyring, &blob),
            "the merged keyring must state the offered expiry"
        );
    }

    /// An offered certificate stating an expiry no later than the held one's
    /// leaves the keyring at the bytes it held. Two directions state it: a
    /// shortened expiry over a longer held one, and an expiry over a held
    /// certificate that states none.
    #[test]
    fn an_earlier_expiry_leaves_the_held_certificate() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let long = KeyFixture::expiring("Long <long@ostrya.example>", "10y");
        let held = long.export(false);
        long.set_expire_at("20250102T000000!", "1d");
        let shortened = long.export(false);
        assert_ne!(shortened, held);
        let (imported, keyring) = merge_keyring(&held, &shortened, &[], SUBJECT).unwrap();
        assert_eq!(imported, 0);
        assert_eq!(keyring, held);

        let never = KeyFixture::expiring("Never <never@ostrya.example>", "never");
        let held = never.export(false);
        never.set_expire_at("20250102T000000!", "1d");
        let expiring = never.export(false);
        assert_ne!(expiring, held);
        let (imported, keyring) = merge_keyring(&held, &expiring, &[], SUBJECT).unwrap();
        assert_eq!(imported, 0);
        assert_eq!(keyring, held);
    }

    /// A held certificate that revokes its key takes no expiry replacement. A
    /// revocation is permanent, so the keyring keeps the bytes that carry it
    /// where the offered certificate carries none.
    #[test]
    fn a_revoked_key_takes_no_expiry_replacement() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::expiring("Struck <struck@ostrya.example>", "1d");
        // The held certificate revokes the key and states the shorter expiry.
        let held = insert_after_primary(&home.export(false), &home.revocation_packet());
        home.set_expire_at("20250102T000000!", "10y");
        let extended = home.export(false);
        // The fixture is the shape under test: the held certificate revokes the
        // key, the offered one does not, and the offered one states the later
        // expiry.
        let certs = GpgVerifier::from_keyring_bytes([&held]).unwrap().certs;
        assert_eq!(certs.len(), 1);
        let held_state = KeyState::over(&certs, &known(&certs));
        assert!(held_state.revoked);
        let offered = GpgVerifier::from_keyring_bytes([&extended]).unwrap().certs;
        let offered_state = KeyState::over(&offered, &known(&offered));
        assert!(!offered_state.revoked);
        assert!(states_later(offered_state.expires, held_state.expires));

        let (imported, keyring) = merge_keyring(&held, &extended, &[], SUBJECT).unwrap();
        assert_eq!(imported, 0);
        assert_eq!(keyring, held);
    }

    /// A keyring carrying bytes past its last framed packet takes no import.
    /// The merge reads the keyring the repository holds with the reader a
    /// verification load uses, so the refusal names the keyring and the merge
    /// writes none.
    ///
    /// The refusal stands whatever the offered stream holds: a revocation for
    /// the key the keyring holds, which a replacement would write where the
    /// held run stands, and a certificate for a key it does not hold, which an
    /// append would write after the bytes it holds.
    ///
    /// Measured over the same shape -- one exported ed25519 certificate with
    /// one `0xff` byte appended -- `gpgv` 2.4.9 reports
    /// `[don't know]: 1st length byte missing`,
    /// `keyring_get_keyblock: read error: Invalid packet`,
    /// `keydb_search failed: Invalid keyring`, `ERRSIG`, and `NO_PUBKEY` at
    /// exit 2 over a signature that key made, `gpg --list-keys` over the file
    /// lists no key, and `ostree show --gpg-verify-remote` reports
    /// `Can't check signature: public key not found`. No implementation trusts
    /// a key out of a file of that shape.
    #[test]
    fn an_unframeable_keyring_takes_no_import() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Tailed <tailed@ostrya.example>");
        let added = KeyFixture::new("Added <added@ostrya.example>");
        let unrevoked = home.export(false);
        home.revoke_primary();
        let revoked = home.export(false);
        let mut held = unrevoked.clone();
        held.push(0xff);
        // The fixture is the shape under test: the walk frames the export and
        // stops at the trailing byte, so the run split answers nothing.
        assert_eq!(packet_spans(&held).1, unrevoked.len());
        assert!(certificate_chunks(&held).is_none());

        for offered in [&revoked, &added.export(false)] {
            let refusal = merge_keyring(&held, offered, &[], SUBJECT).unwrap_err();
            let text = refusal.to_string();
            assert!(text.contains(SUBJECT), "{text}");
            assert!(text.contains("OpenPGP keyring"), "{text}");
        }
    }

    /// Each selector form takes the key it names out of the offered stream: a
    /// fingerprint plain, `0x`-prefixed, and spaced, a key id long and short, a
    /// subkey fingerprint, and a user id substring in another case.
    #[test]
    fn a_selector_takes_the_key_it_names() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Wanted <wanted@ostrya.example>");
        home.add_signing_subkey();
        home.add_key("Other <other@ostrya.example>");
        let primary = home.fingerprint();
        let wanted = home.export_one(&primary);
        let offered = home.export(false);
        assert!(offered.len() > wanted.len());
        let subkey = {
            let verifier = GpgVerifier::from_keyring_bytes([&wanted]).unwrap();
            format!("{:X}", verifier.certs[0].public_subkeys[0].fingerprint())
        };
        let spaced = primary
            .as_bytes()
            .chunks(4)
            .map(|chunk| String::from_utf8_lossy(chunk).into_owned())
            .collect::<Vec<_>>()
            .join(" ");

        for selector in [
            primary.clone(),
            format!("0x{primary}"),
            spaced,
            primary[24..].to_owned(),
            primary[32..].to_owned(),
            subkey,
            "wanted".to_owned(),
            "WANTED@ostrya".to_owned(),
            "Wanted <wanted@ostrya.example>".to_owned(),
        ] {
            let (imported, keyring) =
                merge_keyring(b"", &offered, std::slice::from_ref(&selector), SUBJECT).unwrap();
            assert_eq!(imported, 1, "the selector '{selector}' took no key");
            assert_eq!(
                keyring, wanted,
                "the selector '{selector}' took another key"
            );
        }

        // Two selectors take two keys, and one selector matching both user ids
        // takes both.
        let both = [primary.clone(), "other".to_owned()];
        assert_eq!(merge_keyring(b"", &offered, &both, SUBJECT).unwrap().0, 2);
        let shared = ["ostrya.example".to_owned()];
        assert_eq!(merge_keyring(b"", &offered, &shared, SUBJECT).unwrap().0, 2);
    }

    /// A selector naming no offered key is refused by name, and the keyring is
    /// then left as it was. A hex selector names a key alone: it is no user id
    /// substring, which is how `gpg --export` reads one.
    #[test]
    fn a_selector_naming_nothing_is_refused() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("DEADBEEF Person <hex@ostrya.example>");
        let offered = home.export(false);
        for selector in ["nomatch", "0000000000000000", "DEADBEEF", "", "  "] {
            let err = merge_keyring(b"", &offered, &[selector.to_owned()], SUBJECT).unwrap_err();
            assert!(
                matches!(&err, Error::Signature(m)
                    if m == &format!("no key matching '{selector}' among the keys to import")),
                "{err}"
            );
        }
        // The person's own name is a user id substring and takes the key.
        let taken = ["DEADBEEF Person".to_owned()];
        assert_eq!(merge_keyring(b"", &offered, &taken, SUBJECT).unwrap().0, 1);
    }

    /// A selector `gpg --export` reads as a user id substring is no key
    /// selector here either, so a shape the key reader does not carry names
    /// nothing rather than a key of its own choosing.
    ///
    /// Each row was measured against `gpg --export -- <selector>` on
    /// `gpg` 2.4.9, and none of them exports the key the hex names.
    #[test]
    fn a_selector_the_key_reader_does_not_carry_names_nothing() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        // The user id holds a `0x`-prefixed word, so a `0x` selector that is no
        // key would take this key if it were read as a user id substring.
        let home = KeyFixture::new("Narrow 0xnope <narrow@ostrya.example>");
        let offered = home.export(false);
        let primary = home.fingerprint();
        let group = |width: usize| -> String {
            primary
                .as_bytes()
                .chunks(width)
                .map(|chunk| String::from_utf8_lossy(chunk).into_owned())
                .collect::<Vec<_>>()
                .join(" ")
        };
        // Ten groups the same fingerprint splits into at uneven widths.
        let uneven = format!(
            "{} {} {}",
            &primary[..3],
            &primary[3..8],
            group(4)[10..].to_owned()
        );
        // The `0x` prefix is read in lower case alone and names a key or
        // nothing; a key id carries no interior space; the one spaced shape is a
        // printed v4 fingerprint, ten groups of four; a tab is no space; and
        // `0x` admits no space.
        let narrowed = [
            format!("0X{primary}"),
            format!("0X{}", &primary[32..]),
            format!("{} {}", &primary[24..32], &primary[32..]),
            format!("{} {}", &primary[32..36], &primary[36..]),
            group(2),
            uneven,
            primary.replace(&primary[20..21], &format!("\t{}", &primary[20..21])),
            format!("0x{}", group(4)),
            format!("0x{}", &primary[..7]),
            "0xnope".to_owned(),
        ];
        for selector in narrowed {
            let err =
                merge_keyring(b"", &offered, std::slice::from_ref(&selector), SUBJECT).unwrap_err();
            assert!(
                matches!(&err, Error::Signature(m)
                    if m == &format!("no key matching '{selector}' among the keys to import")),
                "the selector '{selector}' took a key: {err}"
            );
            // The reference: the selector exports nothing through `gpg`.
            let out = home
                .gpg()
                .arg("--export")
                .arg("--")
                .arg(&selector)
                .output()
                .unwrap();
            assert!(
                out.stdout.is_empty(),
                "gpg --export took a key for '{selector}'"
            );
        }
        // The forms the reader does carry still take the key: a printed
        // fingerprint in its ten groups of four, and either hex case, with
        // leading and trailing spaces dropped.
        for selector in [group(4), format!(" {} ", primary.to_lowercase())] {
            assert_eq!(
                merge_keyring(b"", &offered, std::slice::from_ref(&selector), SUBJECT)
                    .unwrap()
                    .0,
                1,
                "the selector '{selector}' took no key"
            );
        }
    }

    /// The user id search folds ASCII case alone, which is what `gpg` folds:
    /// over the user id `Ärger`, `ÄRGER` takes the key and `ärger` takes none.
    #[test]
    fn a_user_id_selector_folds_ascii_case_alone() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Umlaut Ärger <umlaut@ostrya.example>");
        let offered = home.export(false);
        for selector in ["Ärger", "ÄRGER", "ärgER"] {
            let taken = merge_keyring(b"", &offered, &[selector.to_owned()], SUBJECT)
                .map(|(count, _)| count);
            let exported = !home
                .gpg()
                .arg("--export")
                .arg("--")
                .arg(selector)
                .output()
                .unwrap()
                .stdout
                .is_empty();
            assert_eq!(
                taken.is_ok(),
                exported,
                "the selector '{selector}' parts from gpg --export"
            );
        }
    }

    /// A stream carrying no certificate, one the packet walk cannot frame to
    /// its end, and a keybox are each refused, and the keyring is then left as
    /// it was. The `ostree` tool refuses all three as well.
    #[test]
    fn an_unreadable_offered_stream_is_refused() {
        let empty = merge_keyring(b"", b"", &[], SUBJECT).unwrap_err();
        assert!(
            matches!(&empty, Error::Signature(m) if m.contains("no OpenPGP certificate")),
            "{empty}"
        );
        let oversized = vec![0u8; MAX_KEYRING as usize + 1];
        let err = merge_keyring(b"", &oversized, &[], SUBJECT).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("ceiling")),
            "{err}"
        );
        if !gpg_available() {
            eprintln!("skipping the keyring half: gpg not available");
            return;
        }
        let home = KeyFixture::new("Cut <cut@ostrya.example>");
        let offered = home.export(false);
        let cut = &offered[..offered.len() - 1];
        let err = merge_keyring(b"", cut, &[], SUBJECT).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("OpenPGP keyring")),
            "{err}"
        );
        let err = merge_keyring(b"", &home.keybox(), &[], SUBJECT).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("keybox")),
            "{err}"
        );
        // A keyring holds transferable public keys, so a secret-key export
        // holds none. The `ostree` tool takes the public part of such a stream;
        // `cli-surface.md`, "P3", records the divergence.
        let err = merge_keyring(b"", &home.export_secret(), &[], SUBJECT).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("no OpenPGP certificate")),
            "{err}"
        );
        // The certificate cap holds over an offered stream as well: 257 are
        // refused by name and 256 are taken.
        let many = offered.repeat(MAX_KEYRING_CERTS + 1);
        assert!(many.len() as u64 <= MAX_KEYRING);
        let err = merge_keyring(b"", &many, &[], SUBJECT).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("the keyring to import")
                && m.contains("256 certificates")),
            "{err}"
        );
        let allowed = offered.repeat(MAX_KEYRING_CERTS);
        assert_eq!(merge_keyring(b"", &allowed, &[], SUBJECT).unwrap().0, 1);
    }

    /// The listing reports what `gpg` reports over the same keyring: the
    /// fingerprint, the creation instant, and the user ids in listing order.
    /// A keyring holding no key lists none.
    #[test]
    fn the_listing_agrees_with_gpg() {
        if !gpg_available() {
            eprintln!("skipping: gpg not available");
            return;
        }
        let home = KeyFixture::new("Listed <listed@ostrya.example>");
        home.add_uid("Second <second@ostrya.example>");
        home.add_signing_subkey();
        home.add_key("Another <another@ostrya.example>");

        // The reference: the `pub`, `fpr`, and `uid` records of gpg's own
        // machine-readable listing, one record set per primary key.
        let listing = home.listing();
        let mut reference: Vec<GpgKey> = Vec::new();
        let mut in_subkey = false;
        for line in listing.lines() {
            let fields: Vec<&str> = line.split(':').collect();
            match fields[0] {
                "pub" => {
                    in_subkey = false;
                    reference.push(GpgKey {
                        fingerprint: String::new(),
                        created: parse_epoch(fields[5]),
                        user_ids: Vec::new(),
                    });
                }
                "sub" => in_subkey = true,
                "fpr" if !in_subkey => {
                    let key = reference.last_mut().unwrap();
                    if key.fingerprint.is_empty() {
                        key.fingerprint = fields[9].to_owned();
                    }
                }
                "uid" => reference
                    .last_mut()
                    .unwrap()
                    .user_ids
                    .push(fields[9].to_owned()),
                _ => {}
            }
        }
        assert_eq!(reference.len(), 2);
        assert_eq!(reference[0].user_ids.len(), 2);

        for keyring in [home.export(false), home.legacy_keyring()] {
            assert_eq!(keyring_keys(&keyring, SUBJECT).unwrap(), reference);
        }
        assert!(keyring_keys(b"", SUBJECT).unwrap().is_empty());
    }
}