packslip 1.1.1

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
//! The `packslip` binary: create, verify, show, releases, keygen, schema.

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

use eyre::{Context as _, Result, bail};
use packslip::cli::{BinInfo, Version};
use packslip::create::{ArtifactInput, AssetInput, ListRequest, ListedRelease, Request};
use packslip::manifest::Manifest;
use packslip::minisign::{PublicKey, SecretKey, key_id_hex};
use packslip::model::{
    Attestor, Bin, Evidence, Extensions, RELEASES_PREDICATE_TYPE, ReleaseListStatement,
    RequiredBin, Resource, Source, Statement,
};
use packslip::sigstore::{self, Policy, Signer, 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.
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 vendor runs `packslip create` in its release job to publish one signed
/// document listing every artifact. Consumers verify it with `packslip
/// verify` against a pinned identity or key. See https://packslip.dev.
#[derive(usage_rs::Cli)]
#[usage(
    name = "packslip",
    bin = "packslip",
    version,
    author = "Jeff Dickey <@jdx>",
    arg_required_else_help
)]
struct Cli {
    #[usage(subcommand)]
    command: Option<Commands>,
}

#[derive(usage_rs::Subcommands)]
#[usage(run_with)]
enum Commands {
    Create(Box<Create>),
    Keygen(Keygen),
    Releases(Box<Releases>),
    Schema(Schema),
    Show(Show),
    #[usage(hide)]
    Usage(Usage),
    Verify(Verify),
    Version(Version),
}

/// 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 the sigstore-key scheme
///
/// Writes a secret seed to --out (mode 0600 on Unix) and a minisign-format
/// public key beside it with a .pub extension. Refuses to overwrite either
/// file. Keep the secret private; distribute the public key to consumers.
/// A supported CI OIDC identity can sign without a long-lived key.
#[derive(Debug, usage_rs::Args)]
struct Keygen {
    /// Where to write the secret key
    #[usage(short = 'o', long, default = "packslip.key")]
    out: PathBuf,
}

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
///
/// Use --releases for the release-list statement schema. These schemas
/// describe the in-toto payload, not the enclosing sigstore bundle.
#[derive(Debug, usage_rs::Args)]
struct Schema {
    /// The releases/v1 list instead of the release/v1 statement
    #[usage(long)]
    releases: bool,
}

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

    fn run_with(self, _: BinInfo) -> Self::Output {
        let schema = 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
#[derive(Debug, usage_rs::Args)]
struct Show {
    /// The packslip.sigstore.json (or release list) to read
    #[usage(value_hint = usage_rs::ValueHint::FilePath)]
    bundle: PathBuf,
    /// Print the 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)]
enum SignWith {
    Oidc,
    Key,
}

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)]
struct AttestorArg(Attestor);

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.
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 a packslip for a release
///
/// Hash local artifacts, infer platforms and formats from filenames, and
/// write a signed bundle to --out. Use --manifest for per-artifact paths,
/// formats, requirements, and scoped resources. No files are uploaded.
///
/// Signing uses a supported CI OIDC identity by default. Use --key to
/// sign with an Ed25519 key instead. Signatures are logged to Rekor unless
/// a key-signed release explicitly uses --no-log.
///
/// Examples and configuration: https://packslip.dev/docs/describing-releases/
#[derive(Debug, usage_rs::Args)]
struct Create {
    /// The project's name: a host path such as github.com/owner/repo, or
    /// github.com/owner/repo/tool for one tool of a monorepo. Required
    /// unless the manifest names it
    #[usage(long)]
    project: Option<String>,
    /// Semver release version, such as 1.2.3. Required unless set in the manifest
    #[usage(long)]
    version: Option<String>,
    /// Artifact files, optionally as path[:os/arch[/libc]|:any][@variant].
    /// Added to those the manifest lists
    artifacts: Vec<String>,
    /// A TOML manifest giving per-artifact executables, formats,
    /// requirements, platforms, and the release's resources; see
    /// https://packslip.dev/docs/describing-releases/
    #[usage(short = 'm', long, value_hint = usage_rs::ValueHint::FilePath)]
    manifest: Option<PathBuf>,
    /// Sign with this secret key instead of a CI identity
    #[usage(short = 'k', long, value_hint = usage_rs::ValueHint::FilePath)]
    key: Option<PathBuf>,
    /// How to sign; defaults to key when --key is given, else oidc
    #[usage(long)]
    sign: Option<SignWith>,
    /// With --key: do not record the signature in Rekor. Consumers must
    /// then opt in with --allow-unlogged
    #[usage(long)]
    no_log: bool,
    /// Directory for the signed bundle (does not copy artifacts)
    #[usage(short = 'o', long, default = ".")]
    out: PathBuf,
    /// Download URL prefix for the artifacts
    #[usage(long)]
    url_base: Option<String>,
    /// Download URL for one artifact or resource asset, as FILENAME=URL (repeatable)
    #[usage(long)]
    url: Vec<String>,
    /// Format of one artifact whose name does not say, as FILENAME=FORMAT:
    /// 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 (repeatable)
    #[usage(long)]
    format: Vec<String>,
    /// Source repository URL
    #[usage(long)]
    source_repo: Option<String>,
    /// Source commit
    #[usage(long)]
    commit: Option<String>,
    /// Source tag
    #[usage(long)]
    tag: Option<String>,
    /// RFC 3339 publish time; defaults to now
    #[usage(long)]
    published_at: Option<String>,
    /// URL of the release notes
    #[usage(long)]
    notes_url: Option<String>,
    /// Release-level extension as NAME=JSON, where NAME is who defines it
    /// (a consumer such as mise, or a domain the vendor controls) and JSON
    /// is its value. Example: 'example.com={"build_id":"20260901.3"}'
    /// (repeatable)
    #[usage(long)]
    extension: Vec<String>,
    /// Executable inside every artifact, as PATH or NAME=PATH; for a bare
    /// executable, the name it gets on PATH (repeatable)
    #[usage(long)]
    bin: Vec<String>,
    /// Something else the release ships, as
    /// KIND[/QUALIFIER][@os[/arch[/libc]]]=SOURCE:VALUE where SOURCE is
    /// archive (a path inside every archive), asset (a
    /// separate release file, by local path), repo (a path at --commit),
    /// or exec (a command whose stdout is the file). Kinds: completion/SHELL
    /// (or completion/SHELL,SHELL with exec and a {shell} placeholder),
    /// man[/BIN], cli-spec/FORMAT[/BIN], skill/NAME, sbom/FORMAT, desktop, icon,
    /// app. An @ scope limits the entry to the artifacts of that platform,
    /// for a layout that differs across them; the manifest also scopes to
    /// one exact artifact. Examples:
    /// 'completion/zsh=archive:share/zsh/site-functions/_tool',
    /// 'man@linux=archive:share/man/man1/tool.1' (repeatable)
    #[usage(long)]
    resource: Vec<String>,
    /// Provenance URL for an artifact, as FILENAME=URL, or bare URLs in
    /// the order the artifacts are given (repeatable)
    #[usage(long)]
    provenance: Vec<String>,
    /// Who makes the claim: vendor (default) or repackager
    #[usage(long)]
    attested_by: Option<AttestorArg>,
    /// What a repackager checked, as KIND or KIND=DETAIL (repeatable)
    #[usage(long)]
    evidence: Vec<String>,
    /// Record only sha256, not sha512 as well
    #[usage(long)]
    no_sha512: bool,
    /// A command the executables need on PATH, as bin:NAME or bin:NAME@MIN
    /// where MIN is the lowest version that works. Example: bin:java@17
    /// (repeatable)
    #[usage(long)]
    require: Vec<String>,
    /// Do not open the artifacts to record the shared libraries their
    /// executables load from the host
    #[usage(long)]
    no_libs: bool,
}

/// `PATH` or `NAME=PATH`.
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.
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.
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`.
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),
    })
}

/// `KIND` or `KIND=DETAIL`.
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`.
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.
fn file_name_of(path: &Path) -> &str {
    path.file_name()
        .and_then(|n| n.to_str())
        .unwrap_or_default()
}

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");
        }
        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, signer.identity())
        })?;
        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`.
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.
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.
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.
fn valid_scope(scope: &str) -> bool {
    let parts: Vec<_> = scope.split('/').collect();
    (1..=3).contains(&parts.len()) && parts.iter().all(|part| valid_word(part))
}

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 release bundles and write a signed index with their digests,
/// versions, expiry, and sequence. Repeat --release for every entry to keep;
/// this command does not append to a previous list or upload the output.
///
/// Publish at the project's well-known location, or as a supplementary
/// list on a GitHub repository's default branch. See
/// https://packslip.dev/docs/release-lists/.
#[derive(Debug, usage_rs::Args)]
struct Releases {
    /// The project's name, which every listed packslip must carry
    #[usage(long)]
    project: String,
    /// Increases with every list published
    #[usage(long)]
    sequence: u64,
    /// Recommend this exact listed version for unconstrained latest requests
    #[usage(long)]
    latest: Option<String>,
    /// How long the list stays current: 30d, 12h, 2w
    #[usage(long, default = "30d")]
    valid_for: String,
    /// RFC 3339 generation time; defaults to now
    #[usage(long)]
    generated_at: Option<String>,
    /// A released packslip as URL=PATH: where consumers fetch it, and the
    /// local copy to read (repeatable)
    #[usage(long, required = true)]
    release: Vec<String>,
    /// Mark a listed release withdrawn, as URL=REASON (repeatable)
    #[usage(long)]
    yank: Vec<String>,
    /// Mark a listed release as a security fix, by URL (repeatable)
    #[usage(long)]
    security: Vec<String>,
    /// What a publisher other than the vendor checked about a listed
    /// release, as URL=KIND or URL=KIND=DETAIL (repeatable)
    #[usage(long)]
    evidence: Vec<String>,
    /// Sign with this secret key instead of a CI identity
    #[usage(short = 'k', long, value_hint = usage_rs::ValueHint::FilePath)]
    key: Option<PathBuf>,
    /// How to sign; defaults to key when --key is given, else oidc
    #[usage(long)]
    sign: Option<SignWith>,
    /// With --key: do not record the signature in Rekor
    #[usage(long)]
    no_log: bool,
    /// Where to write the list
    #[usage(short = 'o', long, default = "packslip-releases.sigstore.json")]
    out: PathBuf,
}

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: signer.identity(),
        })?;
        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`.
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 packslip, or a release list, against a pinned identity or key
///
/// Check the signature, log evidence, and statement structure. With
/// --artifact, also check local files against signed digests and artifact
/// sizes. Without it, only the bundle is checked. Verification failures
/// exit with status 1; no remote artifacts or provenance are fetched.
///
/// Pin a keyless signer with --identity or --identity-prefix and --issuer,
/// or a signing key with --pubkey. Without an explicit pin, derive the
/// policy from the document's claimed GitHub or GitLab project. Consumers
/// must separately match the project and version to their intended request.
/// For release lists, expiry and remembered sequence checks are the
/// consumer's responsibility. See https://packslip.dev/docs/verifying/.
#[derive(Debug, usage_rs::Args)]
struct Verify {
    /// Local release bundle or signed release list to verify
    #[usage(value_hint = usage_rs::ValueHint::FilePath)]
    bundle: PathBuf,
    /// The pinned public key file, or its base64 line
    #[usage(short = 'p', long)]
    pubkey: Option<String>,
    /// The exact certificate identity a keyless signer must have
    #[usage(long)]
    identity: Option<String>,
    /// A prefix the certificate identity must start with, such as
    /// https://github.com/owner/repo/
    #[usage(long)]
    identity_prefix: Option<String>,
    /// The OIDC issuer a keyless signer must have
    #[usage(long)]
    issuer: Option<String>,
    /// Accept a bundle without a transparency log entry
    #[usage(long)]
    allow_unlogged: bool,
    /// A sigstore trusted_root.json to use instead of the embedded one
    #[usage(long, value_hint = usage_rs::ValueHint::FilePath)]
    trusted_root: Option<PathBuf>,
    /// Local artifacts or resource assets to check (repeatable; not downloaded)
    #[usage(short = 'a', long)]
    artifact: Vec<PathBuf>,
    /// Print the result as JSON
    #[usage(short = 'J', long)]
    json: bool,
}

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

impl Pin {
    fn as_trust(&self) -> Trust<'_> {
        match self {
            Pin::Key(key) => Trust::Key(key),
            Pin::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()
            .to_string();
        let is_list = peeked["predicateType"] == RELEASES_PREDICATE_TYPE;

        let pin = match &self.pubkey {
            Some(text) => {
                if self.identity.is_some()
                    || self.identity_prefix.is_some()
                    || self.issuer.is_some()
                {
                    bail!(
                        "--pubkey pins a key; the identity flags pin a certificate. Pass one kind"
                    );
                }
                let pubkey_text = if Path::new(text).is_file() {
                    std::fs::read_to_string(text)?
                } else {
                    text.clone()
                };
                Pin::Key(PublicKey::parse(&pubkey_text)?)
            }
            None => {
                let explicit = Policy {
                    issuer: self.issuer.clone(),
                    identity: self.identity.clone(),
                    identity_prefix: self.identity_prefix.clone(),
                };
                Pin::Identity(if explicit.is_empty() {
                    Policy::for_project(&project).ok_or(sigstore::Error::NoPolicy(project))?
                } else {
                    explicit
                })
            }
        };
        let root_json = match &self.trusted_root {
            Some(path) => Some(
                std::fs::read_to_string(path)
                    .wrap_err_with(|| format!("reading {}", path.display()))?,
            ),
            None => None,
        };
        let trusted_root = sigstore::trusted_root(root_json.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();

        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;
                    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()
                            }
                        );
                    }
                    Ok(())
                }
                Err(err) => {
                    eprintln!("verification failed: {err}");
                    std::process::exit(1)
                }
            };
        }
        match packslip::verify(&text, &pin.as_trust(), options, &artifacts) {
            Ok(verified) => {
                if self.json {
                    println!("{}", serde_json::to_string_pretty(&verified)?);
                } else {
                    println!(
                        "ok: {} {}{} published {} signed by {} ({}){}{} ({} of {} artifact(s) 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(),
                        },
                        verified.checked_artifacts.len(),
                        verified.artifact_count,
                        if verified.provenance_linked {
                            ", provenance linked"
                        } else {
                            ""
                        },
                        if verified.resources.is_empty() {
                            String::new()
                        } else {
                            format!(", {} resource(s)", verified.resources.len())
                        }
                    );
                    for line in &verified.requires {
                        println!("  requires {line}");
                    }
                }
                Ok(())
            }
            Err(err) => {
                eprintln!("verification failed: {err}");
                std::process::exit(1)
            }
        }
    }
}

fn main() -> Result<()> {
    color_eyre::install()?;
    let args: Vec<_> = std::env::args_os().collect();
    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(test)]
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());
    }
}