packslip 1.11.2

A vendor-neutral signed release manifest: what shipped, and how to verify it
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
//! The `packslip` binary: create, releases, verify, pin, show, keygen,
//! schema, completion, and version.

use std::path::{Path, PathBuf};

use eyre::{Context as _, Result, bail};
use packslip::cli::{BinInfo, Version};
#[cfg(all(feature = "create", feature = "manifest"))]
use packslip::create::{ArtifactInput, AssetInput, ListRequest, ListedRelease, Request};
use packslip::fingerprint::Fingerprint;
#[cfg(all(feature = "create", feature = "manifest"))]
use packslip::manifest::Manifest;
use packslip::minisign::PublicKey;
#[cfg(feature = "sign")]
use packslip::minisign::{SecretKey, key_id_hex};
use packslip::model::{Attestor, RELEASES_PREDICATE_TYPE};
#[cfg(all(feature = "create", feature = "manifest"))]
use packslip::model::{Bin, Evidence, Extensions, RequiredBin, Resource, Source};
#[cfg(feature = "schema")]
use packslip::model::{ReleaseListStatement, Statement};
#[cfg(all(feature = "create", feature = "manifest"))]
use packslip::sigstore::Signer;
use packslip::sigstore::{self, Policy, Trust};
use packslip::verify::Options;
use usage_rs::RunWith;

const BIN: BinInfo = BinInfo {
    name: "packslip",
    version: env!("CARGO_PKG_VERSION"),
};

/// The file a release ships: `packslip.sigstore.json`, or, for a tool in
/// a monorepo named `github.com/owner/repo/sub/path`,
/// `packslip.sub-path.sigstore.json`, so several tools can share one
/// release. Consumers match on the statement's `project`, not the name.
#[cfg(all(feature = "create", feature = "manifest"))]
pub fn bundle_name(project: &str) -> String {
    match packslip::model::repository_subpath(project) {
        Some(sub) => format!("packslip.{}.sigstore.json", sub.replace('/', "-")),
        None => "packslip.sigstore.json".to_string(),
    }
}

/// A signed release manifest: what shipped, and how to verify it
///
/// A release job runs `packslip create` to sign a release bundle,
/// packslip.sigstore.json, whose statement lists every artifact with its
/// digest. Consumers check the bundle and the files they download with
/// `packslip verify`, or install a tool from it with `packslip install`
/// instead of running an installer script. Guides and the specification:
/// https://packslip.dev
#[derive(usage_rs::Cli)]
#[usage(completion = true)]
#[usage(
    name = "packslip",
    bin = "packslip",
    version,
    author = "Jeff Dickey <@jdx>, Shunsuke Suzuki <@suzuki-shunsuke>",
    arg_required_else_help
)]
struct Cli {
    #[usage(subcommand)]
    command: Option<Commands>,
}

#[derive(usage_rs::Subcommands)]
#[usage(run_with)]
enum Commands {
    Completion(Completion),
    #[cfg(all(feature = "create", feature = "manifest"))]
    Create(Box<Create>),
    #[cfg(feature = "install-cli")]
    Install(Box<Install>),
    #[cfg(feature = "sign")]
    Keygen(Keygen),
    Pin(Box<Pin>),
    #[cfg(all(feature = "create", feature = "manifest"))]
    Releases(Box<Releases>),
    #[cfg(feature = "schema")]
    Schema(Schema),
    Show(Show),
    #[usage(hide)]
    Usage(Usage),
    Verify(Verify),
    Version(Version),
}

/// Install a verified release and export its declared commands
///
/// Find the release a project's name leads to, and verify its release bundle
/// and the artifact for this host. Unpack the archive into an installation
/// tree and export the commands the release declares.
///
/// A github.com project must be signed from its repository. A keyless domain
/// project's first install trusts the signer that its release list and
/// release bundle declare, fetched over HTTPS from that host. A key-signed
/// domain project needs --pubkey on its first install. Later installs hold
/// the project to what was accepted, and a keyless domain project to the
/// repository that signed it. A changed signer or signing repository,
/// keyless signing replaced by a key, disabled workflow pinning, a
/// repackager's bundle after the vendor's, or dropped provenance needs
/// --accept-trust-change, and a github.com name that now resolves to a
/// different repository ID is refused.
/// --pin, --issuer, --identity, and --identity-prefix narrow what the
/// project's name requires and never replace it. gitlab.com projects are
/// refused.
///
/// The command runs no downloaded code, installs no dependencies, and edits
/// no shell configuration. There is no uninstall, upgrade, or list. It prints
/// the installed version and tree, `Signer fingerprint: ps1_...` for a
/// github.com project, and each command. It warns when the project's release
/// list withdraws the release it last installed. See
/// https://packslip.dev/docs/bootstrap/
#[cfg(feature = "install-cli")]
#[derive(Debug, usage_rs::Args)]
#[usage(
    example(
        "packslip install github.com/jdx/hk",
        header = "Install the latest release of hk"
    ),
    example(
        "packslip install github.com/jdx/hk \\\n        --version 2.8.0 \\\n        --pin ps1_snirenkjwr7m5ozgcufameodnm",
        header = "Install hk 2.8.0 and require its signer fingerprint"
    ),
    example(
        "packslip install mytool.example.com --pubkey release.pub",
        header = "Install a key-signed domain project"
    )
)]
struct Install {
    /// The project: owner/repo, github.com/owner/repo[/TOOL], or a domain
    /// project such as mytool.example.com[/PATH]
    #[usage(arg)]
    project: String,
    /// Version, prefix, range, tag, or latest (the default)
    ///
    /// latest takes the vendor's recommended release, otherwise the highest
    /// stable version. When that release carries no packslip for the project
    /// or no artifact for this host, install tries the other stable releases
    /// from the highest down. It warns about each release it skips. It examines
    /// the first release in full, and stops before a later release would bring
    /// the bundles it fetched past 32. A version (1.2.3 also matches
    /// 1.2.3+build.5), prefix (1.2), or range (^1.2) skips only releases
    /// without a packslip for the project; a tag tries only that release. Host
    /// requirements never select a different release.
    #[usage(long)]
    version: Option<String>,
    /// Install for all users
    ///
    /// The default for root on Unix. Conflicts with --user.
    #[usage(long)]
    system: bool,
    /// Install for the current user
    ///
    /// The default, except for root on Unix, which cannot select it. Conflicts
    /// with --system.
    #[usage(long)]
    user: bool,
    /// Replace conflicting command entries and installation directories
    ///
    /// An installation directory conflicts when it is unmarked or belongs to
    /// another project. Verification and trust-change approval still apply.
    #[usage(long)]
    force: bool,
    /// Use only locally cached, authenticated metadata and artifacts
    ///
    /// Makes no network requests, and fails when something is not cached.
    #[usage(long)]
    offline: bool,
    /// Install into this absolute directory instead of the scope's tree
    ///
    /// Trust state stays in the scope.
    #[usage(long, value_hint = usage_rs::ValueHint::DirPath)]
    install_dir: Option<PathBuf>,
    /// Export commands into this absolute directory instead of the scope's
    ///
    /// Trust state stays in the scope.
    #[usage(long, value_hint = usage_rs::ValueHint::DirPath)]
    bin_dir: Option<PathBuf>,
    /// Select the artifact the publisher marks with this variant name
    #[usage(long)]
    variant: Option<String>,
    /// Require this signer fingerprint (ps1_...), as `packslip pin` prints it
    /// (repeatable)
    ///
    /// A signer with any of the given fingerprints is accepted.
    #[usage(long)]
    pin: Vec<String>,
    /// Require this public key: a minisign .pub file, such as one from
    /// `packslip keygen`, or its base64 line
    ///
    /// A key-signed domain project's first install needs it, and later
    /// installs remember it. A github.com project refuses it, since it must
    /// be signed keyless.
    #[usage(long)]
    pubkey: Option<String>,
    /// Require this OIDC issuer
    ///
    /// It narrows what the project's name requires and never replaces it.
    #[usage(long)]
    issuer: Option<String>,
    /// Require this exact certificate identity, ref included, such as
    /// https://github.com/owner/repo/.github/workflows/release.yml@refs/tags/v1.2.3
    ///
    /// It narrows what the project's name requires and never replaces it. A
    /// GitHub or GitLab repository name in it matches in any case; the rest
    /// matches exactly.
    #[usage(long)]
    identity: Option<String>,
    /// Require a certificate identity that starts with this prefix, such as
    /// https://github.com/owner/repo/
    ///
    /// It narrows what the project's name requires and never replaces it. A
    /// GitHub or GitLab repository name in it matches in any case; the rest
    /// matches exactly.
    #[usage(long)]
    identity_prefix: Option<String>,
    /// Approve one trust change by the ID install printed for it (repeatable)
    ///
    /// The ID covers that exact release bundle or release list, the signer
    /// accepted before, and the trust requirements in effect, so it approves
    /// nothing else.
    #[usage(long)]
    accept_trust_change: Vec<String>,
    /// Use this Sigstore trusted_root.json instead of refreshing the trust root
    /// through TUF
    #[usage(long, value_hint = usage_rs::ValueHint::FilePath)]
    trusted_root: Option<PathBuf>,
    /// Accept a bundle without a transparency log entry, such as one created
    /// with --key --no-log
    ///
    /// Applies to this install only.
    #[usage(long)]
    allow_unlogged: bool,
    /// Install even when this host does not meet the selected artifact's host
    /// requirements
    #[usage(long)]
    allow_incompatible_host: bool,
    /// The most bytes an archive may expand to
    #[usage(long, default = "10737418240")]
    max_extracted_size: u64,
    /// The most entries an archive may hold
    #[usage(long, default = "100000")]
    max_archive_entries: u64,
}

#[cfg(feature = "install-cli")]
impl RunWith<BinInfo> for Install {
    type Output = Result<()>;
    fn run_with(self, _: BinInfo) -> Result<()> {
        let request = packslip::install::Request {
            project: self.project,
            version: self.version,
            system: self.system,
            user: self.user,
            force: self.force,
            offline: self.offline,
            install_dir: self.install_dir,
            bin_dir: self.bin_dir,
            variant: self.variant,
            constraints: packslip::install_policy::Constraints {
                pins: self.pin,
                pubkey: self.pubkey,
                issuer: self.issuer,
                identity: self.identity,
                identity_prefix: self.identity_prefix,
            },
            accept_trust_change: self.accept_trust_change,
            trusted_root: self.trusted_root,
            allow_unlogged: self.allow_unlogged,
            allow_incompatible_host: self.allow_incompatible_host,
            limits: packslip::install_extract::Limits {
                bytes: self.max_extracted_size,
                entries: self.max_archive_entries,
            },
        };
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;
        let report = runtime.block_on(packslip::install::run(request))?;
        print_install_report(
            report,
            &mut std::io::stdout().lock(),
            &mut std::io::stderr().lock(),
        )?;
        Ok(())
    }
}

/// Print what `install` did: the release and its tree, the signer
/// fingerprint of a keyless forge release, and each exported command, with
/// any warnings on stderr.
#[cfg(feature = "install-cli")]
fn print_install_report(
    report: packslip::install::Report,
    out: &mut impl std::io::Write,
    err: &mut impl std::io::Write,
) -> std::io::Result<()> {
    writeln!(
        out,
        "Installed {} {} at {}",
        report.project,
        report.receipt.version,
        report.receipt.tree.display()
    )?;
    if let Some(fingerprint) = report.pin {
        writeln!(out, "Signer fingerprint: {fingerprint}")?;
    }
    for warning in report.warnings {
        writeln!(err, "warning: {warning}")?;
    }
    for path in report.receipt.exports.keys() {
        writeln!(out, "Command: {}", path.display())?;
    }
    Ok(())
}

/// Generate a self-contained shell completion script
///
/// Print the script to stdout, and redirect it to a file your shell loads, as
/// the example does for bash. The script asks the installed packslip for
/// candidates, so it needs no other tool and keeps working after upgrades.
/// The setup for each shell is at
/// https://packslip.dev/cli/#set-up-shell-completions
#[derive(Debug, usage_rs::Args)]
#[usage(example(
    "mkdir -p ~/.local/share/bash-completion/completions && packslip completion bash > ~/.local/share/bash-completion/completions/packslip",
    header = "Install bash completions for your user"
))]
struct Completion {
    /// The shell to generate the script for
    #[usage(
        arg,
        choices("bash", "elvish", "zsh", "fish", "nu", "nushell", "powershell", "pwsh")
    )]
    shell: String,
}

impl RunWith<BinInfo> for Completion {
    type Output = Result<()>;

    fn run_with(self, _: BinInfo) -> Self::Output {
        let shell = usage_rs::complete::Shell::from_name(&self.shell)
            .ok_or_else(|| eyre::eyre!("unsupported shell: {}", self.shell))?;
        print!("{}", Cli::completion_script(shell));
        Ok(())
    }
}

/// Generate a usage spec for the CLI
///
/// https://usage.jdx.dev
#[derive(Debug, usage_rs::Args)]
struct Usage;

impl RunWith<BinInfo> for Usage {
    type Output = Result<()>;

    fn run_with(self, _: BinInfo) -> Self::Output {
        println!(
            "// @generated by `packslip usage`\n{}",
            Cli::to_kdl().trim_end()
        );
        Ok(())
    }
}

/// Generate an Ed25519 key pair for key-signed releases
///
/// Write a new secret key to --out, as a hex Ed25519 seed with mode 0600 on
/// Unix, and its public key, in minisign format, to the same path with the
/// extension replaced by .pub: --out release.key writes release.key and
/// release.pub. If either file exists, keygen writes nothing and fails.
///
/// Sign with `packslip create --key release.key`, which uses the sigstore-key
/// scheme. Give consumers release.pub for `packslip verify --pubkey` and
/// `packslip install --pubkey`.
/// Keep the secret key private. A CI job with an OIDC identity can sign
/// keyless and needs no key. See https://packslip.dev/docs/other-ci/
#[derive(Debug, usage_rs::Args)]
#[usage(example(
    "packslip keygen --out release.key",
    header = "Write release.key and release.pub"
))]
#[cfg(feature = "sign")]
struct Keygen {
    /// Where to write the secret key; the public key goes beside it, with a
    /// .pub extension
    ///
    /// It must not end in .pub, since the public key takes that name.
    #[usage(short = 'o', long, default = "packslip.key")]
    out: PathBuf,
}

#[cfg(feature = "sign")]
impl RunWith<BinInfo> for Keygen {
    type Output = Result<()>;

    fn run_with(self, _: BinInfo) -> Self::Output {
        use std::io::Write as _;
        let pubkey = self.out.with_extension("pub");
        if self.out == pubkey {
            bail!(
                "secret and public key paths both resolve to {}",
                self.out.display()
            );
        }
        if self.out.exists() || pubkey.exists() {
            bail!(
                "{} or {} exists; not overwriting a key",
                self.out.display(),
                pubkey.display()
            );
        }
        let key = SecretKey::generate();
        let mut options = std::fs::OpenOptions::new();
        options.write(true).create_new(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt as _;
            options.mode(0o600);
        }
        let mut file = options
            .open(&self.out)
            .wrap_err_with(|| format!("creating {}", self.out.display()))?;
        file.write_all(key.to_file().as_bytes())?;
        let public_result = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&pubkey)
            .and_then(|mut public| public.write_all(key.public_key().to_file().as_bytes()));
        if let Err(err) = public_result {
            let _ = std::fs::remove_file(&self.out);
            return Err(err).wrap_err_with(|| format!("writing {}", pubkey.display()));
        }
        println!(
            "wrote {} and {} (key id {})",
            self.out.display(),
            pubkey.display(),
            key_id_hex(&key.public_key().key_id)
        );
        Ok(())
    }
}

/// Print the JSON schema for a decoded release statement
///
/// --releases prints the release list's statement schema instead, and
/// --report the schema of the report `verify --json` prints for a release.
/// The statement schemas describe the in-toto payload, not the Sigstore
/// bundle around it.
///
/// The three schemas, in that order, are published at
/// https://packslip.dev/schema/release-v1.json,
/// https://packslip.dev/schema/releases-v1.json, and
/// https://packslip.dev/schema/verify-report-v1.json.
///
/// See https://packslip.dev/release/v1/#json-schemas
#[derive(Debug, usage_rs::Args)]
#[cfg(feature = "schema")]
struct Schema {
    /// Print the releases/v1 release list schema instead of the release/v1
    /// statement schema
    #[usage(long)]
    releases: bool,
    /// Print the schema of the report `verify --json` prints for a release;
    /// wins over --releases
    #[usage(long)]
    report: bool,
}

#[cfg(feature = "schema")]
impl RunWith<BinInfo> for Schema {
    type Output = Result<()>;

    fn run_with(self, _: BinInfo) -> Self::Output {
        let schema = if self.report {
            packslip::verify_report_schema()
        } else if self.releases {
            ReleaseListStatement::schema()
        } else {
            Statement::schema()
        };
        println!("{}", serde_json::to_string_pretty(&schema)?);
        Ok(())
    }
}

/// Print the statement inside a bundle, without verifying it
///
/// Read a release bundle or release list and print its statement as indented
/// JSON. Nothing is checked: the signer, the signature, and every field are
/// unverified until `packslip verify` accepts the bundle.
///
/// A release bundle's fields are defined at
/// https://packslip.dev/release/v1/#the-release-statement and a release
/// list's at https://packslip.dev/release/v1/#the-release-list
#[derive(Debug, usage_rs::Args)]
#[usage(example(
    "packslip show packslip.sigstore.json",
    header = "Read the statement of a release bundle"
))]
struct Show {
    /// Release bundle or release list to read
    #[usage(value_hint = usage_rs::ValueHint::FilePath)]
    bundle: PathBuf,
    /// Print the exact signed payload followed by a newline, without
    /// pretty-printing
    #[usage(long)]
    raw: bool,
}

impl RunWith<BinInfo> for Show {
    type Output = Result<()>;

    fn run_with(self, _: BinInfo) -> Self::Output {
        let text = std::fs::read_to_string(&self.bundle)
            .wrap_err_with(|| format!("reading {}", self.bundle.display()))?;
        let payload = sigstore::peek_statement(&text)?;
        if self.raw {
            use std::io::Write as _;
            std::io::stdout().write_all(&payload)?;
            println!();
        } else {
            let value: serde_json::Value = serde_json::from_slice(&payload)?;
            println!("{}", serde_json::to_string_pretty(&value)?);
        }
        Ok(())
    }
}

/// How to sign: `oidc` (keyless, with the CI job's identity) or `key` (an
/// Ed25519 key given with --key).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg(all(feature = "create", feature = "manifest"))]
enum SignWith {
    Oidc,
    Key,
}

#[cfg(all(feature = "create", feature = "manifest"))]
impl std::str::FromStr for SignWith {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "oidc" | "sigstore-oidc" => Ok(SignWith::Oidc),
            "key" | "sigstore-key" => Ok(SignWith::Key),
            other => Err(format!("--sign must be oidc or key, got {other:?}")),
        }
    }
}

/// `vendor` or `repackager`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg(all(feature = "create", feature = "manifest"))]
struct AttestorArg(Attestor);

#[cfg(all(feature = "create", feature = "manifest"))]
impl std::str::FromStr for AttestorArg {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "vendor" => Ok(AttestorArg(Attestor::Vendor)),
            "repackager" => Ok(AttestorArg(Attestor::Repackager)),
            other => Err(format!(
                "--attested-by must be vendor or repackager, got {other:?}"
            )),
        }
    }
}

/// Resolve who signs from the shared signing flags.
#[cfg(all(feature = "create", feature = "manifest"))]
fn signer(key: &Option<PathBuf>, sign: Option<SignWith>, no_log: bool) -> Result<Signer> {
    let sign_with = sign.unwrap_or(if key.is_some() {
        SignWith::Key
    } else {
        SignWith::Oidc
    });
    match sign_with {
        SignWith::Key => {
            let Some(path) = key else {
                bail!("--sign key needs --key");
            };
            let key_text = std::fs::read_to_string(path)
                .wrap_err_with(|| format!("reading {}", path.display()))?;
            Ok(Signer::Key {
                key: SecretKey::parse(&key_text)?,
                log: !no_log,
            })
        }
        SignWith::Oidc => {
            if key.is_some() {
                bail!("--key is for --sign key");
            }
            if no_log {
                bail!("keyless signatures are always logged; --no-log is for --key");
            }
            Ok(Signer::Oidc(sigstore::ambient_identity()?))
        }
    }
}

/// Create and sign the release bundle for a release
///
/// Hash local artifacts, infer each one's platform and format from its file
/// name, and write the signed bundle into the --out directory. No files are
/// uploaded. A release.toml passed with --manifest describes per-artifact
/// executables, formats, requirements, and resources. Scalar flags, such as
/// --project, --version, --url-base, and --source-repo, override its
/// release-level values. --bin, --resource, --require, and --provenance add
/// to its values. A file given as an argument that release.toml also lists
/// keeps its release.toml entry.
///
/// Signing is keyless by default, with the OIDC token in SIGSTORE_ID_TOKEN
/// or else the CI job's own identity, which on GitHub Actions needs the
/// `id-token: write` permission. --key signs with a key from `packslip
/// keygen` instead. Every signature is recorded in the Rekor transparency
/// log unless --no-log is passed with --key.
///
/// See https://packslip.dev/docs/describing-releases/ for release.toml and
/// more examples.
#[derive(Debug, usage_rs::Args)]
#[usage(
    example(
        "packslip create \\\n        --project github.com/owner/mytool \\\n        --version 1.2.3 \\\n        --bin mytool \\\n        --url-base https://github.com/owner/mytool/releases/download/v1.2.3 \\\n        --out dist \\\n        dist/mytool-1.2.3-linux-x64.tar.gz \\\n        dist/mytool-1.2.3-darwin-arm64.tar.gz",
        header = "Sign keyless in a CI job"
    ),
    example(
        "packslip create --manifest release.toml --out dist",
        header = "Describe the artifacts in release.toml"
    ),
    example(
        "packslip create \\\n        --project mytool.example.com \\\n        --version 1.2.3 \\\n        --bin mytool \\\n        --url-base https://mytool.example.com/v1.2.3 \\\n        --key release.key \\\n        --out dist \\\n        dist/mytool-1.2.3-linux-x64.tar.gz",
        header = "Sign with a key from packslip keygen"
    )
)]
#[cfg(all(feature = "create", feature = "manifest"))]
struct Create {
    /// The project's name, such as github.com/owner/repo; required unless
    /// release.toml sets it
    ///
    /// Give github.com/owner/repo, github.com/owner/repo/TOOL for one tool of
    /// a monorepo, gitlab.com/GROUP/PROJECT, or a domain project, one named
    /// after a host, such as mytool.example.com[/PATH]. Consumers can verify a
    /// gitlab.com project's releases, but `packslip install` refuses it.
    #[usage(long, help_heading = "Input")]
    project: Option<String>,
    /// The release's semver version, such as 1.2.3; required unless
    /// release.toml sets it
    #[usage(long, help_heading = "Input")]
    version: Option<String>,
    /// Files to describe, each as PATH, PATH:OS/ARCH[/LIBC], or PATH:any,
    /// with an optional @VARIANT
    ///
    /// Without a platform suffix, create infers the platform from the file
    /// name. Give any as ARCH or LIBC to leave that field out, for a build
    /// that runs on every architecture or C library; PATH:any leaves out OS,
    /// ARCH, and LIBC. These files join release.toml's artifacts; a file it
    /// lists under the same file name keeps its release.toml entry, and the
    /// platform suffix and @VARIANT given here are ignored.
    artifacts: Vec<String>,
    /// A release.toml describing the artifacts and the release's resources
    ///
    /// It gives per-artifact executables, formats, requirements, and
    /// platforms. Its artifact and asset paths are relative to the working
    /// directory, not to the file. See
    /// https://packslip.dev/docs/describing-releases/#use-a-toml-manifest
    /// and, for every key, https://packslip.dev/docs/release-toml/
    #[usage(short = 'm', long, value_hint = usage_rs::ValueHint::FilePath, help_heading = "Input")]
    manifest: Option<PathBuf>,
    /// Sign with this secret key, from `packslip keygen`, instead of signing
    /// keyless
    #[usage(short = 'k', long, value_hint = usage_rs::ValueHint::FilePath, help_heading = "Signing")]
    key: Option<PathBuf>,
    /// How to sign: oidc (keyless, with the CI job's identity) or key (with
    /// --key)
    ///
    /// Defaults to key when --key is given, else oidc. sigstore-oidc and
    /// sigstore-key are other spellings. --sign key needs --key; --sign oidc
    /// conflicts with --key.
    #[usage(long, help_heading = "Signing")]
    sign: Option<SignWith>,
    /// Record no Rekor transparency log entry for a key signature
    ///
    /// Needs --key, since keyless signatures are always logged. Consumers
    /// must then pass --allow-unlogged.
    #[usage(long, help_heading = "Signing")]
    no_log: bool,
    /// Directory to write the bundle into, created if missing
    ///
    /// The bundle is packslip.sigstore.json, or packslip.TOOL.sigstore.json
    /// for a tool in a GitHub monorepo, such as github.com/owner/repo/TOOL (a
    /// deeper path has each / replaced by -). An existing bundle is
    /// replaced. Artifacts are not copied.
    #[usage(short = 'o', long, default = ".", help_heading = "Output")]
    out: PathBuf,
    /// Download URL prefix: each artifact and resource asset gets
    /// PREFIX/FILENAME unless --url or release.toml gives its URL
    #[usage(long, help_heading = "Download URLs")]
    url_base: Option<String>,
    /// Download URL of one artifact or resource asset, as FILENAME=URL
    /// (repeatable)
    ///
    /// A URL release.toml gives for an artifact wins.
    #[usage(long, help_heading = "Download URLs")]
    url: Vec<String>,
    /// Format of an artifact whose file name does not say, as FILENAME=FORMAT
    /// (repeatable)
    ///
    /// FORMAT is an archive (tar.xz, tar.gz, tar.zst, tar.bz2, tgz, tar, zip,
    /// 7z), a single compressed executable (gz, xz, zst, bz2), an installer
    /// (deb, rpm, dmg, pkg, msi, msix, exe, appimage), raw for a bare
    /// executable, or a type of your own. A format release.toml gives for an
    /// artifact wins.
    #[usage(long, help_heading = "Artifacts")]
    format: Vec<String>,
    /// Source repository URL, such as https://github.com/owner/repo
    #[usage(long, help_heading = "Source")]
    source_repo: Option<String>,
    /// Commit the release was built from; needs --source-repo or
    /// release.toml's source.repo
    ///
    /// A resource with a repo: source requires it, and consumers read that
    /// file at this commit.
    #[usage(long, help_heading = "Source")]
    commit: Option<String>,
    /// Git tag of the release, such as v1.2.3; needs --source-repo or
    /// release.toml's source.repo
    ///
    /// Consumers that list a GitHub project's versions from its tags do not
    /// see the release when the tag does not name the release's version,
    /// unless a signed release list names the release. create warns when that
    /// happens.
    #[usage(long, help_heading = "Source")]
    tag: Option<String>,
    /// RFC 3339 publish time; defaults to now
    ///
    /// The statement records it in UTC: 2026-09-01T14:00:00+02:00 is written
    /// as 2026-09-01T12:00:00Z.
    #[usage(long, help_heading = "Release metadata")]
    published_at: Option<String>,
    /// URL of the release notes
    #[usage(long, help_heading = "Release metadata")]
    notes_url: Option<String>,
    /// Release-level extension as NAME=JSON (repeatable)
    ///
    /// NAME is who defines it, a consumer such as mise or a domain the vendor
    /// controls, and JSON is its value, such as
    /// 'example.com={"build_id":"20260901.3"}'. A flag replaces release.toml's
    /// extension of the same NAME.
    #[usage(long, help_heading = "Release metadata")]
    extension: Vec<String>,
    /// Executable the artifacts hold, as NAME, PATH, or NAME=PATH (repeatable)
    ///
    /// A NAME is found inside each archive. A PATH starts at the archive root
    /// and includes any top-level directory. NAME=PATH names the command when
    /// it differs from the file's name. For a bare executable, give the
    /// command name it installs as. These join release.toml's top-level bin;
    /// an artifact that release.toml gives its own bin list keeps only that
    /// list.
    #[usage(long, help_heading = "Artifacts")]
    bin: Vec<String>,
    /// Another file the release ships, such as a completion script, man
    /// page, or SBOM, as KIND[/QUALIFIER][@OS[/ARCH[/LIBC]]]=SOURCE:VALUE
    /// (repeatable)
    ///
    /// SOURCE is archive (a path inside the artifact, from its root), asset
    /// (a separate release file, by local path), repo (a path in the source
    /// repository at --commit), or exec (a command whose stdout is the file;
    /// leading NAME=value words set its environment).
    ///
    /// Known kinds: completion/SHELL[/BIN] (completion/SHELL,SHELL[/BIN]
    /// with exec and a {shell} placeholder), man[/BIN],
    /// cli-spec/FORMAT[/BIN], skill/NAME, sbom/FORMAT, desktop, icon, app.
    /// Any other kind takes at most one qualifier, its name.
    ///
    /// An @ scope limits the entry to the artifacts of that platform, for a
    /// layout that differs across them; release.toml can also limit an
    /// entry to one artifact. Examples:
    /// 'completion/zsh=archive:share/zsh/site-functions/_tool',
    /// 'man@linux=archive:share/man/man1/tool.1'. See
    /// https://packslip.dev/docs/resources/#write-a-resource-entry
    #[usage(long, help_heading = "Resources")]
    resource: Vec<String>,
    /// Provenance URL for an artifact, as FILENAME=URL, or bare URLs in
    /// the order of the ARTIFACTS arguments (repeatable)
    #[usage(long, help_heading = "Artifacts")]
    provenance: Vec<String>,
    /// Who makes the claim: vendor (the default) or repackager
    #[usage(long, help_heading = "Repackagers")]
    attested_by: Option<AttestorArg>,
    /// What a repackager checked, as KIND or KIND=DETAIL (repeatable); needs
    /// --attested-by repackager
    #[usage(long, help_heading = "Repackagers")]
    evidence: Vec<String>,
    /// Record only sha256 digests; by default create records sha256 and
    /// sha512
    #[usage(long, help_heading = "Artifacts")]
    no_sha512: bool,
    /// A command the executables need on PATH, as bin:NAME or bin:NAME@MIN
    /// (repeatable)
    ///
    /// MIN is the lowest version that works, such as bin:java@17. Needs an
    /// executable from --bin or release.toml. Each requirement is added to
    /// every artifact that has an executable.
    #[usage(long, help_heading = "Artifacts")]
    require: Vec<String>,
    /// Do not read the executables for the shared libraries and C library
    /// they load from the host
    ///
    /// With this flag, create still finds each --bin inside the archives but
    /// does not derive requires.libs; a libs list in release.toml is recorded
    /// as written, unchecked. A Linux artifact whose platform and file name
    /// give no C library is recorded as gnu, even a static build.
    #[usage(long, help_heading = "Artifacts")]
    no_libs: bool,
    /// Write identity.pin_workflow: false, so consumers do not hold later
    /// releases to this release's workflow file
    ///
    /// Use it when more than one workflow of your repository signs releases;
    /// consumers then hold later releases to the signing repository instead.
    /// The signing certificate must still record that repository as its
    /// source. A consumer that last accepted a release
    /// without the flag refuses the first one with it until a person
    /// approves it. Conflicts with --key, since only a keyless signer has a
    /// workflow. See https://packslip.dev/release/v1/#workflow-pinning
    #[usage(long, help_heading = "Signing")]
    no_pin_workflow: bool,
}

/// The `identity` block the signer declares, with `pin_workflow: false`
/// when the publisher asked for it. Only a keyless signer has a workflow.
#[cfg(all(feature = "create", feature = "manifest"))]
fn declared_identity(signer: &Signer, no_pin_workflow: bool) -> Result<packslip::model::Identity> {
    let mut identity = signer.identity();
    if no_pin_workflow {
        if identity.scheme != packslip::model::Scheme::SigstoreOidc {
            bail!("--no-pin-workflow applies to keyless signing; a key has no workflow");
        }
        identity.pin_workflow = Some(false);
    }
    Ok(identity)
}

/// `PATH` or `NAME=PATH`.
#[cfg(all(feature = "create", feature = "manifest"))]
fn parse_bin(spec: &str) -> Bin {
    match spec.split_once('=') {
        Some((name, path)) if !name.is_empty() && !path.is_empty() => Bin::named(path, name),
        _ => Bin::new(spec),
    }
}

/// A parsed `--resource`: the entry, and the local file behind an `asset`
/// source.
#[cfg(all(feature = "create", feature = "manifest"))]
struct ResourceSpec {
    resource: Resource,
    asset_path: Option<PathBuf>,
}

/// `KIND[/QUALIFIER...][@os[/arch[/libc]]]=SOURCE:VALUE`.
/// `completion/zsh=archive:PATH`,
/// `completion/bash,zsh,fish=exec:tool completion {shell}`,
/// `completion/bash,zsh=exec:COMPLETE={shell} tool` (leading `NAME=value`
/// words become `env`, as at a shell prompt),
/// `skill/NAME=repo:PATH`, `cli-spec/usage[/BIN]=exec:tool usage`,
/// `man=archive:PATH`, `man@linux=archive:PATH`, `app=archive:Tool.app`.
/// With one `--bin`, a `cli-spec` may omit the executable's name.
///
/// The scope is read from the head, which is a small closed grammar of
/// words, so an `@` there is always the scope and never part of a name.
/// The value is left alone, and an `@` inside an exec argv or a path
/// stays where it is.
#[cfg(all(feature = "create", feature = "manifest"))]
fn parse_resource(spec: &str, default_bin: Option<&str>) -> Result<ResourceSpec> {
    let Some((head, value)) = spec.split_once('=') else {
        bail!("--resource wants KIND[/QUALIFIER]=SOURCE:VALUE, got {spec:?}");
    };
    let (head, scope) = match head.split_once('@') {
        Some((head, scope)) => (head, Some(scope)),
        None => (head, None),
    };
    let mut parts = head.split('/');
    let kind = parts.next().unwrap_or_default();
    if kind.is_empty() {
        bail!("--resource {spec:?} has an empty kind");
    }
    let qualifiers: Vec<&str> = parts.collect();
    let mut resource = Resource::new(kind);
    match (kind, qualifiers.as_slice()) {
        ("completion", [shell]) if shell.contains(',') => {
            resource.shells = shell
                .split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_string)
                .collect();
        }
        ("completion", [shell]) => resource.shell = Some(shell.trim().to_string()),
        ("completion", [shell, bin]) => {
            if shell.contains(',') {
                resource.shells = shell
                    .split(',')
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(str::to_string)
                    .collect();
            } else {
                resource.shell = Some(shell.trim().to_string());
            }
            resource.bin = Some(bin.to_string());
        }
        ("completion", _) => {
            bail!("--resource {spec:?}: completion wants completion/SHELL[/BIN]")
        }
        ("man", []) => {}
        ("man", [bin]) => resource.bin = Some(bin.to_string()),
        ("man", _) => bail!("--resource {spec:?}: man wants man[/BIN]"),
        ("cli-spec", [format]) => {
            resource.format = Some(format.to_string());
            let Some(bin) = default_bin else {
                bail!("--resource {spec:?}: say which executable, as cli-spec/{format}/BIN");
            };
            resource.bin = Some(bin.to_string());
        }
        ("cli-spec", [format, bin]) => {
            resource.format = Some(format.to_string());
            resource.bin = Some(bin.to_string());
        }
        ("cli-spec", _) => bail!("--resource {spec:?}: cli-spec wants cli-spec/FORMAT[/BIN]"),
        ("skill", [name]) => resource.name = Some(name.to_string()),
        ("skill", _) => bail!("--resource {spec:?}: skill wants skill/NAME"),
        ("sbom", [format]) => resource.format = Some(format.to_string()),
        ("sbom", _) => bail!("--resource {spec:?}: sbom wants sbom/FORMAT (cyclonedx, spdx)"),
        (_, []) => {}
        (_, [name]) => resource.name = Some(name.to_string()),
        (_, _) => bail!("--resource {spec:?}: {kind} takes at most one qualifier"),
    }
    if let Some(scope) = scope {
        if !valid_scope(scope) {
            bail!("--resource {spec:?}: the @ scope wants os[/arch[/libc]], got {scope:?}");
        }
        let mut fields = scope.split('/');
        resource.os = fields.next().map(str::to_string);
        resource.arch = fields.next().map(str::to_string);
        resource.libc = fields.next().map(str::to_string);
    }
    let mut asset_path = None;
    match value.split_once(':') {
        Some(("archive", path)) => resource.archive = Some(path.to_string()),
        Some(("repo", path)) => resource.repo = Some(path.to_string()),
        Some(("exec", argv)) => {
            let mut words = argv.split_whitespace().peekable();
            while let Some((name, value)) = words.peek().and_then(|w| w.split_once('=')) {
                if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
                {
                    break;
                }
                resource.env.insert(name.to_string(), value.to_string());
                words.next();
            }
            resource.exec = words.map(str::to_string).collect();
            if resource.exec.is_empty() {
                bail!("--resource {spec:?}: exec wants a command after any NAME=value words");
            }
        }
        Some(("asset", path)) => {
            let path = PathBuf::from(path);
            let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
                bail!("--resource {spec:?}: asset wants a file path");
            };
            resource.asset = Some(name.to_string());
            asset_path = Some(path);
        }
        _ => bail!(
            "--resource {spec:?}: the value must start with archive:, asset:, repo:, or exec:"
        ),
    }
    Ok(ResourceSpec {
        resource,
        asset_path,
    })
}

/// `bin:NAME` or `bin:NAME@MIN` for `--require`.
#[cfg(all(feature = "create", feature = "manifest"))]
fn parse_require(spec: &str) -> Result<RequiredBin> {
    let Some(rest) = spec.strip_prefix("bin:") else {
        bail!("--require wants bin:NAME or bin:NAME@MIN, got {spec:?}");
    };
    let (name, min) = match rest.split_once('@') {
        Some((name, min)) => (name, Some(min)),
        None => (rest, None),
    };
    if name.is_empty() {
        bail!("--require {spec:?} has an empty command name");
    }
    if min == Some("") {
        bail!("--require {spec:?} has an empty minimum version");
    }
    Ok(match min {
        Some(min) => RequiredBin::at_least(name, min),
        None => RequiredBin::new(name),
    })
}

/// A requirement minimum as the specification spells one: an ASCII digit,
/// then ASCII letters, digits, `.`, `-`, and `+`. The library's validation
/// holds `requires.bin[].min` to the same grammar.
#[cfg(all(feature = "create", feature = "manifest"))]
fn valid_minimum(value: &str) -> bool {
    value.as_bytes().first().is_some_and(u8::is_ascii_digit)
        && value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'+'))
}

/// `KIND` or `KIND=DETAIL`.
#[cfg(all(feature = "create", feature = "manifest"))]
fn parse_evidence(spec: &str) -> Evidence {
    match spec.split_once('=') {
        Some((kind, detail)) => Evidence {
            kind: kind.to_string(),
            detail: Some(detail.to_string()),
        },
        None => Evidence {
            kind: spec.to_string(),
            detail: None,
        },
    }
}

/// `NAME=JSON` for `--extension`.
#[cfg(all(feature = "create", feature = "manifest"))]
fn parse_extension(spec: &str) -> Result<(String, serde_json::Value)> {
    let Some((name, json)) = spec.split_once('=') else {
        bail!("--extension wants NAME=JSON, got {spec:?}");
    };
    if name.is_empty() {
        bail!("--extension wants a NAME before the =, got {spec:?}");
    }
    let value = serde_json::from_str(json)
        .wrap_err_with(|| format!("--extension {name}: the value is not JSON: {json:?}"))?;
    Ok((name.to_string(), value))
}

/// The file name of a local path, for matching `--url`, `--provenance`,
/// and manifest entries against command-line artifacts.
#[cfg(all(feature = "create", feature = "manifest"))]
fn file_name_of(path: &Path) -> &str {
    path.file_name()
        .and_then(|n| n.to_str())
        .unwrap_or_default()
}

#[cfg(all(feature = "create", feature = "manifest"))]
impl RunWith<BinInfo> for Create {
    type Output = Result<()>;

    fn run_with(self, _: BinInfo) -> Self::Output {
        let manifest = match &self.manifest {
            Some(path) => Manifest::read(path)?,
            None => Manifest::default(),
        };
        // The command line wins over the manifest wherever both speak.
        let Some(project) = self.project.clone().or_else(|| manifest.project.clone()) else {
            bail!("--project is required unless the manifest names the project");
        };
        let Some(version) = self.version.clone().or_else(|| manifest.version.clone()) else {
            bail!("--version is required unless the manifest names the version");
        };
        let manifest_source = manifest.source.as_ref();
        let source_repo = self
            .source_repo
            .clone()
            .or_else(|| manifest_source.map(|s| s.repo.clone()));
        let commit = self
            .commit
            .clone()
            .or_else(|| manifest_source.and_then(|s| s.commit.clone()));
        let tag = self
            .tag
            .clone()
            .or_else(|| manifest_source.and_then(|s| s.tag.clone()));
        if source_repo.is_none() && (commit.is_some() || tag.is_some()) {
            bail!("--commit and --tag require --source-repo");
        }
        let attested_by = self.attested_by.map(|a| a.0).unwrap_or_default();
        if attested_by == Attestor::Vendor && !self.evidence.is_empty() {
            bail!("--evidence describes what a repackager checked; pass --attested-by repackager");
        }
        let signer = signer(&self.key, self.sign, self.no_log)?;
        let mut urls = std::collections::BTreeMap::new();
        for spec in &self.url {
            let Some((name, url)) = spec.split_once('=') else {
                bail!("--url wants FILENAME=URL, got {spec:?}");
            };
            urls.insert(name.to_string(), url.to_string());
        }
        let mut formats = std::collections::BTreeMap::new();
        for spec in &self.format {
            let Some((name, format)) = spec.split_once('=') else {
                bail!("--format wants FILENAME=FORMAT, got {spec:?}");
            };
            if format.is_empty() {
                bail!("--format {spec:?} has an empty format");
            }
            formats.insert(name.to_string(), format.to_string());
        }
        // The manifest's extensions first; a flag naming the same key wins.
        let mut extensions = manifest.extensions.clone();
        let mut from_flags = Extensions::new();
        for spec in &self.extension {
            let (name, value) = parse_extension(spec)?;
            if from_flags.insert(name.clone(), value.clone()).is_some() {
                bail!("--extension {name:?} is given twice");
            }
            extensions.insert(name, value);
        }
        let mut default_bins: Vec<Bin> = manifest.bin.clone();
        default_bins.extend(self.bin.iter().map(|s| parse_bin(s)));
        let mut requires_bin: Vec<RequiredBin> = Vec::new();
        for spec in &self.require {
            let required = parse_require(spec)?;
            if requires_bin.iter().any(|r| r.name == required.name) {
                bail!("--require names {:?} twice", required.name);
            }
            requires_bin.push(required);
        }
        let any_bin = !default_bins.is_empty()
            || manifest
                .artifacts
                .iter()
                .any(|a| !a.bins(&default_bins).is_empty());
        if !requires_bin.is_empty() && !any_bin {
            bail!("--require says what the executables need; name them with --bin");
        }
        let parsed: Vec<ArtifactArg> = self.artifacts.iter().map(|s| parse_spec(s)).collect();

        // Provenance: `FILENAME=URL`, or a bare URL for the artifact at the
        // same position on the command line.
        let mut provenance: std::collections::BTreeMap<String, String> =
            std::collections::BTreeMap::new();
        let mut positional = Vec::new();
        for spec in &self.provenance {
            match spec.split_once('=') {
                Some((name, url))
                    if !name.is_empty() && !name.contains('/') && !name.contains(':') =>
                {
                    provenance.insert(name.to_string(), url.to_string());
                }
                _ => positional.push(spec.clone()),
            }
        }
        for (arg, url) in parsed.iter().zip(positional) {
            provenance
                .entry(file_name_of(&arg.path).to_string())
                .or_insert(url);
        }
        let provenance_of = |name: &str, own: &[String]| -> Vec<String> {
            let mut all = own.to_vec();
            if let Some(url) = provenance.get(name)
                && !all.contains(url)
            {
                all.push(url.clone());
            }
            all
        };

        // The manifest's artifacts, then those on the command line that it
        // does not already describe, so `dist/*` and a manifest coexist.
        let mut artifacts: Vec<ArtifactInput<'_>> = Vec::new();
        for entry in &manifest.artifacts {
            let name = file_name_of(&entry.path);
            artifacts.push(ArtifactInput {
                path: &entry.path,
                os: entry.os.as_deref(),
                arch: entry.arch.as_deref(),
                libc: entry.libc.as_deref(),
                portable: entry.portable,
                variant: entry.variant.clone(),
                url: entry.url.clone().or_else(|| urls.get(name).cloned()),
                format: entry.format.clone().or_else(|| formats.get(name).cloned()),
                bin: entry.bins(&default_bins).to_vec(),
                requires: entry.requirements(manifest.requires.as_ref()),
                provenance: provenance_of(name, &entry.provenance),
                extensions: entry.extensions.clone(),
            });
        }
        for arg in &parsed {
            let name = file_name_of(&arg.path);
            if manifest
                .artifacts
                .iter()
                .any(|entry| file_name_of(&entry.path) == name)
            {
                continue;
            }
            artifacts.push(ArtifactInput {
                path: &arg.path,
                os: arg.os.as_deref(),
                arch: arg.arch.as_deref(),
                libc: arg.libc.as_deref(),
                portable: arg.portable,
                variant: arg.variant.clone(),
                url: urls.get(name).cloned(),
                format: formats.get(name).cloned(),
                bin: default_bins.clone(),
                requires: manifest.requires.clone(),
                provenance: provenance_of(name, &[]),
                extensions: Extensions::new(),
            });
        }
        if artifacts.is_empty() {
            bail!("no artifacts: give files on the command line or list them in the manifest");
        }
        // Validation leaves a malformed os_min or glibc_min to the consumer
        // as an unknown check, since packslips published before create
        // checked them may carry one, but a new document holds both to the
        // grammar of requires.bin[].min.
        for artifact in &artifacts {
            let Some(requires) = &artifact.requires else {
                continue;
            };
            for (field, value) in [
                ("os_min", &requires.os_min),
                ("glibc_min", &requires.glibc_min),
            ] {
                if let Some(value) = value
                    && !valid_minimum(value)
                {
                    bail!(
                        "artifact {:?} requires {field} {value:?}; a minimum starts with a digit and holds only letters, digits, ., -, and +, as in 2.31 or 10.0.17763",
                        file_name_of(artifact.path)
                    );
                }
            }
        }
        for name in provenance.keys() {
            if !artifacts.iter().any(|a| file_name_of(a.path) == name) {
                bail!("--provenance names {name:?}, which is not among the artifacts");
            }
        }

        let default_bin = match default_bins.as_slice() {
            [only] => Some(only.name.as_str()),
            _ => None,
        };
        let mut resources = Vec::new();
        let mut asset_paths: Vec<PathBuf> = Vec::new();
        let mut add_asset = |path: Option<PathBuf>| {
            if let Some(path) = path
                && !asset_paths.contains(&path)
            {
                asset_paths.push(path);
            }
        };
        for entry in &manifest.resources {
            let (resource, asset_path) = entry.resolve()?;
            add_asset(asset_path);
            resources.push(resource);
        }
        for spec in &self.resource {
            let parsed = parse_resource(spec, default_bin)?;
            add_asset(parsed.asset_path);
            resources.push(parsed.resource);
        }
        let assets: Vec<AssetInput<'_>> = asset_paths
            .iter()
            .map(|path| AssetInput {
                path,
                url: urls.get(file_name_of(path)).cloned(),
            })
            .collect();
        for name in urls.keys() {
            if !artifacts.iter().any(|a| file_name_of(a.path) == name)
                && !asset_paths.iter().any(|p| file_name_of(p) == name)
            {
                bail!("--url names {name:?}, which is not among the artifacts or assets");
            }
        }
        for name in formats.keys() {
            if !artifacts.iter().any(|a| file_name_of(a.path) == name) {
                bail!("--format names {name:?}, which is not among the artifacts");
            }
        }
        let source = source_repo.map(|repo| Source {
            repo,
            commit,
            tag: tag.clone(),
        });
        // On a forge, consumers list versions from tags and only then read
        // the packslip; a tag that names no version, or another one, makes
        // this release invisible to them unless a release list names it.
        if let Some(tag) = &tag
            && packslip::model::repository(&project).is_some()
            && packslip::model::tag_version(tag, &project).as_deref() != Some(version.as_str())
        {
            eprintln!(
                "warning: tag {tag:?} does not name version {version} (a tag is the version, optionally after a v and the tool's or repository's name); consumers listing {project} from its tags will not see this release unless a signed release list names it"
            );
        }
        let url_base = self.url_base.as_deref().or(manifest.url_base.as_deref());
        let notes_url = self.notes_url.as_deref().or(manifest.notes_url.as_deref());
        let published_at = self
            .published_at
            .as_deref()
            .or(manifest.published_at.as_deref());
        let created = packslip::create::create(&Request {
            published_at,
            source,
            artifacts,
            resources,
            assets,
            url_base,
            notes_url,
            extensions,
            attested_by,
            evidence: self.evidence.iter().map(|s| parse_evidence(s)).collect(),
            sha512: !self.no_sha512,
            requires_bin,
            read_executables: !self.no_libs,
            ..Request::new(
                &project,
                &version,
                declared_identity(&signer, self.no_pin_workflow)?,
            )
        })?;
        let identity = created.statement.predicate.identity.clone();
        let bundle = sigstore::sign(signer, &created.document)?;
        std::fs::create_dir_all(&self.out)
            .wrap_err_with(|| format!("creating {}", self.out.display()))?;
        let path = self.out.join(bundle_name(&project));
        std::fs::write(&path, &bundle)?;
        let resource_count = created.statement.predicate.resources.len();
        println!(
            "wrote {} ({} artifact(s){}, signed by {}{}{})",
            path.display(),
            created.statement.predicate.artifacts.len(),
            if resource_count > 0 {
                format!(", {resource_count} resource(s)")
            } else {
                String::new()
            },
            identity.key_id,
            if attested_by == Attestor::Repackager {
                ", repackager-attested"
            } else {
                ""
            },
            if self.no_log { ", unlogged" } else { "" }
        );
        for artifact in &created.statement.predicate.artifacts {
            if let Some(requires) = artifact.requires.as_ref().filter(|r| !r.is_empty()) {
                println!("  requires {}: {}", artifact.name, requires.summary());
            }
        }
        Ok(())
    }
}

/// An artifact argument: a path, optionally with `:os/arch[/libc]` or
/// `:any`, and `@variant`.
#[cfg(all(feature = "create", feature = "manifest"))]
struct ArtifactArg {
    path: PathBuf,
    os: Option<String>,
    arch: Option<String>,
    libc: Option<String>,
    portable: bool,
    variant: Option<String>,
}

/// Recognize only a well-formed `os/arch[/libc]` or `any` suffix and a
/// trailing `@variant`. In particular, colons inside timestamped
/// directory names remain part of the path, and so does an `@` inside a
/// file name that is not followed by a plain word.
#[cfg(all(feature = "create", feature = "manifest"))]
fn parse_spec(spec: &str) -> ArtifactArg {
    let (rest, variant) = match spec.rsplit_once('@') {
        Some((rest, variant)) if valid_word(variant) && !rest.is_empty() => {
            (rest, Some(variant.to_string()))
        }
        _ => (spec, None),
    };
    let plain = |path: &str, portable: bool| ArtifactArg {
        path: PathBuf::from(path),
        os: None,
        arch: None,
        libc: None,
        portable,
        variant: variant.clone(),
    };
    match rest.rsplit_once(':') {
        Some((path, "any")) if !path.is_empty() => plain(path, true),
        Some((path, platform)) if valid_platform(platform) => {
            let mut parts = platform.split('/');
            ArtifactArg {
                path: PathBuf::from(path),
                os: parts.next().map(str::to_string),
                arch: parts.next().map(str::to_string),
                libc: parts.next().map(str::to_string),
                portable: false,
                variant,
            }
        }
        _ => plain(rest, false),
    }
}

/// A variant is a word like `fips` or `install_only`, never something
/// with a dot in it, so `scoped@pkg-1.0.tgz` stays a file name.
#[cfg(all(feature = "create", feature = "manifest"))]
fn valid_word(part: &str) -> bool {
    part.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
        && part
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
}

/// A `--resource` scope: `os`, `os/arch`, or `os/arch/libc`. Unlike an
/// artifact's, the os alone is enough, which is how a resource says it is
/// in every Linux build without naming their architectures.
#[cfg(all(feature = "create", feature = "manifest"))]
fn valid_scope(scope: &str) -> bool {
    let parts: Vec<_> = scope.split('/').collect();
    (1..=3).contains(&parts.len()) && parts.iter().all(|part| valid_word(part))
}

#[cfg(all(feature = "create", feature = "manifest"))]
fn valid_platform(platform: &str) -> bool {
    let parts: Vec<_> = platform.split('/').collect();
    (parts.len() == 2 || parts.len() == 3)
        && parts.iter().all(|part| {
            part.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
                && part
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
        })
}

/// Create and sign a project's release list
///
/// Read local copies of released bundles and write a signed release list:
/// each release's bundle URL, digest, version, tag, and publish time, plus
/// the list's sequence and expiry. The bundles are read, not verified, so
/// give copies you trust. The list holds exactly the --release entries
/// given; the command does not append to an earlier list or upload
/// anything. With no --release, the list is empty, which retires every entry
/// an earlier list carried.
///
/// Publish it at https://HOST/.well-known/packslip/PATH.json for a project
/// named HOST/PATH, or at https://HOST/.well-known/packslip.json for a bare
/// host. A github.com project commits it to its default branch instead, as
/// .well-known/packslip.json, or .well-known/packslip/TOOL.json for a
/// monorepo tool. See https://packslip.dev/docs/release-lists/
#[derive(Debug, usage_rs::Args)]
#[usage(example(
    "packslip releases \\\n        --project mytool.example.com \\\n        --sequence \"$(date +%s)\" --valid-for 30d \\\n        --latest 1.2.3 \\\n        --release https://mytool.example.com/v1.2.3/packslip.sigstore.json=releases/v1.2.3/packslip.sigstore.json \\\n        --key release.key \\\n        --out site/.well-known/packslip.json",
    header = "List one key-signed release of a domain project"
))]
#[cfg(all(feature = "create", feature = "manifest"))]
struct Releases {
    /// The project's name, which every --release bundle must name
    #[usage(long)]
    project: String,
    /// This list's sequence number; increase it with every list you publish
    ///
    /// Consumers refuse a list whose sequence is lower than one they accepted.
    #[usage(long)]
    sequence: u64,
    /// Recommend this version to consumers that ask for the latest release
    ///
    /// It must exactly match a --release entry's version. Versions are not
    /// reordered.
    #[usage(long)]
    latest: Option<String>,
    /// How long until the list expires, as a number and a unit (s, m, h, d,
    /// or w), such as 30d
    ///
    /// Consumers refuse the list once it expires, so publish a new one, with
    /// a higher --sequence, before then.
    #[usage(long, default = "30d")]
    valid_for: String,
    /// RFC 3339 generation time, written in UTC; defaults to now
    #[usage(long)]
    generated_at: Option<String>,
    /// A released bundle as URL=PATH: where consumers fetch it, and the local
    /// copy to read (repeatable; omit it for an empty list)
    #[usage(long)]
    release: Vec<String>,
    /// Withdraw a listed release, as URL=REASON, with URL exactly as given
    /// to --release (repeatable)
    #[usage(long)]
    yank: Vec<String>,
    /// Mark a listed release as a security fix, by its --release URL
    /// (repeatable)
    #[usage(long)]
    security: Vec<String>,
    /// What a repackager checked about a listed release, as URL=KIND or
    /// URL=KIND=DETAIL with URL as given to --release (repeatable)
    #[usage(long)]
    evidence: Vec<String>,
    /// Sign with this secret key, from `packslip keygen`, instead of signing
    /// keyless
    #[usage(short = 'k', long, value_hint = usage_rs::ValueHint::FilePath, help_heading = "Signing")]
    key: Option<PathBuf>,
    /// How to sign: oidc (keyless, with the CI job's identity) or key (with
    /// --key)
    ///
    /// Defaults to key when --key is given, else oidc. sigstore-oidc and
    /// sigstore-key are other spellings. --sign key needs --key; --sign oidc
    /// conflicts with --key.
    #[usage(long, help_heading = "Signing")]
    sign: Option<SignWith>,
    /// Record no Rekor transparency log entry for a key signature
    ///
    /// Needs --key, since keyless signatures are always logged. Consumers
    /// must then pass --allow-unlogged.
    #[usage(long, help_heading = "Signing")]
    no_log: bool,
    /// Write identity.pin_workflow: false into the list, as `packslip create
    /// --no-pin-workflow` does for a release
    ///
    /// Conflicts with --key, since only a keyless signer has a workflow. See
    /// https://packslip.dev/release/v1/#workflow-pinning
    #[usage(long, help_heading = "Signing")]
    no_pin_workflow: bool,
    /// Where to write the list
    ///
    /// Consumers fetch a list only from its .well-known path, never under this
    /// default name.
    #[usage(short = 'o', long, default = "packslip-releases.sigstore.json")]
    out: PathBuf,
}

#[cfg(all(feature = "create", feature = "manifest"))]
impl RunWith<BinInfo> for Releases {
    type Output = Result<()>;

    fn run_with(self, _: BinInfo) -> Self::Output {
        let signer = signer(&self.key, self.sign, self.no_log)?;
        let mut pairs = Vec::new();
        for spec in &self.release {
            let Some((url, path)) = spec.split_once('=') else {
                bail!("--release wants URL=PATH, got {spec:?}");
            };
            pairs.push((url.to_string(), PathBuf::from(path)));
        }
        let mut yanked = std::collections::BTreeMap::new();
        for spec in &self.yank {
            let Some((url, reason)) = spec.split_once('=') else {
                bail!("--yank wants URL=REASON, got {spec:?}");
            };
            yanked.insert(url.to_string(), reason.to_string());
        }
        let mut evidence: std::collections::BTreeMap<String, Vec<Evidence>> =
            std::collections::BTreeMap::new();
        for spec in &self.evidence {
            let Some((url, rest)) = spec.split_once('=') else {
                bail!("--evidence wants URL=KIND or URL=KIND=DETAIL, got {spec:?}");
            };
            evidence
                .entry(url.to_string())
                .or_default()
                .push(parse_evidence(rest));
        }
        for url in yanked
            .keys()
            .chain(self.security.iter())
            .chain(evidence.keys())
        {
            if !pairs.iter().any(|(u, _)| u == url) {
                bail!("{url} is not among the --release entries");
            }
        }
        let releases = pairs
            .iter()
            .map(|(url, path)| ListedRelease {
                url,
                bundle_path: path,
                yanked: yanked.get(url).cloned(),
                security: self.security.contains(url),
                evidence: evidence.get(url).cloned().unwrap_or_default(),
            })
            .collect();
        let created = packslip::create::create_release_list(&ListRequest {
            project: &self.project,
            generated_at: self.generated_at.as_deref(),
            valid_for: parse_duration(&self.valid_for)?,
            sequence: self.sequence,
            latest: self.latest.as_deref(),
            releases,
            identity: declared_identity(&signer, self.no_pin_workflow)?,
        })?;
        let bundle = sigstore::sign(signer, &created.document)?;
        if let Some(parent) = self.out.parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&self.out, &bundle)?;
        println!(
            "wrote {} ({} release(s), sequence {}, expires {})",
            self.out.display(),
            created.statement.predicate.releases.len(),
            created.statement.predicate.sequence,
            created.statement.predicate.expires_at
        );
        Ok(())
    }
}

/// `30d`, `12h`, `2w`, `90m`, `45s`.
#[cfg(all(feature = "create", feature = "manifest"))]
fn parse_duration(s: &str) -> Result<std::time::Duration> {
    let s = s.trim();
    let split = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
    let (number, unit) = s.split_at(split);
    let number: u64 = number.parse().wrap_err_with(|| format!("duration {s:?}"))?;
    let seconds = match unit {
        "s" => 1,
        "m" => 60,
        "h" => 3600,
        "d" => 86_400,
        "w" => 7 * 86_400,
        _ => bail!("duration {s:?}: expected a unit of s, m, h, d or w"),
    };
    Ok(std::time::Duration::from_secs(number * seconds))
}

/// Verify a release bundle or release list, and downloaded files
///
/// Check the signature, the transparency log entry, and the statement. Each
/// --artifact file is checked against its signed digest, and an artifact
/// also against its signed size. Nothing is downloaded.
///
/// A github.com or gitlab.com project's name sets the policy. It requires the
/// forge's issuer and a certificate whose source repository is the project's,
/// or, if the certificate records none, a signer that is a workflow of the
/// project's repository. A reusable workflow the project calls may therefore
/// sign. --issuer, --identity, and --identity-prefix narrow that policy and
/// never replace it. A domain project, one named after a host such as
/// mytool.example.com, has no such policy, so pass --issuer with --identity,
/// --identity-prefix, --source-repository, or --pin. --pubkey verifies a
/// key-signed release instead. --source-repository and --pin add checks, and
/// --allow-other-repository accepts a signer outside the project's
/// repository, such as a repackager's.
///
/// Then check that the verified project and version are the ones you meant.
/// A release list's expiry and sequence are not checked. See
/// https://packslip.dev/docs/verifying/
#[derive(Debug, usage_rs::Args)]
#[usage(
    exit_code(0, "The bundle verified, and every --artifact matched it"),
    exit_code(
        1,
        "Verification failed, or an input was unusable: a file could not be read, a key or fingerprint is malformed, or the trust flags conflict or are missing"
    ),
    exit_code(2, "The command line is invalid"),
    example(
        "packslip verify packslip.sigstore.json \\\n        --artifact mytool-1.2.3-linux-x64.tar.gz",
        header = "Verify a GitHub release and a downloaded artifact"
    ),
    example(
        "packslip verify packslip.sigstore.json \\\n        --pin ps1_snirenkjwr7m5ozgcufameodnm \\\n        --artifact hk-x86_64-unknown-linux-gnu.tar.gz",
        header = "Verify hk 2.8.0 against its signer fingerprint"
    ),
    example(
        "packslip verify packslip.sigstore.json \\\n        --issuer https://token.actions.githubusercontent.com \\\n        --identity-prefix https://github.com/repackager/mytool/ \\\n        --allow-other-repository",
        header = "Verify a release a repackager signed from its own repository"
    ),
    example(
        "packslip verify packslip.sigstore.json \\\n        --pubkey release.pub \\\n        --artifact mytool-1.2.3-linux-x64.tar.gz",
        header = "Verify a key-signed release"
    )
)]
struct Verify {
    /// Local release bundle or signed release list to verify
    #[usage(value_hint = usage_rs::ValueHint::FilePath)]
    bundle: PathBuf,
    /// Require this public key: a minisign .pub file, such as one from
    /// `packslip keygen`, or its base64 line
    ///
    /// Conflicts with every other trust flag except --allow-unlogged and
    /// --trusted-root.
    #[usage(short = 'p', long, help_heading = "Trust")]
    pubkey: Option<String>,
    /// Require this exact certificate identity, ref included, such as
    /// https://github.com/owner/repo/.github/workflows/release.yml@refs/tags/v1.2.3
    ///
    /// A GitHub or GitLab repository name in it matches in any case; the rest
    /// matches exactly. For a domain project, also pass --issuer, or a
    /// certificate from any issuer is accepted.
    #[usage(long, help_heading = "Trust")]
    identity: Option<String>,
    /// Require a certificate identity that starts with this prefix, such as
    /// https://github.com/owner/repo/
    ///
    /// A GitHub or GitLab repository name in it matches in any case; the rest
    /// matches exactly. For a domain project, also pass --issuer, or a
    /// certificate from any issuer is accepted.
    #[usage(long, help_heading = "Trust")]
    identity_prefix: Option<String>,
    /// Require this OIDC issuer; for a domain project it alone accepts any
    /// signer from that issuer, so pair it with --identity, --identity-prefix,
    /// --source-repository, or --pin
    #[usage(long, help_heading = "Trust")]
    issuer: Option<String>,
    /// Require the certificate to record this source repository, such as
    /// https://github.com/owner/repo, whichever workflow signed
    ///
    /// Unlike an identity prefix of the repository, it also matches a
    /// reusable workflow of another repository that the repository's run
    /// called. A GitHub or GitLab repository name in it matches in any case.
    /// Needs --issuer. Conflicts with --identity and --identity-prefix.
    #[usage(long, help_heading = "Trust")]
    source_repository: Option<String>,
    /// Require this signer fingerprint (ps1_...), as `packslip pin` prints it
    #[usage(long, help_heading = "Trust")]
    pin: Option<String>,
    /// Accept a keyless signer outside the project's repository, such as a
    /// repackager's
    ///
    /// For a github.com or gitlab.com project. Needs --issuer and one of
    /// --identity, --identity-prefix, or --source-repository to name the
    /// signer. Conflicts with --pubkey.
    #[usage(long, help_heading = "Trust")]
    allow_other_repository: bool,
    /// Accept a bundle without a transparency log entry, such as one created
    /// with --key --no-log
    #[usage(long, help_heading = "Trust")]
    allow_unlogged: bool,
    /// Use this Sigstore trusted_root.json instead of the embedded one
    #[usage(long, value_hint = usage_rs::ValueHint::FilePath, help_heading = "Trust")]
    trusted_root: Option<PathBuf>,
    /// A downloaded artifact or resource asset to check against its signed
    /// digest, and an artifact also against its size (repeatable)
    ///
    /// Files are matched by name, so keep the name each was published under.
    /// A release list has no artifacts to check.
    #[usage(short = 'a', long)]
    artifact: Vec<PathBuf>,
    /// Print the verified report as JSON
    ///
    /// The report lists every artifact with its signed digest, and
    /// source_repository when the signing certificate records one. For a
    /// release list, the verified list statement is printed instead.
    #[usage(short = 'J', long, help_heading = "Output")]
    json: bool,
}

/// An owned pin, so a `Trust` can borrow it.
enum TrustPin {
    Key(PublicKey),
    Identity(Policy),
}

impl TrustPin {
    fn as_trust(&self) -> Trust<'_> {
        match self {
            TrustPin::Key(key) => Trust::Key(key),
            TrustPin::Identity(policy) => Trust::Identity(policy),
        }
    }
}

impl RunWith<BinInfo> for Verify {
    type Output = Result<()>;

    fn run_with(self, _: BinInfo) -> Self::Output {
        let text = std::fs::read_to_string(&self.bundle)
            .wrap_err_with(|| format!("reading {}", self.bundle.display()))?;
        let peeked: serde_json::Value = serde_json::from_slice(&sigstore::peek_statement(&text)?)
            .wrap_err("the bundle's payload is not JSON")?;
        let project = peeked["predicate"]["project"].as_str().unwrap_or_default();
        let is_list = peeked["predicateType"] == RELEASES_PREDICATE_TYPE;

        let want_fingerprint: Option<Fingerprint> = match &self.pin {
            Some(pin) => Some(pin.parse().wrap_err("--pin")?),
            None => None,
        };
        if self.allow_other_repository
            && self.pubkey.is_none()
            && self.identity.is_none()
            && self.identity_prefix.is_none()
            && self.source_repository.is_none()
        {
            bail!(
                "--allow-other-repository accepts a signer outside the project's repository, so name that signer with --identity, --identity-prefix, or --source-repository"
            );
        }
        if self.allow_other_repository && self.pubkey.is_none() && self.issuer.is_none() {
            bail!(
                "--allow-other-repository needs --issuer: a signer outside the project's repository is only as good as the issuer that vouches for it"
            );
        }
        let pin = match &self.pubkey {
            Some(text) => {
                if self.identity.is_some()
                    || self.identity_prefix.is_some()
                    || self.issuer.is_some()
                    || self.source_repository.is_some()
                {
                    bail!(
                        "--pubkey pins a key; the identity flags pin a certificate. Pass one kind"
                    );
                }
                if want_fingerprint.is_some() {
                    bail!(
                        "--pin is the fingerprint of a certificate's repository; a key has none. Use --pubkey alone"
                    );
                }
                if self.allow_other_repository {
                    bail!(
                        "--allow-other-repository is about a certificate's repository; a key has none. Use --pubkey alone"
                    );
                }
                let pubkey_text = if Path::new(text).is_file() {
                    std::fs::read_to_string(text)?
                } else {
                    text.clone()
                };
                TrustPin::Key(PublicKey::parse(&pubkey_text)?)
            }
            None if self.source_repository.is_some() => {
                if self.identity.is_some() || self.identity_prefix.is_some() {
                    bail!(
                        "--source-repository pins the repository, not a workflow; drop --identity and --identity-prefix"
                    );
                }
                let Some(issuer) = &self.issuer else {
                    bail!(
                        "--source-repository needs --issuer: the repository is only as good as the issuer that vouches for it"
                    );
                };
                TrustPin::Identity(Policy {
                    issuer: Some(issuer.clone()),
                    identity: None,
                    identity_prefix: None,
                })
            }
            None => TrustPin::Identity(identity_policy(
                &self.identity,
                &self.identity_prefix,
                &self.issuer,
                project,
                sigstore::Error::NoPolicy,
            )?),
        };
        let trusted_root = load_trusted_root(self.trusted_root.as_deref())?;
        let options = Options {
            require_log: !self.allow_unlogged,
            trusted_root: &trusted_root,
        };
        let artifacts: Vec<&Path> = self.artifact.iter().map(PathBuf::as_path).collect();
        // Only a certificate names a repository; a pinned key is the whole
        // policy.
        let keyless = matches!(pin, TrustPin::Identity(_));

        if is_list {
            if !artifacts.is_empty() {
                bail!("a release list has no artifacts to check");
            }
            return match packslip::verify_release_list(&text, &pin.as_trust(), options) {
                Ok(verified) => {
                    let list = &verified.list.predicate;
                    // The list verified, so its certificate's record of the
                    // repository is the one Fulcio issued.
                    let source = sigstore::source_repository(&text)?;
                    if keyless
                        && let Err(err) = self.check_signer(
                            &list.project,
                            &verified.key_id,
                            verified.issuer.as_deref(),
                            source.as_ref(),
                            want_fingerprint.as_ref(),
                        )
                    {
                        eprintln!("verification failed: {err}");
                        std::process::exit(1)
                    }
                    if self.json {
                        println!("{}", serde_json::to_string_pretty(&verified.list)?);
                    } else {
                        let yanked = list.releases.iter().filter(|r| r.is_yanked()).count();
                        println!(
                            "ok: release list for {} sequence {} expires {} signed by {} ({}) listing {} release(s){}",
                            list.project,
                            list.sequence,
                            list.expires_at,
                            verified.key_id,
                            verified.scheme,
                            list.releases.len(),
                            if yanked > 0 {
                                format!(", {yanked} yanked")
                            } else {
                                String::new()
                            }
                        );
                        if let Some(source) = &source {
                            println!("  repository {}", describe_source(source));
                        }
                    }
                    Ok(())
                }
                Err(err) => {
                    eprintln!("verification failed: {err}");
                    std::process::exit(1)
                }
            };
        }
        match packslip::verify(&text, &pin.as_trust(), options, &artifacts) {
            Ok(verified) => {
                // The bundle verified, so its certificate's record of the
                // repository is the one Fulcio issued.
                let source = sigstore::source_repository(&text)?;
                if keyless
                    && let Err(err) = self.check_signer(
                        &verified.project,
                        &verified.key_id,
                        verified.issuer.as_deref(),
                        source.as_ref(),
                        want_fingerprint.as_ref(),
                    )
                {
                    eprintln!("verification failed: {err}");
                    std::process::exit(1)
                }
                if self.json {
                    let report = packslip::VerifyReport {
                        verified: &verified,
                        source_repository: source.as_ref(),
                    };
                    println!("{}", serde_json::to_string_pretty(&report)?);
                } else {
                    println!(
                        "ok: {} {}{} published {} signed by {} ({}){}{} ({}{} checked{}{})",
                        verified.project,
                        verified.version,
                        match (&verified.channel, verified.prerelease) {
                            (Some(channel), _) => format!(" ({channel} prerelease)"),
                            (None, true) => " (prerelease)".to_string(),
                            (None, false) => String::new(),
                        },
                        verified.published_at,
                        verified.key_id,
                        verified.scheme,
                        if verified.attested_by == Attestor::Repackager {
                            " repackager-attested"
                        } else {
                            ""
                        },
                        match &verified.logged_at {
                            Some(at) => format!(" logged {at}"),
                            None => " unlogged".to_string(),
                        },
                        format_args!(
                            "{} of {} artifact(s)",
                            verified.checked_artifacts.len(),
                            verified.artifact_count
                        ),
                        // Only a release that lists assets counts them, so
                        // the line for one that lists none is unchanged.
                        if verified.asset_count == 0 {
                            String::new()
                        } else {
                            format!(
                                " and {} of {} asset(s)",
                                verified.checked_assets.len(),
                                verified.asset_count
                            )
                        },
                        if verified.provenance_linked {
                            ", provenance linked"
                        } else {
                            ""
                        },
                        if verified.resources.is_empty() {
                            String::new()
                        } else {
                            format!(", {} resource(s)", verified.resources.len())
                        }
                    );
                    if let Some(source) = &source {
                        println!("  repository {}", describe_source(source));
                    }
                    for line in &verified.requires {
                        println!("  requires {line}");
                    }
                }
                Ok(())
            }
            Err(err) => {
                eprintln!("verification failed: {err}");
                std::process::exit(1)
            }
        }
    }
}

impl Verify {
    /// What a verified keyless signer must still satisfy: the
    /// --source-repository and --pin the user passed, and, unless
    /// --allow-other-repository was passed, the repository a GitHub or
    /// GitLab project names. The identity flags only narrow that
    /// requirement, so --issuer alone cannot accept another repository's
    /// signature for the project.
    fn check_signer(
        &self,
        project: &str,
        signer: &str,
        issuer: Option<&str>,
        source: Option<&sigstore::SourceRepository>,
        want_fingerprint: Option<&Fingerprint>,
    ) -> std::result::Result<(), String> {
        if let Some(want) = self.source_repository.as_deref() {
            require_source_repository(want, source)?;
        }
        if !self.allow_other_repository {
            signed_from_project(project, signer, issuer, source, &self.narrowing_flags())?;
        }
        if let Some(want) = want_fingerprint {
            want.verify(issuer, source).map_err(|e| e.to_string())?;
        }
        Ok(())
    }

    /// The trust flags passed that narrow a keyless signer's policy, for a
    /// refusal to name.
    fn narrowing_flags(&self) -> Vec<&'static str> {
        [
            ("--identity", self.identity.is_some()),
            ("--identity-prefix", self.identity_prefix.is_some()),
            ("--issuer", self.issuer.is_some()),
            ("--source-repository", self.source_repository.is_some()),
            ("--pin", self.pin.is_some()),
        ]
        .into_iter()
        .filter_map(|(flag, passed)| passed.then_some(flag))
        .collect()
    }
}

/// Whether a verified certificate records `want` as its source repository.
/// Fulcio derives the record from the forge's token, so it names the
/// repository whose run signed, whichever workflow that was. A GitHub or
/// GitLab repository's name matches in any case, as the forge resolves it.
fn require_source_repository(
    want: &str,
    source: Option<&sigstore::SourceRepository>,
) -> std::result::Result<(), String> {
    let wanted = |uri: &str| {
        let want = want.trim_end_matches('/');
        match (uri.strip_prefix("https://"), want.strip_prefix("https://")) {
            (Some(uri), Some(want)) => packslip::forge::same_project(uri, want),
            _ => uri == want,
        }
    };
    match source {
        Some(source) if wanted(&source.uri) => Ok(()),
        Some(source) => Err(format!(
            "the certificate's source repository is {}, expected {want}",
            source.uri
        )),
        None => Err(format!(
            "the certificate records no source repository, expected {want}"
        )),
    }
}

/// Whether a verified keyless signer belongs to the repository a GitHub or
/// GitLab project names, as [`bound_to_project`] decides, with a refusal
/// that says what was expected, what signed, and how to accept a signer
/// outside the repository on purpose. `flags` are the trust flags passed.
/// A project on any other host names no repository, so nothing is checked.
fn signed_from_project(
    project: &str,
    signer: &str,
    issuer: Option<&str>,
    source: Option<&sigstore::SourceRepository>,
    flags: &[&str],
) -> std::result::Result<(), String> {
    use packslip::forge::IdentityError;
    let reason = match bound_to_project(project, signer, issuer, source) {
        Ok(()) => return Ok(()),
        Err(IdentityError::SourceMismatch {
            certificate,
            repository,
        }) => format!(
            "{project} must be signed from its repository {repository}, but {signer} signed it from {certificate}"
        ),
        Err(IdentityError::SignerOutsideRepository { repository, .. }) => format!(
            "{project} must be signed from its repository {repository}, but {signer} is not one of its workflows"
        ),
        Err(IdentityError::Issuer {
            expected, actual, ..
        }) => format!(
            "{project} must be signed from its repository through {expected}, but {signer} signed it through {}",
            actual.as_deref().unwrap_or("no issuer")
        ),
        Err(err) => err.to_string(),
    };
    // The refusal names the flags passed, which do not lift the requirement.
    let remedy = "accept a signer outside that repository, name it with --issuer and --identity, --identity-prefix, or --source-repository, and add --allow-other-repository";
    let named = match flags {
        [] => return Err(format!("{reason}. To {remedy}")),
        [flag] => {
            return Err(format!(
                "{reason}. {flag} narrows what the project's name requires and does not replace it; to {remedy}"
            ));
        }
        [first, last] => format!("{first} and {last}"),
        [init @ .., last] => format!("{}, and {last}", init.join(", ")),
    };
    Err(format!(
        "{reason}. {named} narrow what the project's name requires and do not replace it; to {remedy}"
    ))
}

/// The certificate policy for `project`: the identity flags, or else the
/// one its GitHub or GitLab name implies. `missing` builds the error for a
/// project that is on neither, so each command can name the flags it has.
///
/// The policy a forge name implies is the forge's issuer alone, the one
/// `packslip install` verifies under ([`packslip::forge::policy`]): the
/// certificate's source repository, not the workflow that signed, binds a
/// release to the project, so a reusable workflow of another repository
/// may sign. That policy accepts any signer the issuer vouches for, so the
/// caller must then bind the release to the project with
/// [`bound_to_project`], as `verify` and `pin` do for every keyless signer.
fn identity_policy(
    identity: &Option<String>,
    identity_prefix: &Option<String>,
    issuer: &Option<String>,
    project: &str,
    missing: fn(String) -> sigstore::Error,
) -> Result<Policy> {
    let explicit = Policy {
        issuer: issuer.clone(),
        identity: identity.clone(),
        identity_prefix: identity_prefix.clone(),
    };
    if explicit.is_empty() {
        // `Policy::for_project` decides which names are forge projects, as
        // it does for install.
        let derived = Policy::for_project(project)
            .and_then(|_| packslip::forge::policy(project, project))
            .ok_or_else(|| missing(project.into()))?;
        Ok(derived)
    } else {
        Ok(explicit)
    }
}

fn load_trusted_root(path: Option<&Path>) -> Result<sigstore_trust_root::TrustedRoot> {
    let json = match path {
        Some(path) => Some(
            std::fs::read_to_string(path)
                .wrap_err_with(|| format!("reading {}", path.display()))?,
        ),
        None => None,
    };
    Ok(sigstore::trusted_root(json.as_deref())?)
}

/// Whether what a verified certificate says about its repository is about
/// the project the statement names. A signer can be a reusable workflow of
/// another repository, so the certificate's own source repository must be
/// the project's, whichever workflow signed. A project that is not on a forge
/// has nothing to compare.
fn bound_to_project(
    project: &str,
    signer: &str,
    issuer: Option<&str>,
    source: Option<&sigstore::SourceRepository>,
) -> std::result::Result<(), packslip::forge::IdentityError> {
    match packslip::forge::check_source(
        &packslip::forge::Expected::new(project),
        project,
        signer,
        issuer,
        source,
    ) {
        Ok(_) | Err(packslip::forge::IdentityError::NotForge(_)) => Ok(()),
        Err(err) => Err(err),
    }
}

/// The signer fingerprint of a verified keyless release.
fn signer_fingerprint(
    project: &str,
    signer: &str,
    issuer: Option<&str>,
    source: Option<&sigstore::SourceRepository>,
) -> std::result::Result<Fingerprint, String> {
    if issuer.is_none() {
        return Err(format!(
            "{project} is signed with a key, which has no signer fingerprint; pin it with --pubkey"
        ));
    }
    bound_to_project(project, signer, issuer, source).map_err(|e| e.to_string())?;
    Fingerprint::of_signer(issuer, source).ok_or_else(|| {
        format!(
            "{project}'s certificate records no repository ID, so it has no signer fingerprint; pin it with --identity-prefix and --issuer instead"
        )
    })
}

/// Verify a release bundle and print its signer fingerprint
///
/// The fingerprint, `ps1_` and 26 characters, comes from the forge's issuer
/// and the signing repository's ID. It stays the same when the repository is
/// renamed, moves to another owner, or signs from another workflow; a
/// repository that later takes the old name gets a different one. Only a
/// keyless release whose certificate records a repository ID has one; a
/// key-signed release is pinned by its key, with `packslip verify --pubkey`.
///
/// Verification works as in `packslip verify` without
/// --allow-other-repository. A domain project, one named after a host such as
/// mytool.example.com, has no policy from its name, so pass --issuer with
/// --identity or --identity-prefix. Only the fingerprint is printed, on
/// stdout.
///
/// Run pin on a release you already trust, since it fingerprints whichever
/// repository signed. Publish the value where consumers can read it without
/// trusting a release, such as a README, and check releases with `packslip
/// verify --pin` or `packslip install --pin`. See
/// https://packslip.dev/docs/verifying/#pin-a-signer-with-its-fingerprint
#[derive(Debug, usage_rs::Args)]
#[usage(
    exit_code(0, "Printed the signer fingerprint"),
    exit_code(
        1,
        "Verification failed, the release has no signer fingerprint, or an input was unusable"
    ),
    exit_code(2, "The command line is invalid"),
    example(
        "packslip pin packslip.sigstore.json",
        header = "Print the fingerprint of a release you already trust"
    )
)]
struct Pin {
    /// Local release bundle to verify and fingerprint
    #[usage(value_hint = usage_rs::ValueHint::FilePath)]
    bundle: PathBuf,
    /// Require this exact certificate identity, ref included, such as
    /// https://github.com/owner/repo/.github/workflows/release.yml@refs/tags/v1.2.3
    ///
    /// A GitHub or GitLab repository name in it matches in any case; the rest
    /// matches exactly. For a domain project, also pass --issuer, or a
    /// certificate from any issuer is accepted.
    #[usage(long, help_heading = "Trust")]
    identity: Option<String>,
    /// Require a certificate identity that starts with this prefix, such as
    /// https://github.com/owner/repo/
    ///
    /// A GitHub or GitLab repository name in it matches in any case; the rest
    /// matches exactly. For a domain project, also pass --issuer, or a
    /// certificate from any issuer is accepted.
    #[usage(long, help_heading = "Trust")]
    identity_prefix: Option<String>,
    /// Require this OIDC issuer; for a domain project it alone accepts any
    /// signer from that issuer, so pair it with --identity or
    /// --identity-prefix
    #[usage(long, help_heading = "Trust")]
    issuer: Option<String>,
    /// Accept a bundle without a transparency log entry
    #[usage(long, help_heading = "Trust")]
    allow_unlogged: bool,
    /// Use this Sigstore trusted_root.json instead of the embedded one
    #[usage(long, value_hint = usage_rs::ValueHint::FilePath, help_heading = "Trust")]
    trusted_root: Option<PathBuf>,
}

impl RunWith<BinInfo> for Pin {
    type Output = Result<()>;

    fn run_with(self, _: BinInfo) -> Self::Output {
        let text = std::fs::read_to_string(&self.bundle)
            .wrap_err_with(|| format!("reading {}", self.bundle.display()))?;
        let peeked: serde_json::Value = serde_json::from_slice(&sigstore::peek_statement(&text)?)
            .wrap_err("the bundle's payload is not JSON")?;
        if peeked["predicateType"] == RELEASES_PREDICATE_TYPE {
            bail!("a release list is not a release; give a release's packslip.sigstore.json");
        }
        let project = peeked["predicate"]["project"].as_str().unwrap_or_default();
        let policy = identity_policy(
            &self.identity,
            &self.identity_prefix,
            &self.issuer,
            project,
            sigstore::Error::NoIdentityPolicy,
        )?;
        let trusted_root = load_trusted_root(self.trusted_root.as_deref())?;
        let options = Options {
            require_log: !self.allow_unlogged,
            trusted_root: &trusted_root,
        };
        let verified = match packslip::verify(&text, &Trust::Identity(&policy), options, &[]) {
            Ok(verified) => verified,
            Err(err) => {
                eprintln!("verification failed: {err}");
                std::process::exit(1)
            }
        };
        // The bundle verified, so its certificate's record of the
        // repository is the one Fulcio issued.
        let source = sigstore::source_repository(&text)?;
        match signer_fingerprint(
            &verified.project,
            &verified.key_id,
            verified.issuer.as_deref(),
            source.as_ref(),
        ) {
            Ok(fingerprint) => {
                println!("{fingerprint}");
                Ok(())
            }
            Err(err) => {
                eprintln!("{err}");
                std::process::exit(1)
            }
        }
    }
}

/// The signing repository and the forge's IDs for it and its owner:
/// `https://github.com/jdx/hk (id 922514152), owner https://github.com/jdx (id 216188)`.
fn describe_source(source: &sigstore::SourceRepository) -> String {
    let with_id = |uri: &str, id: &Option<String>| match id {
        Some(id) => format!("{uri} (id {id})"),
        None => uri.to_string(),
    };
    let mut line = with_id(&source.uri, &source.id);
    if let Some(owner) = &source.owner_uri {
        line.push_str(&format!(", owner {}", with_id(owner, &source.owner_id)));
    }
    line
}

fn main() -> Result<()> {
    color_eyre::install()?;
    let args: Vec<_> = std::env::args_os().collect();
    if let Some(answer) = Cli::completion_request(&args[1..]) {
        print!("{answer}");
        return Ok(());
    }
    let argv = packslip::cli::argv(&args);
    let cli = packslip::cli::unwrap_or_exit(Cli::spec(), &argv, Cli::parse_from_argv(&argv));
    match cli.command {
        Some(command) => command.run_with(BIN),
        None => Ok(()),
    }
}

#[cfg(all(test, feature = "create", feature = "manifest"))]
mod tests {
    use super::*;

    #[test]
    fn artifact_specs() {
        let spec = parse_spec("build/2026-09-01T12:00:00Z/tool.tar.gz");
        assert_eq!(
            spec.path,
            PathBuf::from("build/2026-09-01T12:00:00Z/tool.tar.gz")
        );
        assert!(spec.os.is_none());
        assert!(spec.variant.is_none());
        let spec = parse_spec("weird.bin:freebsd/riscv64");
        assert_eq!(spec.os.as_deref(), Some("freebsd"));
        assert_eq!(spec.arch.as_deref(), Some("riscv64"));
        let spec = parse_spec("tool.tar.gz:linux/x86_64/musl@fips");
        assert_eq!(spec.libc.as_deref(), Some("musl"));
        assert_eq!(spec.variant.as_deref(), Some("fips"));
        let spec = parse_spec("tool-fips.tar.gz@fips");
        assert_eq!(spec.path, PathBuf::from("tool-fips.tar.gz"));
        assert_eq!(spec.variant.as_deref(), Some("fips"));
        let spec = parse_spec("scoped@pkg-1.0.tgz");
        assert_eq!(spec.path, PathBuf::from("scoped@pkg-1.0.tgz"));
        assert!(spec.variant.is_none(), "a variant is a plain word");
        let spec = parse_spec("tool.jar:any");
        assert_eq!(spec.path, PathBuf::from("tool.jar"));
        assert!(spec.portable);
        let spec = parse_spec("tool-linux.jar:any@slim");
        assert!(spec.portable);
        assert_eq!(spec.variant.as_deref(), Some("slim"));
    }

    #[test]
    fn bins_and_evidence_parse() {
        assert_eq!(parse_bin("bin/tool"), Bin::new("bin/tool"));
        assert_eq!(
            parse_bin("oxlint=bin/oxlint-x86_64"),
            Bin::named("bin/oxlint-x86_64", "oxlint")
        );
        assert_eq!(parse_evidence("pkgbuild-checksums").detail, None);
        assert_eq!(
            parse_evidence("apt-release-gpg=3FEF9748").detail.as_deref(),
            Some("3FEF9748")
        );
    }

    #[test]
    fn resources_parse() {
        let r = parse_resource(
            "completion/zsh=archive:share/zsh/site-functions/_tool",
            None,
        )
        .unwrap();
        assert_eq!(r.resource.kind, "completion");
        assert_eq!(r.resource.shell.as_deref(), Some("zsh"));
        assert_eq!(
            r.resource.archive.as_deref(),
            Some("share/zsh/site-functions/_tool")
        );
        assert!(r.asset_path.is_none());
        let r = parse_resource(
            "completion/bash,zsh,fish=exec:tool completion {shell}",
            None,
        )
        .unwrap();
        assert_eq!(r.resource.shells, ["bash", "zsh", "fish"]);
        assert_eq!(r.resource.exec, ["tool", "completion", "{shell}"]);
        let r = parse_resource(
            "completion/bash,zsh=exec:COMPLETE={shell} _TOOL_X=1 tool",
            None,
        )
        .unwrap();
        assert_eq!(r.resource.exec, ["tool"]);
        assert_eq!(r.resource.env["COMPLETE"], "{shell}");
        assert_eq!(r.resource.env["_TOOL_X"], "1");
        assert!(parse_resource("man=exec:ONLY=env", None).is_err());
        let r = parse_resource(
            "completion/bash, zsh,,fish =exec:tool completion {shell}",
            None,
        )
        .unwrap();
        assert_eq!(r.resource.shells, ["bash", "zsh", "fish"]);
        let r = parse_resource("cli-spec/usage=exec:tool usage", Some("tool")).unwrap();
        assert_eq!(r.resource.format.as_deref(), Some("usage"));
        assert_eq!(r.resource.bin.as_deref(), Some("tool"));
        let r = parse_resource("cli-spec/usage/other=repo:specs/other.kdl", Some("tool")).unwrap();
        assert_eq!(r.resource.bin.as_deref(), Some("other"));
        assert_eq!(r.resource.repo.as_deref(), Some("specs/other.kdl"));
        let r = parse_resource("completion/zsh/other=archive:share/_other", None).unwrap();
        assert_eq!(r.resource.shell.as_deref(), Some("zsh"));
        assert_eq!(r.resource.bin.as_deref(), Some("other"));
        let r = parse_resource(
            "completion/bash,zsh/other=exec:other completion {shell}",
            None,
        )
        .unwrap();
        assert_eq!(r.resource.shells, ["bash", "zsh"]);
        assert_eq!(r.resource.bin.as_deref(), Some("other"));
        let r = parse_resource("man/other=archive:share/man/other.1", None).unwrap();
        assert_eq!(r.resource.bin.as_deref(), Some("other"));
        assert!(r.resource.name.is_none());
        assert!(parse_resource("cli-spec/usage=repo:x", None).is_err());
        let r = parse_resource("skill/tool=asset:dist/tool-skill.tar.gz", None).unwrap();
        assert_eq!(r.resource.name.as_deref(), Some("tool"));
        assert_eq!(r.resource.asset.as_deref(), Some("tool-skill.tar.gz"));
        assert_eq!(r.asset_path, Some(PathBuf::from("dist/tool-skill.tar.gz")));
        let r = parse_resource("man=archive:man/man1/tool.1", None).unwrap();
        assert!(r.resource.name.is_none());
        let r = parse_resource("font/Tool=archive:fonts/Tool.ttf", None).unwrap();
        assert_eq!(r.resource.name.as_deref(), Some("Tool"));
        let r = parse_resource("sbom/cyclonedx=asset:dist/tool.cdx.json", None).unwrap();
        assert_eq!(r.resource.format.as_deref(), Some("cyclonedx"));
        assert_eq!(r.resource.name, None);
        assert_eq!(r.resource.asset.as_deref(), Some("tool.cdx.json"));
        assert!(parse_resource("sbom=asset:dist/tool.cdx.json", None).is_err());

        // An @ scope limits the entry to one platform, from the os alone
        // down to os/arch/libc, and rides alongside any qualifier.
        let r = parse_resource("man@linux=archive:share/man/man1/tool.1", None).unwrap();
        assert_eq!(r.resource.os.as_deref(), Some("linux"));
        assert_eq!(r.resource.arch, None);
        assert_eq!(r.resource.libc, None);
        assert_eq!(r.resource.archive.as_deref(), Some("share/man/man1/tool.1"));
        let r = parse_resource("completion/zsh@linux/x86_64/musl=archive:_tool", None).unwrap();
        assert_eq!(r.resource.shell.as_deref(), Some("zsh"));
        assert_eq!(
            (
                r.resource.os.as_deref(),
                r.resource.arch.as_deref(),
                r.resource.libc.as_deref()
            ),
            (Some("linux"), Some("x86_64"), Some("musl"))
        );
        // Only the head is read for a scope, so an @ in an exec argv or a
        // path is left where it is.
        let r = parse_resource("cli-spec/usage/tool=exec:tool usage @all", None).unwrap();
        assert_eq!(r.resource.os, None);
        assert_eq!(r.resource.exec, ["tool", "usage", "@all"]);
        let r = parse_resource("skill/tool=repo:skills/@tool", None).unwrap();
        assert_eq!(r.resource.repo.as_deref(), Some("skills/@tool"));
        assert_eq!(r.resource.os, None);

        for bad in [
            "man",
            "=archive:x",
            "man=x",
            "man=ftp:x",
            "completion=archive:x",
            "skill=archive:x",
            "man/a/b=archive:x",
            "man@=archive:x",
            "man@linux/x86_64/gnu/extra=archive:x",
            "man@linux//gnu=archive:x",
            "man@1inux=archive:x",
        ] {
            assert!(parse_resource(bad, None).is_err(), "{bad}");
        }
    }

    #[test]
    fn bundle_names() {
        assert_eq!(bundle_name("github.com/jdx/mise"), "packslip.sigstore.json");
        assert_eq!(bundle_name("mise.jdx.dev"), "packslip.sigstore.json");
        assert_eq!(bundle_name("example.com/tool"), "packslip.sigstore.json");
        assert_eq!(
            bundle_name("github.com/oxc-project/oxc/oxlint"),
            "packslip.oxlint.sigstore.json"
        );
        assert_eq!(
            bundle_name("github.com/biomejs/biome/crates/cli"),
            "packslip.crates-cli.sigstore.json"
        );
    }

    #[test]
    fn durations() {
        assert_eq!(
            parse_duration("30d").unwrap(),
            std::time::Duration::from_secs(30 * 86_400)
        );
        assert_eq!(
            parse_duration("2w").unwrap(),
            std::time::Duration::from_secs(14 * 86_400)
        );
        assert!(parse_duration("3x").is_err());
        assert!(parse_duration("").is_err());
    }
}

/// What `verify` asks of a keyless signer once its signature checks out.
/// A bundle signed from another repository needs a live Fulcio certificate,
/// so these cases take hk 2.3.0's real certificate and put it to a statement
/// naming another project, or describe a certificate without one.
#[cfg(test)]
mod signer_tests {
    use super::*;
    use packslip::sigstore::{GITHUB_ISSUER, SourceRepository};

    const HK: &str = include_str!("../tests/fixtures/hk-v2.3.0.sigstore.json");
    const HK_SIGNER: &str =
        "https://github.com/jdx/hk/.github/workflows/release.yml@refs/tags/v2.3.0";
    const HK_PIN: &str = "ps1_snirenkjwr7m5ozgcufameodnm";

    /// `packslip verify BUNDLE --issuer GITHUB_ISSUER` with the given
    /// --source-repository and --allow-other-repository.
    fn issuer_alone(source_repository: Option<&str>, allow_other_repository: bool) -> Verify {
        Verify {
            bundle: PathBuf::from("packslip.sigstore.json"),
            pubkey: None,
            identity: None,
            identity_prefix: None,
            issuer: Some(GITHUB_ISSUER.into()),
            source_repository: source_repository.map(str::to_string),
            pin: None,
            allow_other_repository,
            allow_unlogged: false,
            trusted_root: None,
            artifact: Vec::new(),
            json: false,
        }
    }

    /// `packslip verify BUNDLE` with no trust flags.
    fn no_flags() -> Verify {
        Verify {
            issuer: None,
            ..issuer_alone(None, false)
        }
    }

    /// The end of a refusal: how to accept a signer outside the repository.
    const REMEDY: &str = "accept a signer outside that repository, name it with --issuer and --identity, --identity-prefix, or --source-repository, and add --allow-other-repository";

    /// hk 2.3.0 verified under the policy --issuer alone builds, which pins
    /// no workflow: its signer, issuer, and source repository.
    fn hk_under_issuer_alone() -> (String, Option<String>, Option<SourceRepository>) {
        let policy = identity_policy(
            &None,
            &None,
            &Some(GITHUB_ISSUER.into()),
            "github.com/jdx/hk",
            sigstore::Error::NoPolicy,
        )
        .unwrap();
        assert_eq!(policy.identity_prefix, None);
        let root = sigstore::trusted_root(None).unwrap();
        let options = Options {
            require_log: true,
            trusted_root: &root,
        };
        let verified = packslip::verify(HK, &Trust::Identity(&policy), options, &[]).unwrap();
        assert_eq!(verified.key_id, HK_SIGNER);
        let source = sigstore::source_repository(HK).unwrap();
        (verified.key_id, verified.issuer, source)
    }

    #[test]
    fn issuer_alone_accepts_only_the_forge_projects_repository() {
        let (signer, issuer, source) = hk_under_issuer_alone();
        let check = |project: &str| {
            issuer_alone(None, false).check_signer(
                project,
                &signer,
                issuer.as_deref(),
                source.as_ref(),
                None,
            )
        };
        check("github.com/jdx/hk").unwrap();
        check("github.com/jdx/hk/tool").unwrap();

        // The same signature on a statement that names another project, as
        // any GitHub repository's workflow can sign one.
        let err = check("github.com/jdx/mise").unwrap_err();
        assert_eq!(
            err,
            format!(
                "github.com/jdx/mise must be signed from its repository https://github.com/jdx/mise, but {HK_SIGNER} signed it from https://github.com/jdx/hk. --issuer narrows what the project's name requires and does not replace it; to {REMEDY}"
            )
        );

        // A project on the other forge has another issuer as well.
        let err = check("gitlab.com/jdx/hk").unwrap_err();
        assert!(
            err.starts_with(&format!(
                "gitlab.com/jdx/hk must be signed from its repository through https://gitlab.com, but {HK_SIGNER} signed it through {GITHUB_ISSUER}. "
            )),
            "{err}"
        );
    }

    #[test]
    fn without_flags_another_repositorys_certificate_is_refused() {
        // `packslip verify BUNDLE` and `packslip pin BUNDLE` with no trust
        // flags verify under the forge's issuer alone, which names no
        // workflow, so hk's bundle verifies under the policy derived for
        // github.com/jdx/mise as it would for a statement naming mise. Only
        // the certificate's source repository can refuse it.
        let policy = identity_policy(
            &None,
            &None,
            &None,
            "github.com/jdx/mise",
            sigstore::Error::NoPolicy,
        )
        .unwrap();
        assert_eq!(
            policy,
            Policy {
                issuer: Some(GITHUB_ISSUER.into()),
                identity: None,
                identity_prefix: None,
            }
        );
        let root = sigstore::trusted_root(None).unwrap();
        let options = Options {
            require_log: true,
            trusted_root: &root,
        };
        let verified = packslip::verify(HK, &Trust::Identity(&policy), options, &[]).unwrap();
        let source = sigstore::source_repository(HK).unwrap();
        let (signer, issuer) = (verified.key_id.as_str(), verified.issuer.as_deref());

        let no_flags = Verify {
            issuer: None,
            ..issuer_alone(None, false)
        };
        no_flags
            .check_signer("github.com/jdx/hk", signer, issuer, source.as_ref(), None)
            .unwrap();
        let err = no_flags
            .check_signer("github.com/jdx/mise", signer, issuer, source.as_ref(), None)
            .unwrap_err();
        assert!(
            err.starts_with(&format!(
                "github.com/jdx/mise must be signed from its repository https://github.com/jdx/mise, but {HK_SIGNER} signed it from https://github.com/jdx/hk. "
            )),
            "{err}"
        );

        assert_eq!(
            signer_fingerprint("github.com/jdx/hk", signer, issuer, source.as_ref())
                .unwrap()
                .to_string(),
            HK_PIN
        );
        let err =
            signer_fingerprint("github.com/jdx/mise", signer, issuer, source.as_ref()).unwrap_err();
        assert_eq!(
            err,
            "the certificate's source repository is https://github.com/jdx/hk, not https://github.com/jdx/mise"
        );
    }

    #[test]
    fn allow_other_repository_lifts_only_the_projects_repository() {
        let (signer, issuer, source) = hk_under_issuer_alone();
        let check = |verify: Verify, pin: Option<&str>| {
            let pin: Option<Fingerprint> = pin.map(|p| p.parse().unwrap());
            verify.check_signer(
                "github.com/jdx/mise",
                &signer,
                issuer.as_deref(),
                source.as_ref(),
                pin.as_ref(),
            )
        };
        check(issuer_alone(None, true), None).unwrap();
        check(issuer_alone(Some("https://github.com/jdx/hk"), true), None).unwrap();
        check(issuer_alone(None, true), Some(HK_PIN)).unwrap();

        // The flags that name the signer still apply.
        let err = check(
            issuer_alone(Some("https://github.com/jdx/mise"), true),
            None,
        )
        .unwrap_err();
        assert_eq!(
            err,
            "the certificate's source repository is https://github.com/jdx/hk, expected https://github.com/jdx/mise"
        );
        let err = check(
            issuer_alone(None, true),
            Some("ps1_kwhjac5qpc45qetfh6ppwisi6a"),
        )
        .unwrap_err();
        assert!(
            err.contains("but the pin is ps1_kwhjac5qpc45qetfh6ppwisi6a"),
            "{err}"
        );

        // Without the opt-out, neither flag accepts another repository, and
        // the refusal names the flags that were passed.
        let err = check(issuer_alone(Some("https://github.com/jdx/hk"), false), None).unwrap_err();
        assert!(
            err.ends_with(&format!(
                ". --issuer and --source-repository narrow what the project's name requires and do not replace it; to {REMEDY}"
            )),
            "{err}"
        );
        let pinned = |source_repository| Verify {
            pin: Some(HK_PIN.into()),
            ..issuer_alone(source_repository, false)
        };
        let err = check(pinned(None), Some(HK_PIN)).unwrap_err();
        assert!(
            err.ends_with(&format!(
                ". --issuer and --pin narrow what the project's name requires and do not replace it; to {REMEDY}"
            )),
            "{err}"
        );
        let err = check(pinned(Some("https://github.com/jdx/hk")), Some(HK_PIN)).unwrap_err();
        assert!(
            err.ends_with(&format!(
                ". --issuer, --source-repository, and --pin narrow what the project's name requires and do not replace it; to {REMEDY}"
            )),
            "{err}"
        );
    }

    #[test]
    fn a_reusable_workflow_signs_for_the_repository_whose_run_called_it() {
        let shared = "https://github.com/suzuki-shunsuke/go-release-workflow/.github/workflows/release.yaml@refs/heads/main";
        let caller = SourceRepository::new("https://github.com/suzuki-shunsuke/mkghtag");
        let check = |project: &str, signer: &str, source: Option<&SourceRepository>| {
            issuer_alone(None, false).check_signer(
                project,
                signer,
                Some(GITHUB_ISSUER),
                source,
                None,
            )
        };
        check("github.com/suzuki-shunsuke/mkghtag", shared, Some(&caller)).unwrap();
        // --source-repository names the same repository.
        issuer_alone(Some("https://github.com/suzuki-shunsuke/mkghtag"), false)
            .check_signer(
                "github.com/suzuki-shunsuke/mkghtag",
                shared,
                Some(GITHUB_ISSUER),
                Some(&caller),
                None,
            )
            .unwrap();

        // Another repository's run is refused, even through a workflow of
        // the project's own.
        let own = "https://github.com/jdx/hk/.github/workflows/release.yml@refs/heads/main";
        let elsewhere = SourceRepository::new("https://github.com/someone/else");
        let err = check("github.com/jdx/hk", own, Some(&elsewhere)).unwrap_err();
        assert!(
            err.starts_with(&format!(
                "github.com/jdx/hk must be signed from its repository https://github.com/jdx/hk, but {own} signed it from https://github.com/someone/else. "
            )),
            "{err}"
        );
        // So is verify without flags, whose derived prefix the signer
        // matches; the refusal then names no flags.
        let err = no_flags()
            .check_signer(
                "github.com/jdx/hk",
                own,
                Some(GITHUB_ISSUER),
                Some(&elsewhere),
                None,
            )
            .unwrap_err();
        assert_eq!(
            err,
            format!(
                "github.com/jdx/hk must be signed from its repository https://github.com/jdx/hk, but {own} signed it from https://github.com/someone/else. To {REMEDY}"
            )
        );

        // A certificate that records no repository leaves only the signer,
        // which must then be a workflow of the project.
        let err = check("github.com/suzuki-shunsuke/mkghtag", shared, None).unwrap_err();
        assert!(
            err.starts_with(&format!(
                "github.com/suzuki-shunsuke/mkghtag must be signed from its repository https://github.com/suzuki-shunsuke/mkghtag, but {shared} is not one of its workflows. "
            )),
            "{err}"
        );
    }

    #[test]
    fn a_project_on_another_host_is_held_to_the_flags_alone() {
        let (signer, issuer, source) = hk_under_issuer_alone();
        for project in ["hk.jdx.dev", "example.com/tools/hk"] {
            issuer_alone(None, false)
                .check_signer(project, &signer, issuer.as_deref(), source.as_ref(), None)
                .unwrap();
        }
    }

    #[test]
    fn without_flags_a_forge_project_is_verified_under_its_issuer_alone() {
        // The workflow is left to `check_signer`, which binds the release to
        // the project through the certificate's source repository, as
        // install does.
        let derived = |project: &str| {
            identity_policy(&None, &None, &None, project, sigstore::Error::NoPolicy)
        };
        let issuer_alone = |issuer: &str| Policy {
            issuer: Some(issuer.into()),
            identity: None,
            identity_prefix: None,
        };
        for project in ["github.com/jdx/hk", "github.com/oxc-project/oxc/oxlint"] {
            assert_eq!(derived(project).unwrap(), issuer_alone(GITHUB_ISSUER));
        }
        assert_eq!(
            derived("gitlab.com/group/sub/tool").unwrap(),
            issuer_alone(packslip::sigstore::GITLAB_ISSUER)
        );
        // The names that were not forge projects before still are not.
        for project in ["hk.jdx.dev", "github.com/jdx", "gitlab.com/group"] {
            let err = derived(project).unwrap_err().to_string();
            assert!(
                err.contains("no identity to verify against"),
                "{project}: {err}"
            );
        }
    }
}

#[cfg(all(test, feature = "install-cli"))]
mod install_tests {
    use std::collections::BTreeMap;
    use std::path::PathBuf;

    use packslip::install::Report;
    use packslip::install_fs::{Entry, History, Receipt};

    fn printed(pin: Option<&str>) -> (String, String) {
        let tree = PathBuf::from("/installs/hk");
        let command = PathBuf::from("/bin/hk");
        let report = Report {
            project: "github.com/jdx/hk".into(),
            receipt: Receipt {
                schema: 1,
                project: "github.com/jdx/hk".into(),
                version: "1.2.3".into(),
                tree: tree.clone(),
                exports: BTreeMap::from([(command, Entry::Link(tree.join("hk")))]),
                history: History::default(),
            },
            pin: pin.map(Into::into),
            warnings: vec!["/bin is absent from PATH".into()],
        };
        let (mut out, mut err) = (Vec::new(), Vec::new());
        super::print_install_report(report, &mut out, &mut err).unwrap();
        (
            String::from_utf8(out).unwrap(),
            String::from_utf8(err).unwrap(),
        )
    }

    #[test]
    fn install_prints_the_signer_fingerprint_of_a_keyless_release() {
        let (out, err) = printed(Some("ps1_snirenkjwr7m5ozgcufameodnm"));
        assert_eq!(
            out,
            "Installed github.com/jdx/hk 1.2.3 at /installs/hk\n\
             Signer fingerprint: ps1_snirenkjwr7m5ozgcufameodnm\n\
             Command: /bin/hk\n"
        );
        assert_eq!(err, "warning: /bin is absent from PATH\n");

        // A key-signed release has no fingerprint to print.
        let (out, _) = printed(None);
        assert_eq!(
            out,
            "Installed github.com/jdx/hk 1.2.3 at /installs/hk\nCommand: /bin/hk\n"
        );
    }
}