packslip 0.2.0

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
//! 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, ListRequest, ListedRelease, Request};
use packslip::minisign::{PublicKey, SecretKey, key_id_hex};
use packslip::model::{RELEASES_PREDICATE_TYPE, ReleaseListStatement, 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.
const BUNDLE_NAME: &str = "packslip.sigstore.json";

/// 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),
    Verify(Verify),
    Version(Version),
}

/// Generate an Ed25519 key pair for the sigstore-key scheme
///
/// Only needed outside a CI job: with an OIDC identity, `create` signs
/// keylessly and needs no key. Writes the secret seed to the given path
/// (mode 0600) and a minisign-format public key beside it with a .pub
/// extension.
#[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 of the release statement, or of the release list
#[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,
    /// The exact signed bytes instead of pretty JSON
    #[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:?}")),
        }
    }
}

/// 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
///
/// Digests every artifact, infers os/arch/libc/format from file names
/// (override with name:os/arch[/libc]), and writes packslip.sigstore.json
/// into --out. Inside a CI job the document is signed keylessly with the
/// job's identity. With --key it is signed with an Ed25519 key from
/// `packslip keygen`. Either way the signature is logged to Rekor.
#[derive(Debug, usage_rs::Args)]
struct Create {
    /// The project's name: a host path such as github.com/owner/repo
    #[usage(long)]
    project: String,
    /// The release version
    #[usage(long)]
    version: String,
    /// Artifact files, optionally as path:os/arch[/libc]
    #[usage(required = true)]
    artifacts: 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. Consumers must
    /// then opt in with --allow-unlogged
    #[usage(long)]
    no_log: bool,
    /// Directory to write into
    #[usage(short = 'o', long, default = ".")]
    out: PathBuf,
    /// Download URL prefix for the artifacts
    #[usage(long)]
    url_base: Option<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>,
    /// SBOM URL
    #[usage(long)]
    sbom: Option<String>,
    /// The version this release replaces
    #[usage(long)]
    supersedes: Option<String>,
    /// Executable inside every archive, relative to its root (repeatable)
    #[usage(long)]
    bin: Vec<String>,
    /// Provenance URL for every artifact (repeatable, positional order)
    #[usage(long)]
    provenance: Vec<String>,
}

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

    fn run_with(self, _: BinInfo) -> Self::Output {
        if self.source_repo.is_none() && (self.commit.is_some() || self.tag.is_some()) {
            bail!("--commit and --tag require --source-repo");
        }
        let signer = signer(&self.key, self.sign, self.no_log)?;
        let parsed: Vec<ArtifactSpec> = self.artifacts.iter().map(|s| parse_spec(s)).collect();
        let artifacts: Vec<ArtifactInput<'_>> = parsed
            .iter()
            .enumerate()
            .map(|(i, spec)| ArtifactInput {
                path: &spec.path,
                os: spec.os.as_deref(),
                arch: spec.arch.as_deref(),
                libc: spec.libc.as_deref(),
                bin: self.bin.clone(),
                provenance: self.provenance.get(i).cloned().into_iter().collect(),
            })
            .collect();
        let source = self.source_repo.as_ref().map(|repo| Source {
            repo: repo.clone(),
            commit: self.commit.clone(),
            tag: self.tag.clone(),
        });
        let created = packslip::create::create(&Request {
            project: &self.project,
            version: &self.version,
            published_at: self.published_at.as_deref(),
            source,
            artifacts,
            url_base: self.url_base.as_deref(),
            sbom: self.sbom.as_deref(),
            supersedes: self.supersedes.as_deref(),
            identity: 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);
        std::fs::write(&path, &bundle)?;
        println!(
            "wrote {} ({} artifact(s), signed by {}{})",
            path.display(),
            created.statement.predicate.artifacts.len(),
            identity.key_id,
            if self.no_log { ", unlogged" } else { "" }
        );
        Ok(())
    }
}

/// An artifact argument: a path, optionally with `:os/arch[/libc]`.
struct ArtifactSpec {
    path: PathBuf,
    os: Option<String>,
    arch: Option<String>,
    libc: Option<String>,
}

/// Recognize only a well-formed `os/arch[/libc]` suffix. In particular,
/// colons inside timestamped directory names remain part of the path.
fn parse_spec(spec: &str) -> ArtifactSpec {
    match spec.rsplit_once(':') {
        Some((path, platform)) if valid_platform(platform) => {
            let mut parts = platform.split('/');
            ArtifactSpec {
                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),
            }
        }
        _ => ArtifactSpec {
            path: PathBuf::from(spec),
            os: None,
            arch: None,
            libc: None,
        },
    }
}

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
///
/// For a project on its own domain: lists released packslips with their
/// digests so consumers can discover releases, with an expiry and a
/// sequence number so they notice a stale or truncated list. Publish the
/// result at https://<host>/.well-known/packslip/<path>.json.
#[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,
    /// 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>,
    /// 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 releases = pairs
            .iter()
            .map(|(url, path)| ListedRelease {
                url,
                bundle_path: path,
            })
            .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,
            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
///
/// Checks the bundle's signature and log entry, the statement, and the
/// digest and size of every artifact file given. Exits 1 on any failure.
/// A keyless document is checked against --identity, --identity-prefix,
/// and --issuer, or, for a project on github.com or gitlab.com, against
/// the repository the project name says signed it. A key-signed document
/// is checked against --pubkey.
#[derive(Debug, usage_rs::Args)]
struct Verify {
    /// The packslip.sigstore.json 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>,
    /// Artifact files to check against the document
    #[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 {
                        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()
                        );
                    }
                    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,
                        verified.published_at,
                        verified.key_id,
                        verified.scheme,
                        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 {
                            ""
                        }
                    );
                }
                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_platform_suffix_does_not_consume_timestamped_paths() {
        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());
        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");
        assert_eq!(spec.libc.as_deref(), Some("musl"));
    }

    #[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());
    }
}