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
//! Creating the statements: a release from its artifact files, and a
//! release list from released packslips. Signing is `sigstore::sign`.

use std::path::Path;

use crate::model::{
    Artifact, Attestor, Bin, Digest, Envelope, Evidence, Extensions, Identity, InvalidDocument,
    PREDICATE_TYPE, Predicate, RELEASES_PREDICATE_TYPE, ReleaseList, ReleaseListStatement,
    ReleaseRef, RequiredBin, Requires, Resource, STATEMENT_TYPE, Source, Statement, Subject,
};

/// What `create` needs.
pub struct Request<'a> {
    pub project: &'a str,
    pub version: &'a str,
    /// RFC 3339, with any offset; the statement records the same instant in
    /// UTC. Defaults to now. An instant before year 0 in UTC is refused as
    /// [`InvalidDocument::Timestamp`], because RFC 3339 cannot write it.
    pub published_at: Option<&'a str>,
    pub source: Option<Source>,
    pub artifacts: Vec<ArtifactInput<'a>>,
    /// Completions, man pages, CLI specs, skills, desktop entries, icons,
    /// app bundles. An `asset` source names one of `assets` by file name.
    pub resources: Vec<Resource>,
    /// Separate release files that resources come from, digested into
    /// `subject` like artifacts.
    pub assets: Vec<AssetInput<'a>>,
    /// Prepended to artifact and asset names for their download URL, when
    /// given and the file has no URL of its own.
    pub url_base: Option<&'a str>,
    pub notes_url: Option<&'a str>,
    /// Release-level extensions, keyed by who defines them.
    pub extensions: Extensions,
    /// Who will sign the document.
    pub identity: Identity,
    pub attested_by: Attestor,
    pub evidence: Vec<Evidence>,
    /// Also record sha512 digests.
    pub sha512: bool,
    /// Commands the executables need on PATH, recorded on every artifact
    /// that has executables.
    pub requires_bin: Vec<RequiredBin>,
    /// Open the artifacts and record the shared libraries their
    /// executables load from the host as `requires.libs`.
    pub read_executables: bool,
}

impl<'a> Request<'a> {
    /// A vendor-attested request with nothing optional set.
    pub fn new(project: &'a str, version: &'a str, identity: Identity) -> Request<'a> {
        Request {
            project,
            version,
            published_at: None,
            source: None,
            artifacts: Vec::new(),
            resources: Vec::new(),
            assets: Vec::new(),
            url_base: None,
            notes_url: None,
            extensions: Extensions::new(),
            identity,
            attested_by: Attestor::Vendor,
            evidence: Vec::new(),
            sha512: true,
            requires_bin: Vec::new(),
            read_executables: true,
        }
    }
}

/// One artifact file, with optional overrides for what the name implies.
pub struct ArtifactInput<'a> {
    pub path: &'a Path,
    pub os: Option<&'a str>,
    /// [`ANY`] for a build that runs on every architecture of its OS.
    /// Without one, the name must say, unless the OS is macOS or Windows.
    pub arch: Option<&'a str>,
    /// [`ANY`] for a build that loads no C library from the host.
    /// Without one, the name says, or the executables do.
    pub libc: Option<&'a str>,
    /// Runs on any host: `os`, `arch`, and `libc` are left out whatever
    /// the file name says.
    pub portable: bool,
    pub variant: Option<String>,
    /// The download URL, when it is not `url_base/name`.
    pub url: Option<String>,
    /// The format, when it is not what the file name implies: `raw` for
    /// an `.exe` that is the program rather than an installer.
    pub format: Option<String>,
    /// Executables inside the artifact. On Windows a path without an
    /// extension gets `.exe`; the name never has one. For a bare
    /// executable (`raw`, `gz`, `xz`, `zst`, `bz2`), an entry that is a
    /// plain name becomes the artifact's own file under that name.
    pub bin: Vec<Bin>,
    pub requires: Option<Requires>,
    pub provenance: Vec<String>,
    /// Artifact-level extensions, keyed by who defines them.
    pub extensions: Extensions,
}

impl<'a> ArtifactInput<'a> {
    pub fn new(path: &'a Path) -> ArtifactInput<'a> {
        ArtifactInput {
            path,
            os: None,
            arch: None,
            libc: None,
            portable: false,
            variant: None,
            url: None,
            format: None,
            bin: Vec::new(),
            requires: None,
            provenance: Vec::new(),
            extensions: Extensions::new(),
        }
    }
}

/// A separate release file a resource comes from.
pub struct AssetInput<'a> {
    pub path: &'a Path,
    /// The download URL, when it is not `url_base/name`.
    pub url: Option<String>,
}

/// The statement, ready to sign.
#[derive(Debug)]
pub struct Created {
    /// The payload bytes that get signed.
    pub document: Vec<u8>,
    pub statement: Statement,
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("{path}: {source}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("{0}")]
    Invalid(#[from] crate::model::InvalidDocument),
    #[error("{0}")]
    Executables(#[from] crate::linkage::Error),
    #[error(
        "artifact {artifact:?} says its executables need libraries [{given}], but they load [{read}]; drop the list and let create read it"
    )]
    LibsMismatch {
        artifact: String,
        given: String,
        read: String,
    },
    #[error("{0}")]
    Archive(#[from] crate::archive::Error),
    #[error("{path}: not a packslip bundle: {why}")]
    NotAPackslip { path: String, why: String },
    #[error(
        "asset {path} is named {name:?}, but a different file with that name was already given"
    )]
    AssetCollision { name: String, path: String },
    #[error(
        "artifacts {a:?} and {b:?} both describe {platform}; give one a variant so consumers can tell them apart"
    )]
    Ambiguous {
        a: String,
        b: String,
        platform: String,
    },
    #[error(
        "artifact {name:?}: nothing in the name says what kind of file it is; give it a format, or leave it out of the artifacts if it is not one"
    )]
    UnknownFormat { name: String },
    #[error(
        "artifact {name:?} is for {os}, but nothing in the name says which architecture; give it as PATH:{os}/x86_64 or arch = \"x86_64\" in the manifest, with any in place of x86_64 if the build runs on every architecture"
    )]
    UnknownArch { name: String, os: String },
}

/// The `arch` or `libc` a vendor gives for a build that runs on every
/// architecture or C library: the field is left out.
pub const ANY: &str = "any";

/// The `(os, arch, libc, format)` a file name implies.
pub type Platform = (
    Option<&'static str>,
    Option<&'static str>,
    Option<&'static str>,
    Option<&'static str>,
);

/// Infer `(os, arch, libc, format)` from a release file name.
///
/// `libc` is only what the name says (`musl`, or `gnu` in a triple such as
/// `x86_64-unknown-linux-gnu`); [`create`] reads the rest from the
/// executables. An architecture the vocabulary lacks, such as goreleaser's
/// `mips64le`, is given as Rust's triples spell it (`mips64el`).
///
/// A `.exe` is taken for the program itself (`raw`) unless its name says
/// `setup`, `install`, or `installer`, which makes it an `exe` installer;
/// a manifest or `--format` settles any case the name leaves open.
pub fn infer_platform(name: &str) -> Platform {
    let lower = name.to_ascii_lowercase();
    // Android and iOS are read from whole words, since `helios` is not
    // iOS and `android-tools` is not an Android build. Their Rust triples
    // also say `linux` and `apple` (`aarch64-linux-android`,
    // `aarch64-apple-ios`), so the word wins when it follows that one, or
    // when the name says nothing else.
    let tokens: Vec<&str> = lower
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|t| !t.is_empty())
        .collect();
    let has = |word: &str| tokens.contains(&word);
    let follows = |first: &str, second: &str| {
        tokens
            .windows(2)
            .any(|pair| pair[0] == first && pair[1] == second)
    };
    let android = |word: &str| word == "android" || word == "androideabi";
    let os = if tokens
        .windows(2)
        .any(|pair| pair[0] == "linux" && android(pair[1]))
        || (tokens.iter().any(|t| android(t)) && !has("linux"))
    {
        Some("android")
    } else if follows("apple", "ios")
        || (has("ios") && !has("apple") && !has("darwin") && !has("macos"))
    {
        Some("ios")
    } else if lower.contains("linux")
        || lower.ends_with(".deb")
        || lower.ends_with(".rpm")
        || lower.ends_with(".appimage")
    {
        Some("linux")
    } else if lower.contains("darwin")
        || lower.contains("macos")
        || lower.contains("apple")
        || lower.ends_with(".dmg")
        || lower.ends_with(".pkg")
    {
        Some("darwin")
    } else if lower.contains("windows")
        || lower.contains("win64")
        || lower.contains("win32")
        || lower.ends_with(".exe")
        || lower.ends_with(".exe.gz")
        || lower.ends_with(".exe.zip")
        || lower.ends_with(".msi")
        || lower.ends_with(".msix")
    {
        Some("windows")
    } else if lower.contains("freebsd") {
        Some("freebsd")
    } else if lower.contains("netbsd") {
        Some("netbsd")
    } else if lower.contains("openbsd") {
        Some("openbsd")
    } else if lower.contains("illumos") {
        Some("illumos")
    } else {
        None
    };
    // A number stands for an architecture only as a word of its own, not
    // as a part of a dotted version: goreleaser's `386` is i686 in
    // `tool_1.2.0_linux_386.tar.gz`, but nothing in `tool-1.386.0.tar.gz`.
    let bytes = lower.as_bytes();
    let digit_at = |i: Option<usize>| i.and_then(|i| bytes.get(i)).is_some_and(u8::is_ascii_digit);
    let word = |w: &str| {
        lower.match_indices(w).any(|(start, _)| {
            let end = start + w.len();
            let before = start.checked_sub(1).map(|i| bytes[i]);
            let after = bytes.get(end).copied();
            let bounded = |c: Option<u8>| !c.is_some_and(|c| c.is_ascii_alphanumeric());
            let versioned = w.bytes().all(|b| b.is_ascii_digit())
                && ((before == Some(b'.') && digit_at(start.checked_sub(2)))
                    || (after == Some(b'.') && digit_at(Some(end + 1))));
            bounded(before) && bounded(after) && !versioned
        })
    };
    let arch = if lower.contains("x86_64")
        || lower.contains("x86-64")
        || lower.contains("x64")
        || lower.contains("amd64")
    {
        Some("x86_64")
    } else if lower.contains("aarch64") || lower.contains("arm64") {
        Some("aarch64")
    } else if lower.contains("armv7") || lower.contains("armhf") {
        Some("armv7")
    } else if lower.contains("armv6") {
        Some("armv6")
    } else if lower.contains("riscv64") {
        Some("riscv64")
    } else if lower.contains("ppc64le")
        || lower.contains("ppc64el")
        || lower.contains("powerpc64le")
    {
        Some("powerpc64le")
    } else if lower.contains("s390x") {
        Some("s390x")
    } else if lower.contains("loongarch64") || lower.contains("loong64") {
        Some("loongarch64")
    } else if lower.contains("i686")
        || lower.contains("i386")
        || lower.contains("x86")
        || word("ia32")
        || word("386")
    {
        Some("i686")
    } else if word("arm") {
        // Plain `arm` is ARMv6 in both of the conventions that write it:
        // goreleaser builds `GOARCH=arm` with `GOARM=6` unless told
        // otherwise, and Rust's `arm-unknown-linux-*` targets are ARMv6.
        Some("armv6")
    } else if word("mips64el") || word("mips64le") {
        // Architectures outside the vocabulary, spelled as Rust's triples
        // spell them, so no consumer takes them for another one.
        // goreleaser writes the little-endian ones `mipsle`, `mips64le`.
        Some("mips64el")
    } else if word("mips64") {
        Some("mips64")
    } else if word("mipsel") || word("mipsle") {
        Some("mipsel")
    } else if word("mips") {
        Some("mips")
    } else if word("ppc64") || word("powerpc64") {
        Some("powerpc64")
    } else if word("win64") {
        // Only when nothing else in the name gives the architecture.
        Some("x86_64")
    } else {
        None
    };
    // Only what the name says. `create` falls back to what the
    // executables load, then to `gnu`, for a Linux build.
    let libc = if !matches!(os, None | Some("linux")) {
        None
    } else if lower.contains("musl") {
        Some("musl")
    } else if tokens.iter().any(|t| {
        *t == "gnu"
            || t.starts_with("gnueabi")
            || t.starts_with("gnuabi")
            || t.starts_with("gnux32")
            || t.starts_with("glibc")
    }) {
        Some("gnu")
    } else {
        None
    };
    // Compound suffixes first, so `.tar.gz` is not taken for `.gz`.
    let format = [
        "tar.xz", "tar.gz", "tar.zst", "tar.bz2", "tgz", "tar", "zip", "7z", "gz", "xz", "zst",
        "bz2", "deb", "rpm", "dmg", "pkg", "msix", "msi", "exe", "appimage",
    ]
    .into_iter()
    .find(|ext| lower.ends_with(&format!(".{ext}")))
    .map(|ext| match ext {
        "exe" if !(lower.contains("setup") || lower.contains("install")) => "raw",
        other => other,
    });
    (os, arch, libc, format)
}

/// What the vendor gave for `arch` or `libc`: `Some(None)` for `any`,
/// which leaves the field out because the build runs on every one.
fn given(value: Option<&str>) -> Option<Option<&str>> {
    value.map(|v| (v != ANY).then_some(v))
}

/// Whether a file name ends in something that reads as an extension: a
/// short alphanumeric tail after the last dot with a letter in it. A
/// dotted version leaves a tail of its own, so `tool-1.2.3-linux-x64` is
/// a bare executable rather than a file of type `3-linux-x64`, and
/// `tool-linux-x64-1.2.3` is not one of type `3`. Every documented format
/// clears the bar: the longest is `appimage`, and `7z` is the only one
/// that starts with a digit.
fn has_extension(name: &str) -> bool {
    name.rsplit_once('.').is_some_and(|(_, ext)| {
        ext.len() <= 9
            && ext.chars().all(|c| c.is_ascii_alphanumeric())
            && ext.chars().any(|c| c.is_ascii_alphabetic())
    })
}

/// Add `.exe` to a Windows executable name that has no extension.
fn windows_exe(value: &str) -> String {
    let last = value.rsplit('/').next().unwrap_or(value);
    if last.contains('.') {
        value.to_string()
    } else {
        format!("{value}.exe")
    }
}

/// The instant `text` names, to be written in UTC with `Z` as publishers
/// write every timestamp. Any spelling the validator reads is accepted,
/// such as an offset of `+02:00`. An instant before year 0 is refused
/// because RFC 3339 cannot spell it in UTC.
fn utc_timestamp(field: &'static str, text: &str) -> Result<jiff::Timestamp, InvalidDocument> {
    // 0000-01-01T00:00:00Z. Compare whole instants: before the epoch the
    // fraction carries the sign, so `as_second` alone would let through an
    // instant a fraction of a second before year 0.
    const YEAR_ZERO: jiff::Timestamp = jiff::Timestamp::constant(-62_167_219_200, 0);
    text.parse::<jiff::Timestamp>()
        .ok()
        .filter(|timestamp| *timestamp >= YEAR_ZERO)
        .ok_or_else(|| InvalidDocument::Timestamp {
            field,
            value: text.to_string(),
        })
}

/// Build and validate the release statement.
pub fn create(request: &Request<'_>) -> Result<Created, Error> {
    let file_name = |path: &Path| {
        path.file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default()
            .to_string()
    };
    // A file named as an asset is an asset, not a platform artifact, even
    // when an artifact glob such as `dist/*` swept it up as well.
    let asset_names: Vec<String> = request.assets.iter().map(|a| file_name(a.path)).collect();
    let mut subject = Vec::new();
    let mut artifacts: Vec<Artifact> = Vec::new();
    for input in &request.artifacts {
        let name = file_name(input.path);
        if asset_names.contains(&name) {
            continue;
        }
        let digests = crate::digest_file_all(input.path).map_err(|source| Error::Io {
            path: input.path.display().to_string(),
            source,
        })?;
        let (inferred_os, inferred_arch, inferred_libc, inferred_format) = infer_platform(&name);
        let os = if input.portable {
            None
        } else {
            input.os.or(inferred_os)
        };
        let given_arch = given(input.arch);
        let given_libc = given(input.libc);
        let arch = if input.portable {
            None
        } else {
            given_arch.unwrap_or(inferred_arch)
        };
        // A file with no archive or installer extension is the executable
        // itself, when the name says which host it is for or the vendor
        // said it runs anywhere. The tail after the last dot only counts
        // as an extension when it looks like one: a released binary is
        // often named for a dotted version, and `mise-v2026.9.1-linux-x64`
        // ends in `1-linux-x64`, which is a platform, not a format.
        let format = input
            .format
            .clone()
            .or_else(|| inferred_format.map(str::to_string))
            .or_else(|| {
                (!has_extension(&name) && (os.is_some() || input.portable))
                    .then(|| "raw".to_string())
            });
        // An artifact with no format is dead weight: rule 3 of Selecting
        // an artifact keeps a consumer from ever choosing one, so it
        // would ship a digest and a platform that nothing can act on.
        // A library or a header swept up by a glob lands here.
        let Some(format) = format else {
            return Err(Error::UnknownFormat { name });
        };
        let format = Some(format);
        // An artifact with no architecture fits every host of its OS, so
        // a name that only fails to say one would hand an x86 build to an
        // ARM host. macOS and Windows are the exceptions: a build named for
        // no architecture there is by convention universal or x86, and
        // both run x86 builds on ARM. A package its own format declares
        // architecture-independent, `.noarch.rpm` or `_all.deb`, is another:
        // the package manager already installs it on every architecture.
        let lower = name.to_ascii_lowercase();
        let arch_independent_package = match format.as_deref() {
            Some("rpm") => lower.ends_with(".noarch.rpm"),
            Some("deb") => lower.ends_with("_all.deb"),
            _ => false,
        };
        if !input.portable
            && arch.is_none()
            && given_arch.is_none()
            && !arch_independent_package
            && let Some(os) = os
            && !matches!(os, "darwin" | "windows")
        {
            return Err(Error::UnknownArch {
                name,
                os: os.to_string(),
            });
        }
        let bare = format
            .as_deref()
            .filter(|f| crate::model::is_bare_format(f))
            .map(|f| crate::model::bare_file_name(&name, f).to_string());
        let windows = os == Some("windows");
        // Inside an archive the executables are where they really are: a
        // plain `--bin tool` is looked up, and a given path is checked.
        // An archive that cannot be read is taken at the vendor's word.
        let listed = match format.as_deref() {
            Some(f) if crate::archive::can_list(f) && !input.bin.is_empty() => {
                match crate::archive::resolve_bins(input.path, f, &input.bin, windows) {
                    Ok(bins) => Some(bins),
                    Err(crate::archive::Error::Undecodable { .. }) => None,
                    Err(err) => return Err(Error::Archive(err)),
                }
            }
            _ => None,
        };
        let verified = listed.is_some();
        let bin: Vec<Bin> = listed
            .unwrap_or_else(|| input.bin.clone())
            .into_iter()
            .map(|b| {
                // `--bin tool` names the program; for a bare executable the
                // program is the artifact itself, under that name.
                let (b, path_is_real) = match &bare {
                    Some(file) if !b.path.contains('/') => (Bin::named(file, &b.name), true),
                    _ => (b, verified),
                };
                if windows {
                    // The path takes `.exe` only when nothing confirmed the
                    // file: a path read from the archive or the artifact's own
                    // name is already exact. The name is the command as typed
                    // and never carries it.
                    let path = if path_is_real {
                        b.path
                    } else {
                        windows_exe(&b.path)
                    };
                    Bin::named(path, b.name)
                } else {
                    b
                }
            })
            .collect();
        let url = input.url.clone().or_else(|| {
            request
                .url_base
                .map(|base| format!("{}/{name}", base.trim_end_matches('/')))
        });
        // What the executables load is read from them, so the document
        // says what the bytes say. An artifact `create` cannot open, or
        // an executable that is a script, records nothing.
        let executables = if request.read_executables {
            crate::linkage::read_executables(input.path, format.as_deref(), &bin)?
        } else {
            None
        };
        let mut requires = input.requires.clone().unwrap_or_default();
        if !bin.is_empty() {
            for required in &request.requires_bin {
                if !requires.bin.contains(required) {
                    requires.bin.push(required.clone());
                }
            }
            // A list the manifest gives must agree with what is read.
            if let Some(read) = executables
                .as_ref()
                .and_then(crate::linkage::host_libraries)
            {
                // The read list is sorted; a given one may be in any order.
                let given_sorted = requires.libs.as_ref().map(|given| {
                    let mut sorted = given.clone();
                    sorted.sort();
                    sorted.dedup();
                    sorted
                });
                match (&requires.libs, given_sorted) {
                    (Some(given), Some(sorted)) if sorted != read => {
                        return Err(Error::LibsMismatch {
                            artifact: name,
                            given: given.join(", "),
                            read: read.join(", "),
                        });
                    }
                    _ => requires.libs = Some(read),
                }
            }
        }
        // A Linux build's C library is what the vendor or the name says,
        // else what the executables load: none for a static build, which
        // runs on a musl host as well as a glibc one. Only when neither
        // can be told is it taken for `gnu`, the common case.
        let libc = if input.portable {
            None
        } else if let Some(libc) = given_libc {
            libc
        } else if os != Some("linux") {
            None
        } else if inferred_libc.is_some() {
            inferred_libc
        } else {
            match executables.as_ref().and_then(crate::linkage::elf_libc) {
                Some(read) => read.value(),
                None => Some("gnu"),
            }
        };
        let artifact = Artifact {
            url,
            name: name.clone(),
            os: os.map(str::to_string),
            arch: arch.map(str::to_string),
            libc: libc.map(str::to_string),
            variant: input.variant.clone(),
            size: digests.size,
            format,
            bin,
            requires: (!requires.is_empty()).then_some(requires),
            provenance: input.provenance.clone(),
            extensions: input.extensions.clone(),
        };
        // Anything with a format is selectable, so two artifacts that agree
        // on platform, variant, and format leave a consumer nothing to
        // choose by, portable ones included.
        if artifact.format.is_some()
            && let Some(other) = artifacts.iter().find(|a| {
                a.os == artifact.os
                    && a.arch == artifact.arch
                    && a.libc == artifact.libc
                    && a.format == artifact.format
                    && a.variant == artifact.variant
            })
        {
            return Err(Error::Ambiguous {
                a: other.name.clone(),
                b: artifact.name.clone(),
                platform: [
                    artifact.os.as_deref(),
                    artifact.arch.as_deref(),
                    artifact.libc.as_deref(),
                    artifact.format.as_deref(),
                    artifact.variant.as_deref(),
                ]
                .into_iter()
                .flatten()
                .collect::<Vec<_>>()
                .join("/"),
            });
        }
        subject.push(Subject {
            name,
            digest: Digest {
                sha256: digests.sha256,
                sha512: request.sha512.then_some(digests.sha512),
            },
        });
        artifacts.push(artifact);
    }
    let mut asset_urls = std::collections::BTreeMap::new();
    let mut asset_digests: std::collections::BTreeMap<String, String> =
        std::collections::BTreeMap::new();
    for asset in &request.assets {
        let name = file_name(asset.path);
        let digests = crate::digest_file_all(asset.path).map_err(|source| Error::Io {
            path: asset.path.display().to_string(),
            source,
        })?;
        // The same file given twice is one asset; two different files that
        // share a name cannot both be the subject that name would carry.
        match asset_digests.get(&name) {
            Some(seen) if *seen == digests.sha256 => continue,
            Some(_) => {
                return Err(Error::AssetCollision {
                    name,
                    path: asset.path.display().to_string(),
                });
            }
            None => {
                asset_digests.insert(name.clone(), digests.sha256.clone());
            }
        }
        let url = asset.url.clone().or_else(|| {
            request
                .url_base
                .map(|base| format!("{}/{name}", base.trim_end_matches('/')))
        });
        asset_urls.insert(name.clone(), url);
        subject.push(Subject {
            name,
            digest: Digest {
                sha256: digests.sha256,
                sha512: request.sha512.then_some(digests.sha512),
            },
        });
    }
    let resources = request
        .resources
        .iter()
        .map(|resource| {
            let mut resource = resource.clone();
            if resource.url.is_none()
                && let Some(url) = resource.asset.as_ref().and_then(|a| asset_urls.get(a))
            {
                resource.url = url.clone();
            }
            resource
        })
        .collect();
    let published_at = match request.published_at {
        Some(text) => utc_timestamp("published_at", text)?,
        None => jiff::Timestamp::now(),
    }
    .to_string();
    let statement = Statement {
        kind: STATEMENT_TYPE.into(),
        subject,
        predicate_type: PREDICATE_TYPE.into(),
        predicate: Predicate {
            project: request.project.into(),
            version: request.version.into(),
            published_at,
            source: request.source.clone(),
            artifacts,
            resources,
            identity: request.identity.clone(),
            attested_by: request.attested_by,
            evidence: request.evidence.clone(),
            notes_url: request.notes_url.map(str::to_string),
            extensions: request.extensions.clone(),
        },
    };
    statement.validate()?;
    let document = statement.canonical_bytes();
    Ok(Created {
        document,
        statement,
    })
}

/// One released packslip to list: where consumers fetch it, and the local
/// copy to digest and read the version from.
pub struct ListedRelease<'a> {
    pub url: &'a str,
    pub bundle_path: &'a Path,
    /// Withdrawn by the vendor, with the reason.
    pub yanked: Option<String>,
    pub security: bool,
    /// What the list's publisher checked about the release, when the
    /// publisher is not the vendor.
    pub evidence: Vec<Evidence>,
}

/// What `create_release_list` needs.
pub struct ListRequest<'a> {
    pub project: &'a str,
    /// RFC 3339, with any offset; the list records the same instant in UTC.
    /// Defaults to now. As with [`Request::published_at`], an instant before
    /// year 0 in UTC is refused, here and in each listed packslip.
    pub generated_at: Option<&'a str>,
    /// How long the list stays current.
    pub valid_for: std::time::Duration,
    pub sequence: u64,
    /// Exact listed version recommended for unconstrained latest requests.
    pub latest: Option<&'a str>,
    pub releases: Vec<ListedRelease<'a>>,
    pub identity: Identity,
}

/// The release list, ready to sign.
#[derive(Debug)]
pub struct CreatedList {
    pub document: Vec<u8>,
    pub statement: ReleaseListStatement,
}

/// Build and validate the release list from released bundles. The bundles
/// are read, not verified: the list's signer vouches for them.
pub fn create_release_list(request: &ListRequest<'_>) -> Result<CreatedList, Error> {
    let generated = match request.generated_at {
        Some(text) => utc_timestamp("generated_at", text)?,
        None => jiff::Timestamp::now(),
    };
    let expires = generated
        .checked_add(
            jiff::SignedDuration::try_from(request.valid_for)
                .map_err(|_| Error::Invalid(crate::model::InvalidDocument::Expiry))?,
        )
        .map_err(|_| Error::Invalid(crate::model::InvalidDocument::Expiry))?;
    let mut subject = Vec::new();
    let mut releases = Vec::new();
    for listed in &request.releases {
        let digests = crate::digest_file_all(listed.bundle_path).map_err(|source| Error::Io {
            path: listed.bundle_path.display().to_string(),
            source,
        })?;
        let text = std::fs::read_to_string(listed.bundle_path).map_err(|source| Error::Io {
            path: listed.bundle_path.display().to_string(),
            source,
        })?;
        let payload = crate::sigstore::peek_statement(&text).map_err(|e| Error::NotAPackslip {
            path: listed.bundle_path.display().to_string(),
            why: e.to_string(),
        })?;
        let statement: Statement =
            serde_json::from_slice(&payload).map_err(|e| Error::NotAPackslip {
                path: listed.bundle_path.display().to_string(),
                why: e.to_string(),
            })?;
        // A GitHub or GitLab repository's name matches in any case, as
        // consumers compare it.
        if !crate::forge::same_project(&statement.predicate.project, request.project) {
            return Err(Error::NotAPackslip {
                path: listed.bundle_path.display().to_string(),
                why: format!(
                    "it is for {}, the list is for {}",
                    statement.predicate.project, request.project
                ),
            });
        }
        // The packslip's instant, written in UTC even when the packslip
        // gave it with another offset.
        let published_at = utc_timestamp("published_at", &statement.predicate.published_at)
            .map_err(|e| Error::NotAPackslip {
                path: listed.bundle_path.display().to_string(),
                why: e.to_string(),
            })?;
        subject.push(Subject {
            name: listed.url.to_string(),
            digest: Digest {
                sha256: digests.sha256,
                sha512: Some(digests.sha512),
            },
        });
        releases.push(ReleaseRef {
            version: statement.predicate.version,
            tag: statement.predicate.source.and_then(|s| s.tag),
            published_at: published_at.to_string(),
            packslip: listed.url.to_string(),
            status: listed
                .yanked
                .is_some()
                .then_some(crate::model::ReleaseStatus::Yanked),
            status_reason: listed.yanked.clone(),
            security: listed.security,
            evidence: listed.evidence.clone(),
            extensions: Extensions::new(),
        });
    }
    // sigstore binds a signed statement to one of its subject digests, so
    // a list with no releases still needs a subject: one named `_`, the
    // in-toto name for none, with the digest of empty input.
    if subject.is_empty() {
        use sha2::Digest as _;
        subject.push(Subject {
            name: "_".into(),
            digest: Digest {
                sha256: hex::encode(sha2::Sha256::digest(b"")),
                sha512: None,
            },
        });
    }
    let statement = Envelope {
        kind: STATEMENT_TYPE.into(),
        subject,
        predicate_type: RELEASES_PREDICATE_TYPE.into(),
        predicate: ReleaseList {
            project: request.project.into(),
            generated_at: generated.to_string(),
            expires_at: expires.to_string(),
            sequence: request.sequence,
            latest: request.latest.map(str::to_owned),
            identity: request.identity.clone(),
            releases,
            extensions: Extensions::new(),
        },
    };
    statement.validate()?;
    let document = statement.canonical_bytes();
    Ok(CreatedList {
        document,
        statement,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::minisign::SecretKey;
    use crate::model::Scheme;
    use crate::sigstore::{Signer, Trust};

    fn key_identity(key: &SecretKey) -> Identity {
        Signer::Key {
            key: key.clone(),
            log: false,
        }
        .identity()
    }

    #[test]
    fn infers_platforms() {
        // The name gives a libc only when it says one; `create` reads the
        // rest from the executables.
        assert_eq!(
            infer_platform("mise-v2026.9.1-linux-x64.tar.xz"),
            (Some("linux"), Some("x86_64"), None, Some("tar.xz"))
        );
        assert_eq!(
            infer_platform("mise-v2026.9.1-linux-arm64-musl.tar.gz"),
            (Some("linux"), Some("aarch64"), Some("musl"), Some("tar.gz"))
        );
        assert_eq!(
            infer_platform("tool-macos-aarch64.zip"),
            (Some("darwin"), Some("aarch64"), None, Some("zip"))
        );
        // A .exe is the program unless its name says it installs.
        assert_eq!(
            infer_platform("tool-windows-x64.exe"),
            (Some("windows"), Some("x86_64"), None, Some("raw"))
        );
        assert_eq!(
            infer_platform("Tool-Setup-1.2.3.exe"),
            (Some("windows"), None, None, Some("exe"))
        );
        assert_eq!(
            infer_platform("tool-installer-x64.exe"),
            (Some("windows"), Some("x86_64"), None, Some("exe"))
        );
        // Single compressed executables, and a plain tar.
        assert_eq!(
            infer_platform("argo-linux-amd64.gz"),
            (Some("linux"), Some("x86_64"), None, Some("gz"))
        );
        assert_eq!(
            infer_platform("argo-windows-amd64.exe.gz"),
            (Some("windows"), Some("x86_64"), None, Some("gz"))
        );
        assert_eq!(
            infer_platform("restic_0.16.0_linux_arm64.bz2"),
            (Some("linux"), Some("aarch64"), None, Some("bz2"))
        );
        assert_eq!(
            infer_platform("tool-linux-x64.zst"),
            (Some("linux"), Some("x86_64"), None, Some("zst"))
        );
        assert_eq!(
            infer_platform("tool-linux-x64.xz"),
            (Some("linux"), Some("x86_64"), None, Some("xz"))
        );
        assert_eq!(
            infer_platform("mmctl_linux_amd64.tar"),
            (Some("linux"), Some("x86_64"), None, Some("tar"))
        );
        // Less common hosts and architectures.
        // Android and iOS triples also say linux and apple.
        assert_eq!(
            infer_platform("tool-aarch64-linux-android.tar.gz"),
            (Some("android"), Some("aarch64"), None, Some("tar.gz"))
        );
        assert_eq!(
            infer_platform("tool-aarch64-apple-ios.zip"),
            (Some("ios"), Some("aarch64"), None, Some("zip"))
        );
        assert_eq!(
            infer_platform("tool-android-arm64.tar.gz"),
            (Some("android"), Some("aarch64"), None, Some("tar.gz"))
        );
        assert_eq!(
            infer_platform("tool-armv7-linux-androideabi.tar.gz"),
            (Some("android"), Some("armv7"), None, Some("tar.gz"))
        );
        assert_eq!(
            infer_platform("tool-ios-arm64.zip"),
            (Some("ios"), Some("aarch64"), None, Some("zip"))
        );
        // Whole words only: a product name is not a platform.
        assert_eq!(
            infer_platform("helios-linux-amd64.tar.gz"),
            (Some("linux"), Some("x86_64"), None, Some("tar.gz"))
        );
        assert_eq!(
            infer_platform("android-tools_linux_amd64.tar.gz"),
            (Some("linux"), Some("x86_64"), None, Some("tar.gz"))
        );
        assert_eq!(
            infer_platform("studios-darwin-arm64.tar.gz"),
            (Some("darwin"), Some("aarch64"), None, Some("tar.gz"))
        );
        assert_eq!(
            infer_platform("tool-netbsd-i386.tar.gz"),
            (Some("netbsd"), Some("i686"), None, Some("tar.gz"))
        );
        assert_eq!(
            infer_platform("tool-linux-ppc64le.tar.gz"),
            (Some("linux"), Some("powerpc64le"), None, Some("tar.gz"))
        );
        assert_eq!(
            infer_platform("tool-linux-s390x.tar.gz"),
            (Some("linux"), Some("s390x"), None, Some("tar.gz"))
        );
        assert_eq!(
            infer_platform("tool-linux-armv6.tar.gz"),
            (Some("linux"), Some("armv6"), None, Some("tar.gz"))
        );
        assert_eq!(infer_platform("SHASUMS256.txt"), (None, None, None, None));
        assert_eq!(
            infer_platform("tool_amd64.deb"),
            (Some("linux"), Some("x86_64"), None, Some("deb"))
        );
        assert_eq!(
            infer_platform("Tool.dmg"),
            (Some("darwin"), None, None, Some("dmg"))
        );
        assert_eq!(
            infer_platform("Tool.msi"),
            (Some("windows"), None, None, Some("msi"))
        );
        assert_eq!(
            infer_platform("Tool-x64.msix"),
            (Some("windows"), Some("x86_64"), None, Some("msix"))
        );
        assert_eq!(
            infer_platform("LM-Studio-0.3.0-x64.AppImage"),
            (Some("linux"), Some("x86_64"), None, Some("appimage"))
        );
        assert_eq!(
            infer_platform("tool-linux-x86-64.tar.zst"),
            (Some("linux"), Some("x86_64"), None, Some("tar.zst"))
        );
        assert_eq!(
            infer_platform("tool-linux-x64.7z"),
            (Some("linux"), Some("x86_64"), None, Some("7z"))
        );
        assert_eq!(
            infer_platform("tool-x86_64-unknown-linux-gnu.tar.xz"),
            (Some("linux"), Some("x86_64"), Some("gnu"), Some("tar.xz"))
        );
        assert_eq!(
            infer_platform("tool-arm-unknown-linux-gnueabihf.tar.gz"),
            (Some("linux"), Some("armv6"), Some("gnu"), Some("tar.gz"))
        );
        assert_eq!(
            infer_platform("tool-x86_64-unknown-linux-musl.tar.gz"),
            (Some("linux"), Some("x86_64"), Some("musl"), Some("tar.gz"))
        );
        // libc is for Linux builds; a windows-gnu triple names none.
        assert_eq!(
            infer_platform("tool-x86_64-pc-windows-gnu.zip"),
            (Some("windows"), Some("x86_64"), None, Some("zip"))
        );
        // goreleaser's architecture names.
        for (name, arch) in [
            ("helmfile_1.8.0_linux_386.tar.gz", "i686"),
            ("tool_1.0.0_windows_386.zip", "i686"),
            ("tool-win32-ia32.zip", "i686"),
            ("tool_1.0.0_linux_arm.tar.gz", "armv6"),
            ("tool_1.0.0_linux_armv6.tar.gz", "armv6"),
            ("tool_1.0.0_linux_armv7.tar.gz", "armv7"),
            ("tool_1.0.0_linux_arm64.tar.gz", "aarch64"),
            ("tool_1.0.0_linux_ppc64le.tar.gz", "powerpc64le"),
            ("tool_1.0.0_linux_s390x.tar.gz", "s390x"),
            ("tool_1.0.0_linux_riscv64.tar.gz", "riscv64"),
            ("tool_1.0.0_linux_loong64.tar.gz", "loongarch64"),
            // Outside the vocabulary, as Rust's triples spell them.
            ("tool_1.0.0_linux_mips.tar.gz", "mips"),
            ("tool_1.0.0_linux_mips_softfloat.tar.gz", "mips"),
            ("tool_1.0.0_linux_mipsle.tar.gz", "mipsel"),
            ("tool_1.0.0_linux_mips64.tar.gz", "mips64"),
            ("tool_1.0.0_linux_mips64le_hardfloat.tar.gz", "mips64el"),
            ("tool-mips64el-unknown-linux-gnuabi64.tar.gz", "mips64el"),
            ("tool_1.0.0_linux_ppc64.tar.gz", "powerpc64"),
            ("tool-powerpc64-unknown-linux-gnu.tar.gz", "powerpc64"),
            ("ffmpeg-win64-gpl.zip", "x86_64"),
        ] {
            assert_eq!(infer_platform(name).1, Some(arch), "{name}");
        }
        // A number is an architecture only as a word of its own, never as
        // part of a version.
        for name in [
            "tool-1.386.0-linux.tar.gz",
            "tool-386.1.0-linux.tar.gz",
            "tool-v2.0.386-linux.tar.gz",
            "tool386-linux.tar.gz",
            "armory-linux.tar.gz",
            "tool-linux-armel.tar.gz",
            "tool-linux.tar.gz",
        ] {
            assert_eq!(infer_platform(name).1, None, "{name}");
        }
    }

    #[test]
    fn libc_is_read_from_the_executables() {
        let dir = tempfile::tempdir().unwrap();
        let fixture = |name: &str| {
            std::fs::read(
                Path::new(env!("CARGO_MANIFEST_DIR"))
                    .join("tests/fixtures")
                    .join(name),
            )
            .unwrap()
        };
        let key = SecretKey::from_seed([1u8; 32]);
        let libc_of = |file: &str, elf: &str, libc: Option<&str>| {
            let path = dir.path().join(file);
            std::fs::write(&path, fixture(elf)).unwrap();
            let created = create(&Request {
                artifacts: vec![ArtifactInput {
                    libc,
                    bin: vec![Bin::new("tool")],
                    ..ArtifactInput::new(&path)
                }],
                ..Request::new("tool.example.com", "1.0.0", key_identity(&key))
            })
            .unwrap();
            created.statement.predicate.artifacts[0].libc.clone()
        };
        let read = |file, elf| libc_of(file, elf, None);
        // A static build, such as a Go binary built with CGO_ENABLED=0,
        // names no libc, so a musl host takes it as well as a glibc one.
        assert_eq!(read("helmfile_linux_amd64", "static"), None);
        assert_eq!(read("tool-linux-x64", "needs-z").as_deref(), Some("gnu"));
        assert_eq!(
            read("tool-linux-arm64", "needs-musl").as_deref(),
            Some("musl")
        );
        // What the name says wins over the bytes.
        assert_eq!(
            read("tool-linux-x64-musl", "static").as_deref(),
            Some("musl")
        );
        assert_eq!(
            read("tool-x86_64-unknown-linux-gnu", "static").as_deref(),
            Some("gnu")
        );
        // And what the vendor says wins over both; `any` leaves it out.
        assert_eq!(
            libc_of("tool-linux-riscv64", "static", Some("gnu")).as_deref(),
            Some("gnu")
        );
        assert_eq!(libc_of("tool-linux-s390x", "needs-z", Some(ANY)), None);
        // Without reading the executables the default is gnu, as before.
        let path = dir.path().join("tool-linux-ppc64le");
        std::fs::write(&path, fixture("static")).unwrap();
        let unread = create(&Request {
            artifacts: vec![ArtifactInput {
                bin: vec![Bin::new("tool")],
                ..ArtifactInput::new(&path)
            }],
            read_executables: false,
            ..Request::new("tool.example.com", "1.0.0", key_identity(&key))
        })
        .unwrap();
        assert_eq!(
            unread.statement.predicate.artifacts[0].libc.as_deref(),
            Some("gnu")
        );
        // A static executable in a non-Linux build still names no libc.
        assert_eq!(read("tool-freebsd-x64", "static"), None);
    }

    #[test]
    fn an_architecture_is_required() {
        let dir = tempfile::tempdir().unwrap();
        let key = SecretKey::from_seed([1u8; 32]);
        let one = |input: ArtifactInput<'_>| {
            create(&Request {
                artifacts: vec![input],
                ..Request::new("tool.example.com", "1.0.0", key_identity(&key))
            })
        };
        let file = |name: &str| {
            let path = dir.path().join(name);
            std::fs::write(&path, b"bytes").unwrap();
            path
        };
        // A Linux or BSD build whose name says no architecture would fit
        // every host of its OS, so it is refused.
        for name in [
            "tool_1.0.0_linux_sparc.tar.gz",
            "tool-1.386.0-linux.tar.gz",
            "tool-freebsd.tar.gz",
            "tool-linux.AppImage",
            "tool-linux-noarch-tool.rpm",
            "tool-linux-all-tools.deb",
        ] {
            let path = file(name);
            let err = one(ArtifactInput::new(&path)).unwrap_err();
            assert!(matches!(err, Error::UnknownArch { .. }), "{name}: {err}");
            assert!(err.to_string().contains("any in place of"), "{err}");
        }
        let path = file("tool_1.0.0_linux_sparc.tar.gz");
        let err = one(ArtifactInput {
            os: Some("linux"),
            ..ArtifactInput::new(&path)
        })
        .unwrap_err();
        assert!(matches!(err, Error::UnknownArch { .. }), "{err}");
        // Naming one, saying `any`, or declaring the artifact portable
        // settles it.
        let named = one(ArtifactInput {
            os: Some("linux"),
            arch: Some("sparc64"),
            ..ArtifactInput::new(&path)
        })
        .unwrap();
        assert_eq!(
            named.statement.predicate.artifacts[0].arch.as_deref(),
            Some("sparc64")
        );
        let any = one(ArtifactInput {
            arch: Some(ANY),
            ..ArtifactInput::new(&path)
        })
        .unwrap();
        let artifact = &any.statement.predicate.artifacts[0];
        assert_eq!(
            (artifact.os.as_deref(), artifact.arch.as_deref()),
            (Some("linux"), None)
        );
        let portable = one(ArtifactInput {
            portable: true,
            ..ArtifactInput::new(&path)
        })
        .unwrap();
        assert_eq!(portable.statement.predicate.artifacts[0].os, None);
        // A macOS or Windows build named for no architecture is universal
        // or x86, which both run on ARM, and a file with no OS in its name
        // is not refused either, nor is a package whose format declares it
        // architecture-independent.
        for name in [
            "tool-1.0-1.noarch.rpm",
            "tool_1.0_all.deb",
            "Tool.dmg",
            "tool-macos.zip",
            "Tool-Setup-1.2.3.exe",
            "Tool.msi",
            "tool.tar.gz",
        ] {
            let path = file(name);
            let created = one(ArtifactInput::new(&path)).unwrap();
            assert_eq!(created.statement.predicate.artifacts[0].arch, None);
        }
    }

    #[test]
    fn resources_and_assets() {
        let dir = tempfile::tempdir().unwrap();
        let a = dir.path().join("tool-v1.0.0-linux-x64.tar.xz");
        let skill = dir.path().join("tool-skill.tar.gz");
        std::fs::write(&a, b"linux bytes").unwrap();
        std::fs::write(&skill, b"skill bytes").unwrap();
        let key = SecretKey::from_seed([1u8; 32]);
        let request = Request {
            artifacts: vec![ArtifactInput {
                bin: vec![Bin::new("tool")],
                ..ArtifactInput::new(&a)
            }],
            resources: vec![
                Resource {
                    shell: Some("zsh".into()),
                    archive: Some("share/zsh/site-functions/_tool".into()),
                    ..Resource::new("completion")
                },
                Resource {
                    name: Some("tool".into()),
                    asset: Some("tool-skill.tar.gz".into()),
                    ..Resource::new("skill")
                },
                Resource {
                    format: Some("usage".into()),
                    bin: Some("tool".into()),
                    exec: vec!["tool".into(), "usage".into()],
                    ..Resource::new("cli-spec")
                },
            ],
            assets: vec![AssetInput {
                path: &skill,
                url: None,
            }],
            url_base: Some("https://dl.example.com/1.0.0"),
            ..Request::new("tool.example.com", "1.0.0", key_identity(&key))
        };
        let created = create(&request).unwrap();
        let s = &created.statement;
        assert_eq!(s.subject.len(), 2);
        assert_eq!(s.subject[1].name, "tool-skill.tar.gz");
        assert_eq!(
            s.predicate.resources[1].url.as_deref(),
            Some("https://dl.example.com/1.0.0/tool-skill.tar.gz")
        );
        assert_eq!(s.predicate.resources[0].url, None);
        let asset_url = Request {
            assets: vec![AssetInput {
                path: &skill,
                url: Some("https://cdn.example.com/skill.tar.gz".into()),
            }],
            ..request
        };
        let created = create(&asset_url).unwrap();
        assert_eq!(
            created.statement.predicate.resources[1].url.as_deref(),
            Some("https://cdn.example.com/skill.tar.gz")
        );

        // A file given as both an artifact and an asset is the asset, once.
        let swept = create(&Request {
            artifacts: vec![
                ArtifactInput {
                    bin: vec![Bin::new("tool")],
                    ..ArtifactInput::new(&a)
                },
                ArtifactInput::new(&skill),
            ],
            assets: vec![
                AssetInput {
                    path: &skill,
                    url: None,
                },
                AssetInput {
                    path: &skill,
                    url: None,
                },
            ],
            resources: vec![Resource {
                name: Some("tool".into()),
                asset: Some("tool-skill.tar.gz".into()),
                ..Resource::new("skill")
            }],
            ..Request::new("tool.example.com", "1.0.0", key_identity(&key))
        })
        .unwrap();
        assert_eq!(swept.statement.predicate.artifacts.len(), 1);
        assert_eq!(swept.statement.subject.len(), 2);
        assert_eq!(swept.statement.subject[1].name, "tool-skill.tar.gz");

        // Two different files sharing a name are refused, not collapsed.
        let elsewhere = dir.path().join("elsewhere");
        std::fs::create_dir_all(&elsewhere).unwrap();
        let other_skill = elsewhere.join("tool-skill.tar.gz");
        std::fs::write(&other_skill, b"different bytes").unwrap();
        let err = create(&Request {
            artifacts: vec![ArtifactInput {
                bin: vec![Bin::new("tool")],
                ..ArtifactInput::new(&a)
            }],
            assets: vec![
                AssetInput {
                    path: &skill,
                    url: None,
                },
                AssetInput {
                    path: &other_skill,
                    url: None,
                },
            ],
            resources: vec![Resource {
                name: Some("tool".into()),
                asset: Some("tool-skill.tar.gz".into()),
                ..Resource::new("skill")
            }],
            ..Request::new("tool.example.com", "1.0.0", key_identity(&key))
        })
        .unwrap_err();
        assert!(matches!(err, Error::AssetCollision { .. }), "{err}");

        // The asset digest is checked like an artifact's, and a resource
        // whose asset was not given is refused.
        let root = crate::sigstore::trusted_root(None).unwrap();
        let options = crate::verify::Options {
            require_log: false,
            trusted_root: &root,
        };
        let bundle = crate::sigstore::sign(
            Signer::Key {
                key: key.clone(),
                log: false,
            },
            &created.document,
        )
        .unwrap();
        let verified =
            crate::verify::verify(&bundle, &Trust::Key(&key.public_key()), options, &[&skill])
                .unwrap();
        // The skill archive is an asset, not an artifact.
        assert!(verified.checked_artifacts.is_empty());
        assert_eq!(verified.checked_assets, ["tool-skill.tar.gz"]);
        assert_eq!(verified.asset_count, 1);
        assert_eq!(
            verified.resources,
            [
                "completion/zsh (archive)",
                "skill/tool (asset)",
                "cli-spec/usage/tool (exec)"
            ]
        );
        let err = create(&Request {
            assets: vec![],
            ..asset_url
        })
        .unwrap_err();
        assert!(err.to_string().contains("not a subject"), "{err}");
    }

    #[test]
    fn create_sign_verify_and_list() {
        let dir = tempfile::tempdir().unwrap();
        let a = dir.path().join("tool-v1.0.0-linux-x64.tar.xz");
        let b = dir.path().join("tool-v1.0.0-darwin-arm64.tar.xz");
        let w = dir.path().join("tool-v1.0.0-windows-x64.zip");
        let raw = dir.path().join("tool-linux-arm64");
        std::fs::write(&a, b"linux bytes").unwrap();
        std::fs::write(&b, b"darwin bytes").unwrap();
        std::fs::write(&w, b"windows bytes").unwrap();
        std::fs::write(&raw, b"bare").unwrap();
        let key = SecretKey::from_seed([1u8; 32]);
        let input = |path, os, bin: &[&str], provenance: &[&str]| ArtifactInput {
            os,
            bin: bin.iter().map(|s| Bin::new(*s)).collect(),
            provenance: provenance.iter().map(|s| s.to_string()).collect(),
            ..ArtifactInput::new(path)
        };
        let request = |artifacts, source, url_base| Request {
            published_at: Some("2026-09-01T00:00:00Z"),
            source,
            artifacts,
            url_base,
            ..Request::new("tool.example.com", "1.0.0", key_identity(&key))
        };
        let created = create(&request(
            vec![
                input(
                    &a,
                    None,
                    &["tool"],
                    &["https://example.com/a.sigstore.json"],
                ),
                input(&b, None, &["tool"], &[]),
                input(&w, None, &["bin/tool"], &[]),
                ArtifactInput {
                    bin: vec![Bin::named("tool-linux-arm64", "tool")],
                    url: Some("https://cdn.example.com/tool-linux-arm64".into()),
                    ..ArtifactInput::new(&raw)
                },
            ],
            Some(Source {
                repo: "https://github.com/example/tool".into(),
                commit: None,
                tag: Some("v1.0.0".into()),
            }),
            Some("https://github.com/example/tool/releases/download/v1.0.0/"),
        ))
        .unwrap();
        let arts = &created.statement.predicate.artifacts;
        assert_eq!(
            arts[0].url.as_deref(),
            Some(
                "https://github.com/example/tool/releases/download/v1.0.0/tool-v1.0.0-linux-x64.tar.xz"
            )
        );
        assert_eq!(arts[0].size, 11);
        assert_eq!(arts[0].bin, [Bin::new("tool")]);
        assert_eq!(
            arts[2].bin,
            [Bin::named("bin/tool.exe", "tool")],
            "windows gets .exe on the path, never the name"
        );
        assert_eq!(arts[3].format.as_deref(), Some("raw"));
        assert_eq!(
            arts[3].url.as_deref(),
            Some("https://cdn.example.com/tool-linux-arm64")
        );
        assert_eq!(arts[3].bin[0].name, "tool");

        // `--bin tool` on a bare executable names the artifact itself,
        // compressed or not, and on Windows both sides get .exe.
        let gz = dir.path().join("tool-linux-x64.gz");
        let exe = dir.path().join("tool-windows-x64.exe");
        let exe_gz = dir.path().join("tool-windows-arm64.exe.gz");
        for path in [&gz, &exe, &exe_gz] {
            std::fs::write(path, b"bare").unwrap();
        }
        let bare = create(&request(
            vec![
                input(&raw, None, &["tool"], &[]),
                input(&gz, None, &["tool"], &[]),
                input(&exe, None, &["tool"], &[]),
                input(&exe_gz, None, &["tool"], &[]),
            ],
            None,
            None,
        ))
        .unwrap();
        let arts = &bare.statement.predicate.artifacts;
        assert_eq!(arts[0].bin, [Bin::named("tool-linux-arm64", "tool")]);
        assert_eq!(arts[1].format.as_deref(), Some("gz"));
        assert_eq!(arts[1].bin, [Bin::named("tool-linux-x64", "tool")]);
        assert_eq!(arts[2].format.as_deref(), Some("raw"));
        assert_eq!(arts[2].bin, [Bin::named("tool-windows-x64.exe", "tool")]);
        assert_eq!(arts[3].format.as_deref(), Some("gz"));
        assert_eq!(arts[3].bin, [Bin::named("tool-windows-arm64.exe", "tool")]);

        // A format override and a portable artifact.
        let setup = dir.path().join("tool-x64.exe");
        let jar = dir.path().join("tool-linux.jar");
        std::fs::write(&setup, b"installer").unwrap();
        std::fs::write(&jar, b"jar").unwrap();
        let overridden = create(&request(
            vec![
                ArtifactInput {
                    format: Some("exe".into()),
                    ..ArtifactInput::new(&setup)
                },
                ArtifactInput {
                    portable: true,
                    format: Some("jar".into()),
                    ..ArtifactInput::new(&jar)
                },
            ],
            None,
            None,
        ))
        .unwrap();
        let arts = &overridden.statement.predicate.artifacts;
        assert_eq!(arts[0].format.as_deref(), Some("exe"));
        assert!(arts[0].bin.is_empty());
        assert_eq!(
            (&arts[1].os, &arts[1].arch, &arts[1].libc),
            (&None, &None, &None)
        );
        assert_eq!(arts[1].format.as_deref(), Some("jar"));

        // `.jar` is no format the name inference knows, and running it is
        // not something a consumer could guess, so without that override
        // the file is refused rather than published unusable. A header or
        // a shared library swept up by an artifacts glob lands here too.
        let header = dir.path().join("tool.h");
        std::fs::write(&header, b"#pragma once").unwrap();
        for path in [&jar, &header] {
            let err = create(&request(
                vec![ArtifactInput {
                    portable: true,
                    ..ArtifactInput::new(path)
                }],
                None,
                None,
            ))
            .unwrap_err();
            assert!(
                matches!(err, Error::UnknownFormat { .. }),
                "{path:?}: {err}"
            );
        }

        // A portable file with no extension is still a bare executable, and
        // a bare Windows file without .exe keeps its exact name as the path.
        let script = dir.path().join("tool-universal");
        let bare_win = dir.path().join("tool-windows-x64");
        std::fs::write(&script, b"#!/bin/sh").unwrap();
        std::fs::write(&bare_win, b"pe").unwrap();
        let portable = create(&request(
            vec![
                ArtifactInput {
                    portable: true,
                    bin: vec![Bin::new("tool")],
                    ..ArtifactInput::new(&script)
                },
                input(&bare_win, None, &["tool"], &[]),
            ],
            None,
            None,
        ))
        .unwrap();
        let arts = &portable.statement.predicate.artifacts;
        assert_eq!(arts[0].os, None);
        assert_eq!(arts[0].format.as_deref(), Some("raw"));
        assert_eq!(arts[0].bin, [Bin::named("tool-universal", "tool")]);
        assert_eq!(arts[1].format.as_deref(), Some("raw"));
        assert_eq!(arts[1].bin, [Bin::named("tool-windows-x64", "tool.exe")]);

        // A dotted version leaves a tail after the last dot that is not an
        // extension, so a bare executable named for one is still `raw`.
        let dotted = dir.path().join("tool-v1.2.3-linux-x64");
        std::fs::write(&dotted, b"elf").unwrap();
        let versioned = create(&request(
            vec![input(&dotted, None, &["tool"], &[])],
            None,
            None,
        ))
        .unwrap();
        let arts = &versioned.statement.predicate.artifacts;
        assert_eq!(arts[0].format.as_deref(), Some("raw"));
        assert_eq!(arts[0].bin, [Bin::named("tool-v1.2.3-linux-x64", "tool")]);

        // The same when the version comes last and the tail is a bare
        // number: `3` is no more an extension than `3-linux-x64` was.
        let trailing = dir.path().join("tool-linux-x64-v1.2.3");
        std::fs::write(&trailing, b"elf").unwrap();
        let trailing = create(&request(
            vec![input(&trailing, None, &["tool"], &[])],
            None,
            None,
        ))
        .unwrap();
        let arts = &trailing.statement.predicate.artifacts;
        assert_eq!(arts[0].format.as_deref(), Some("raw"));
        assert_eq!(arts[0].bin, [Bin::named("tool-linux-x64-v1.2.3", "tool")]);
        // Two portable artifacts of one format are as ambiguous as two
        // builds for one platform.
        let other_script = dir.path().join("tool-anywhere");
        std::fs::write(&other_script, b"#!/bin/sh").unwrap();
        let err = create(&request(
            vec![
                ArtifactInput {
                    portable: true,
                    ..ArtifactInput::new(&script)
                },
                ArtifactInput {
                    portable: true,
                    ..ArtifactInput::new(&other_script)
                },
            ],
            None,
            None,
        ))
        .unwrap_err();
        assert!(matches!(err, Error::Ambiguous { .. }), "{err}");

        // A path read from a Windows archive is kept exactly; only the PATH
        // name takes .exe.
        let win_zip = dir.path().join("tool-windows-x64.zip");
        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
        for entry in ["bin/tool", "bin/helper.exe"] {
            use std::io::Write as _;
            writer
                .start_file(entry, zip::write::SimpleFileOptions::default())
                .unwrap();
            writer.write_all(b"x").unwrap();
        }
        std::fs::write(&win_zip, writer.finish().unwrap().into_inner()).unwrap();
        let listed = create(&request(
            vec![input(&win_zip, None, &["tool", "helper"], &[])],
            None,
            None,
        ))
        .unwrap();
        assert_eq!(
            listed.statement.predicate.artifacts[0].bin,
            [
                Bin::named("bin/tool", "tool.exe"),
                Bin::named("bin/helper.exe", "helper.exe")
            ]
        );
        assert_eq!(
            created.statement.subject[0]
                .digest
                .sha512
                .as_ref()
                .map(String::len),
            Some(128)
        );
        assert!(!created.statement.provenance_linked());

        let overridden = create(&request(
            vec![input(&a, Some("darwin"), &[], &[])],
            None,
            None,
        ))
        .unwrap();
        assert_eq!(overridden.statement.predicate.artifacts[0].libc, None);
        let overridden = create(&request(
            vec![input(&b, Some("linux"), &[], &[])],
            None,
            None,
        ))
        .unwrap();
        assert_eq!(
            overridden.statement.predicate.artifacts[0].libc.as_deref(),
            Some("gnu")
        );

        // Two artifacts for one platform need a variant.
        let fips = dir.path().join("tool-fips-v1.0.0-linux-x64.tar.xz");
        std::fs::write(&fips, b"fips bytes").unwrap();
        let err = create(&request(
            vec![input(&a, None, &[], &[]), input(&fips, None, &[], &[])],
            None,
            None,
        ))
        .unwrap_err();
        assert!(matches!(err, Error::Ambiguous { .. }), "{err}");
        assert!(err.to_string().contains("linux/x86_64/gnu/tar.xz"), "{err}");
        let ok = create(&request(
            vec![
                input(&a, None, &[], &[]),
                ArtifactInput {
                    variant: Some("fips".into()),
                    ..ArtifactInput::new(&fips)
                },
            ],
            None,
            None,
        ))
        .unwrap();
        assert_eq!(
            ok.statement.predicate.artifacts[1].variant.as_deref(),
            Some("fips")
        );

        // Sign with the key, unlogged, and verify with the key.
        let root = crate::sigstore::trusted_root(None).unwrap();
        let options = crate::verify::Options {
            require_log: false,
            trusted_root: &root,
        };
        let bundle = crate::sigstore::sign(
            Signer::Key {
                key: key.clone(),
                log: false,
            },
            &created.document,
        )
        .unwrap();
        let public = key.public_key();
        let verified =
            crate::verify::verify(&bundle, &Trust::Key(&public), options, &[&a, &b]).unwrap();
        assert_eq!(verified.version, "1.0.0");
        assert_eq!(verified.scheme, Scheme::SigstoreKey);
        assert_eq!(verified.attested_by, Attestor::Vendor);
        assert_eq!(
            verified.checked_artifacts,
            [
                "tool-v1.0.0-linux-x64.tar.xz",
                "tool-v1.0.0-darwin-arm64.tar.xz"
            ]
        );
        assert!(!verified.provenance_linked);
        assert_eq!(verified.logged_at, None);

        // A modified artifact, a wrong key, an unlisted file, and a
        // statement declaring a different signer all fail.
        std::fs::write(&a, b"other bytes").unwrap();
        let err = crate::verify::verify(&bundle, &Trust::Key(&public), options, &[&a]).unwrap_err();
        assert!(err.to_string().contains("sha256 is"), "{err}");
        let other = SecretKey::from_seed([2u8; 32]);
        assert!(
            crate::verify::verify(&bundle, &Trust::Key(&other.public_key()), options, &[]).is_err()
        );
        let unknown = dir.path().join("unknown.tar.gz");
        std::fs::write(&unknown, b"").unwrap();
        let err =
            crate::verify::verify(&bundle, &Trust::Key(&public), options, &[&unknown]).unwrap_err();
        assert!(err.to_string().contains("not listed"), "{err}");
        let mut lying = created.statement.clone();
        lying.predicate.identity = key_identity(&other);
        let lying_bundle = crate::sigstore::sign(
            Signer::Key {
                key: key.clone(),
                log: false,
            },
            &lying.canonical_bytes(),
        )
        .unwrap();
        let err =
            crate::verify::verify(&lying_bundle, &Trust::Key(&public), options, &[]).unwrap_err();
        assert!(
            matches!(err, crate::verify::Error::DeclaredSignerMismatch { .. }),
            "{err}"
        );

        // A repackager document says so and lists its evidence.
        let repack = create(&Request {
            attested_by: Attestor::Repackager,
            evidence: vec![Evidence {
                kind: "pkgbuild-checksums".into(),
                detail: None,
            }],
            ..request(vec![input(&b, None, &[], &[])], None, None)
        })
        .unwrap();
        assert!(
            String::from_utf8_lossy(&repack.document).contains(r#""attested_by":"repackager""#)
        );
        let repack_bundle = crate::sigstore::sign(
            Signer::Key {
                key: key.clone(),
                log: false,
            },
            &repack.document,
        )
        .unwrap();
        let verified =
            crate::verify::verify(&repack_bundle, &Trust::Key(&public), options, &[]).unwrap();
        assert_eq!(verified.attested_by, Attestor::Repackager);

        // A release list over the bundle: a yanked, security-flagged entry.
        let bundle_path = dir.path().join("packslip.sigstore.json");
        std::fs::write(&bundle_path, &bundle).unwrap();
        let list = create_release_list(&ListRequest {
            project: "tool.example.com",
            generated_at: Some("2026-09-01T01:00:00Z"),
            valid_for: std::time::Duration::from_secs(30 * 86_400),
            sequence: 3,
            latest: Some("1.0.0"),
            releases: vec![ListedRelease {
                url: "https://dl.example.com/1.0.0/packslip.sigstore.json",
                bundle_path: &bundle_path,
                yanked: Some("bad build".into()),
                security: true,
                evidence: vec![],
            }],
            identity: key_identity(&key),
        })
        .unwrap();
        assert_eq!(list.statement.predicate.expires_at, "2026-10-01T01:00:00Z");
        assert_eq!(list.statement.predicate.latest.as_deref(), Some("1.0.0"));
        let entry = &list.statement.predicate.releases[0];
        assert_eq!(entry.version, "1.0.0");
        assert_eq!(entry.tag.as_deref(), Some("v1.0.0"));
        assert!(entry.is_yanked());
        assert_eq!(entry.status_reason.as_deref(), Some("bad build"));
        assert!(entry.security);
        assert_eq!(
            list.statement.subject[0].name,
            "https://dl.example.com/1.0.0/packslip.sigstore.json"
        );
        let list_bundle = crate::sigstore::sign(
            Signer::Key {
                key: key.clone(),
                log: false,
            },
            &list.document,
        )
        .unwrap();
        let verified_list =
            crate::verify::verify_release_list(&list_bundle, &Trust::Key(&public), options)
                .unwrap();
        assert_eq!(verified_list.list.predicate.sequence, 3);
        assert_eq!(
            verified_list.list.predicate.latest.as_deref(),
            Some("1.0.0")
        );
        assert!(
            verified_list
                .list
                .is_current("2026-09-15T00:00:00Z".parse().unwrap())
        );
        // A list with no releases still carries a subject for sigstore to
        // bind the signature to, and verifies.
        let empty = create_release_list(&ListRequest {
            project: "tool.example.com",
            generated_at: Some("2026-09-01T01:00:00Z"),
            valid_for: std::time::Duration::from_secs(86_400),
            sequence: 4,
            latest: None,
            releases: vec![],
            identity: key_identity(&key),
        })
        .unwrap();
        assert!(empty.statement.predicate.releases.is_empty());
        assert_eq!(empty.statement.subject.len(), 1);
        assert_eq!(empty.statement.subject[0].name, "_");
        assert_eq!(
            empty.statement.subject[0].digest.sha256,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
        let empty_bundle = crate::sigstore::sign(
            Signer::Key {
                key: key.clone(),
                log: false,
            },
            &empty.document,
        )
        .unwrap();
        let verified_empty =
            crate::verify::verify_release_list(&empty_bundle, &Trust::Key(&public), options)
                .unwrap();
        assert!(verified_empty.list.predicate.releases.is_empty());
        // Two bundles carrying the same version are a duplicate release.
        let err = create_release_list(&ListRequest {
            project: "tool.example.com",
            generated_at: None,
            valid_for: std::time::Duration::from_secs(60),
            sequence: 4,
            latest: None,
            releases: vec![
                ListedRelease {
                    url: "https://x/a.sigstore.json",
                    bundle_path: &bundle_path,
                    yanked: None,
                    security: false,
                    evidence: vec![],
                },
                ListedRelease {
                    url: "https://x/b.sigstore.json",
                    bundle_path: &bundle_path,
                    yanked: None,
                    security: false,
                    evidence: vec![],
                },
            ],
            identity: key_identity(&key),
        })
        .unwrap_err();
        assert!(err.to_string().contains("appears more than once"), "{err}");
        let err = create_release_list(&ListRequest {
            project: "other.example.com",
            generated_at: None,
            valid_for: std::time::Duration::from_secs(60),
            sequence: 1,
            latest: None,
            releases: vec![ListedRelease {
                url: "https://x/packslip.sigstore.json",
                bundle_path: &bundle_path,
                yanked: None,
                security: false,
                evidence: vec![],
            }],
            identity: key_identity(&key),
        })
        .unwrap_err();
        assert!(err.to_string().contains("the list is for"), "{err}");
    }

    #[test]
    fn a_release_list_takes_a_github_repository_name_in_any_case() {
        let bundle_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/hk-v2.3.0.sigstore.json");
        let key = SecretKey::from_seed([1u8; 32]);
        let request = |project| ListRequest {
            project,
            generated_at: None,
            valid_for: std::time::Duration::from_secs(60),
            sequence: 1,
            latest: None,
            releases: vec![ListedRelease {
                url: "https://x/packslip.sigstore.json",
                bundle_path: &bundle_path,
                yanked: None,
                security: false,
                evidence: vec![],
            }],
            identity: key_identity(&key),
        };
        // The bundle is for github.com/jdx/hk.
        create_release_list(&request("github.com/JDX/HK")).unwrap();
        let err = create_release_list(&request("github.com/jdx/hk/HK")).unwrap_err();
        assert!(err.to_string().contains("the list is for"), "{err}");
    }

    #[test]
    fn timestamps_are_written_in_utc() {
        let dir = tempfile::tempdir().unwrap();
        let a = dir.path().join("tool-v1.0.0-linux-x64.tar.xz");
        std::fs::write(&a, b"linux bytes").unwrap();
        let key = SecretKey::from_seed([1u8; 32]);
        let request = |published_at: Option<&'static str>| Request {
            published_at,
            artifacts: vec![ArtifactInput::new(&a)],
            ..Request::new("tool.example.com", "1.0.0", key_identity(&key))
        };
        // An offset, and a spelling outside RFC 3339 that the validator
        // reads, become the same instant in UTC.
        for given in [
            "2026-09-01T12:00:00Z",
            "2026-09-01T14:00:00+02:00",
            "20260901T120000Z",
        ] {
            let created = create(&request(Some(given))).unwrap();
            assert_eq!(
                created.statement.predicate.published_at, "2026-09-01T12:00:00Z",
                "{given}"
            );
        }
        let now = create(&request(None)).unwrap();
        let now = now.statement.predicate.published_at;
        assert!(now.ends_with('Z'), "{now}");
        // Year 0 itself is the earliest instant RFC 3339 can spell in UTC.
        let created = create(&request(Some("0000-01-01T01:00:00+01:00"))).unwrap();
        assert_eq!(
            created.statement.predicate.published_at,
            "0000-01-01T00:00:00Z"
        );
        // Text that names no instant, and an instant RFC 3339 cannot spell
        // in UTC, even by a fraction of a second.
        for given in [
            "yesterday",
            "2026-09-01T12:00:00",
            "0000-01-01T00:00:00+01:00",
            "0000-01-01T00:59:59.5+01:00",
        ] {
            let err = create(&request(Some(given))).unwrap_err();
            assert!(
                matches!(
                    err,
                    Error::Invalid(InvalidDocument::Timestamp {
                        field: "published_at",
                        ..
                    })
                ),
                "{given}: {err}"
            );
        }

        // A list writes its own times, and each packslip's, in UTC, even
        // for a packslip written with an offset.
        let mut offset = create(&request(None)).unwrap().statement;
        offset.predicate.published_at = "2026-09-01T14:00:00+02:00".into();
        let bundle = crate::sigstore::sign(
            Signer::Key {
                key: key.clone(),
                log: false,
            },
            &offset.canonical_bytes(),
        )
        .unwrap();
        let bundle_path = dir.path().join("packslip.sigstore.json");
        std::fs::write(&bundle_path, &bundle).unwrap();
        let list = |generated_at| {
            create_release_list(&ListRequest {
                project: "tool.example.com",
                generated_at,
                valid_for: std::time::Duration::from_secs(86_400),
                sequence: 1,
                latest: None,
                releases: vec![ListedRelease {
                    url: "https://dl.example.com/1.0.0/packslip.sigstore.json",
                    bundle_path: &bundle_path,
                    yanked: None,
                    security: false,
                    evidence: vec![],
                }],
                identity: key_identity(&key),
            })
        };
        let created = list(Some("2026-09-02T09:00:00+09:00")).unwrap();
        let p = &created.statement.predicate;
        assert_eq!(p.generated_at, "2026-09-02T00:00:00Z");
        assert_eq!(p.expires_at, "2026-09-03T00:00:00Z");
        assert_eq!(p.releases[0].published_at, "2026-09-01T12:00:00Z");
        let err = list(Some("tomorrow")).unwrap_err();
        assert!(
            matches!(
                err,
                Error::Invalid(InvalidDocument::Timestamp {
                    field: "generated_at",
                    ..
                })
            ),
            "{err}"
        );
    }
}