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
//! Verifying a packslip: the bundle against what the consumer pinned, then
//! the statement, then the digests of any artifacts at hand. And the same
//! for a release list.

use std::path::Path;

use sigstore_trust_root::TrustedRoot;

use crate::forge;
use crate::model::{Artifact, InvalidDocument, ReleaseListStatement, Scheme, Statement};
use crate::sigstore::{self, Policy, SignedBy, Trust};

/// How strict to be.
#[derive(Debug, Clone, Copy)]
pub struct Options<'a> {
    /// Refuse a bundle without a Rekor entry. On by default; a consumer
    /// turns it off only for a vendor it has agreed to accept unlogged.
    pub require_log: bool,
    pub trusted_root: &'a TrustedRoot,
}

/// An artifact the verified statement lists, with the digest the statement
/// signs for it.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct VerifiedArtifact {
    #[serde(flatten)]
    pub artifact: Artifact,
    /// The signed SHA-256 of the file, in lowercase hex.
    pub sha256: String,
}

/// What a successful verification established.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Verified {
    pub project: String,
    pub version: String,
    pub published_at: String,
    pub scheme: Scheme,
    /// Who signed: the certificate identity, or the key id.
    pub key_id: String,
    /// Whether the document asks consumers to hold later releases to the
    /// workflow that signed it. See [`crate::model::Identity::pin_workflow`].
    #[serde(skip_serializing_if = "std::clone::Clone::clone")]
    pub pin_workflow: bool,
    /// Whether the vendor or a repackager made the claim.
    pub attested_by: crate::model::Attestor,
    /// Whether the version has a prerelease part.
    pub prerelease: bool,
    /// The channel the version's prerelease part names, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channel: Option<String>,
    /// The OIDC issuer, for `sigstore-oidc`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub issuer: Option<String>,
    /// When the transparency log recorded the signature, RFC 3339. None
    /// only for an unlogged bundle the consumer chose to accept.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logged_at: Option<String>,
    /// Whether every artifact links build provenance for the consumer to
    /// verify. The packslip proves the manifest; SLSA provenance, if
    /// verified, proves the build.
    pub provenance_linked: bool,
    /// Artifacts whose digests were checked against files.
    pub checked_artifacts: Vec<String>,
    pub artifact_count: usize,
    /// Resource assets, such as an SBOM or a skill archive, whose digests
    /// were checked against files.
    pub checked_assets: Vec<String>,
    /// How many assets the document lists besides its artifacts.
    pub asset_count: usize,
    /// The kinds of resources declared (completions, man pages, CLI
    /// specs, ...), one label per entry, in document order.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub resources: Vec<String>,
    /// What each artifact requires of the host, one line per artifact
    /// that declares anything: `name: glibc>=2.31; libs libz.so.1; bin
    /// java>=17`.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub requires: Vec<String>,
    /// Every artifact the statement lists, in document order, with its
    /// signed digest. Whatever the caller passed as `--artifact`, these are
    /// verified metadata: nothing was downloaded to produce them.
    pub artifacts: Vec<VerifiedArtifact>,
}

/// What `packslip verify --json` prints for a release: the verified report,
/// plus the repository the signing certificate records, when it records one.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct VerifyReport<'a> {
    #[serde(flatten)]
    pub verified: &'a Verified,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_repository: Option<&'a sigstore::SourceRepository>,
}

/// What verifying a release list established.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedList {
    pub list: ReleaseListStatement,
    pub scheme: Scheme,
    pub key_id: String,
    pub issuer: Option<String>,
    /// Whether the list asks consumers to hold later lists to the workflow
    /// that signed it. See [`crate::model::Identity::pin_workflow`].
    pub pin_workflow: bool,
    pub logged_at: Option<String>,
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("statement is not well-formed: {0}")]
    Json(#[from] serde_json::Error),
    #[error("statement is invalid: {0}")]
    Invalid(#[from] InvalidDocument),
    #[error("statement declares scheme {declared} but the bundle was signed by {actual}")]
    SchemeMismatch {
        declared: Scheme,
        actual: &'static str,
    },
    #[error("statement declares signer {declared:?}, the bundle was signed by {actual:?}")]
    DeclaredSignerMismatch { declared: String, actual: String },
    #[error("statement declares issuer {declared:?}, the certificate says {actual:?}")]
    DeclaredIssuerMismatch { declared: String, actual: String },
    #[error("{0}")]
    Sigstore(#[from] sigstore::Error),
    #[error("artifact {name}: {why}")]
    Artifact { name: String, why: String },
}

/// Check the statement's own `identity` block against who actually signed.
fn check_declared(
    identity: &crate::model::Identity,
    signed_by: &SignedBy,
) -> Result<(Scheme, String, Option<String>), Error> {
    match (identity.scheme, signed_by) {
        (
            Scheme::SigstoreOidc,
            SignedBy::Identity {
                identity: actual,
                issuer,
            },
        ) => {
            if identity.key_id != *actual {
                return Err(Error::DeclaredSignerMismatch {
                    declared: identity.key_id.clone(),
                    actual: actual.clone(),
                });
            }
            if let Some(declared) = &identity.issuer
                && declared != issuer
            {
                return Err(Error::DeclaredIssuerMismatch {
                    declared: declared.clone(),
                    actual: issuer.clone(),
                });
            }
            Ok((Scheme::SigstoreOidc, actual.clone(), Some(issuer.clone())))
        }
        (Scheme::SigstoreKey, SignedBy::Key { key_id }) => {
            if !identity.key_id.eq_ignore_ascii_case(key_id) {
                return Err(Error::DeclaredSignerMismatch {
                    declared: identity.key_id.clone(),
                    actual: key_id.clone(),
                });
            }
            Ok((Scheme::SigstoreKey, key_id.clone(), None))
        }
        (declared, SignedBy::Identity { .. }) => Err(Error::SchemeMismatch {
            declared,
            actual: "an OIDC identity",
        }),
        (declared, SignedBy::Key { .. }) => Err(Error::SchemeMismatch {
            declared,
            actual: "a key",
        }),
    }
}

fn logged_at(integrated_time: Option<i64>) -> Option<String> {
    integrated_time
        .and_then(|t| jiff::Timestamp::from_second(t).ok())
        .map(|t| t.to_string())
}

/// Verify a packslip bundle against what the consumer trusts, then check
/// any local artifacts by file name.
pub fn verify(
    bundle: &str,
    trust: &Trust<'_>,
    options: Options<'_>,
    artifacts: &[&Path],
) -> Result<Verified, Error> {
    let verified = sigstore::verify(bundle, trust, options.require_log, options.trusted_root)?;
    let statement: Statement = serde_json::from_slice(&verified.statement)?;
    statement.validate()?;
    let version = crate::model::parse_version(&statement.predicate.version)?;
    let (scheme, key_id, issuer) =
        check_declared(&statement.predicate.identity, &verified.signed_by)?;
    let mut checked_artifacts = Vec::new();
    let mut checked_assets = Vec::new();
    for path in artifacts {
        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default()
            .to_string();
        let Some(expected) = statement.digest_of(&name) else {
            return Err(Error::Artifact {
                name,
                why: "not listed in the document".into(),
            });
        };
        let (actual, size) = crate::digest_file(path).map_err(|e| Error::Artifact {
            name: name.clone(),
            why: e.to_string(),
        })?;
        if actual != expected {
            return Err(Error::Artifact {
                name,
                why: format!("sha256 is {actual}, document says {expected}"),
            });
        }
        let declared_size = statement
            .predicate
            .artifacts
            .iter()
            .find(|a| a.name == name)
            .map(|a| a.size);
        match declared_size {
            Some(declared) if declared != size => {
                return Err(Error::Artifact {
                    name,
                    why: format!("size is {size}, document says {declared}"),
                });
            }
            Some(_) => checked_artifacts.push(name),
            // A subject that is not an artifact is a resource asset.
            None => checked_assets.push(name),
        }
    }
    let artifact_count = statement.predicate.artifacts.len();
    Ok(Verified {
        project: statement.predicate.project.clone(),
        version: statement.predicate.version.clone(),
        published_at: statement.predicate.published_at.clone(),
        scheme,
        key_id,
        pin_workflow: statement.predicate.identity.pins_workflow(),
        attested_by: statement.predicate.attested_by,
        prerelease: !version.pre.is_empty(),
        channel: crate::model::channel(&version).map(str::to_string),
        issuer,
        logged_at: logged_at(verified.integrated_time),
        provenance_linked: statement.provenance_linked(),
        checked_artifacts,
        artifact_count,
        checked_assets,
        asset_count: statement.subject.len() - artifact_count,
        resources: statement
            .predicate
            .resources
            .iter()
            .map(|r| {
                format!(
                    "{} ({})",
                    r.label(),
                    r.source().map_or("?".to_string(), |s| s.to_string())
                )
            })
            .collect(),
        requires: statement
            .predicate
            .artifacts
            .iter()
            .filter_map(|a| {
                let requires = a.requires.as_ref().filter(|r| !r.is_empty())?;
                Some(format!("{}: {}", a.name, requires.summary()))
            })
            .collect(),
        artifacts: statement
            .predicate
            .artifacts
            .iter()
            .map(|a| VerifiedArtifact {
                artifact: a.clone(),
                sha256: statement.digest_of(&a.name).unwrap_or_default().to_string(),
            })
            .collect(),
    })
}

/// Verify a release-list bundle against what the consumer trusts. The
/// caller checks expiry and sequence against what it has seen.
pub fn verify_release_list(
    bundle: &str,
    trust: &Trust<'_>,
    options: Options<'_>,
) -> Result<VerifiedList, Error> {
    let verified = sigstore::verify(bundle, trust, options.require_log, options.trusted_root)?;
    let list: ReleaseListStatement = serde_json::from_slice(&verified.statement)?;
    list.validate()?;
    let (scheme, key_id, issuer) = check_declared(&list.predicate.identity, &verified.signed_by)?;
    let pin_workflow = list.predicate.identity.pins_workflow();
    Ok(VerifiedList {
        list,
        scheme,
        key_id,
        issuer,
        pin_workflow,
        logged_at: logged_at(verified.integrated_time),
    })
}

/// What [`verify_forge`] or [`verify_forge_release_list`] established: the
/// verification itself, and how the signing repository relates to the
/// one the consumer expected.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ForgeVerified<T> {
    /// A [`Verified`] or a [`VerifiedList`].
    pub verified: T,
    /// The continuity, the certificate's source repository, and the pin
    /// to remember once the release is accepted.
    pub check: forge::Check,
}

/// Why [`verify_forge`] or [`verify_forge_release_list`] refused a bundle.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ForgeError {
    /// The bundle or its statement did not verify.
    #[error(transparent)]
    Verify(#[from] Error),
    /// It verified, but not as the project the consumer expected.
    #[error(transparent)]
    Identity(#[from] forge::IdentityError),
}

/// What a bundle's statement claims, read by [`peek_unverified`] without
/// verifying anything. Nothing in it is established: an attacker can put
/// any project and version in a bundle. Use it only to decide how to
/// verify, such as whether a forge lookup is worth making, and take the
/// project and version from [`Verified`] afterwards.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Claimed {
    /// The statement's `predicateType`: [`crate::model::PREDICATE_TYPE`]
    /// for a release, [`crate::model::RELEASES_PREDICATE_TYPE`] for a
    /// release list.
    pub predicate_type: String,
    /// The project the statement names.
    pub project: String,
    /// The version it names; none for a release list.
    pub version: Option<String>,
}

/// Read the project and version a bundle's statement claims, **without
/// verifying the bundle**. The result is untrusted: see [`Claimed`].
/// Fails when the bundle is not a DSSE-wrapped in-toto statement or the
/// statement names no project.
pub fn peek_unverified(bundle: &str) -> Result<Claimed, Error> {
    #[derive(serde::Deserialize)]
    struct Peek {
        #[serde(rename = "predicateType")]
        predicate_type: String,
        predicate: PeekPredicate,
    }
    #[derive(serde::Deserialize)]
    struct PeekPredicate {
        project: String,
        version: Option<String>,
    }
    let payload = sigstore::peek_statement(bundle)?;
    let peek: Peek = serde_json::from_slice(&payload)?;
    let is_release = peek.predicate_type == crate::model::PREDICATE_TYPE;
    Ok(Claimed {
        predicate_type: peek.predicate_type,
        project: peek.predicate.project,
        version: peek.predicate.version.filter(|_| is_release),
    })
}

/// The policy to verify a forge project's bundle under: see
/// [`forge::policy`].
fn forge_policy(bundle: &str, expected: &forge::Expected<'_>) -> Result<Policy, ForgeError> {
    let payload = sigstore::peek_statement(bundle).map_err(Error::from)?;
    let peeked: serde_json::Value = serde_json::from_slice(&payload).map_err(Error::from)?;
    let signed = peeked["predicate"]["project"].as_str().unwrap_or_default();
    forge::policy(expected.project, signed)
        .ok_or_else(|| forge::IdentityError::NotForge(expected.project.to_string()).into())
}

/// Verify a GitHub or GitLab project's packslip under the policy its forge
/// implies, then check that it was signed by the repository the consumer
/// expected, by the forge's immutable repository ID where the certificate
/// and the consumer's pin or forge lookup give one ([`forge::check_source`]). A
/// renamed or transferred repository's releases verify under the new name,
/// and its older releases under the old one; a recreated name does not.
///
/// The caller still applies signer continuity, with
/// [`forge::Check::continues_signer`], and records
/// [`forge::Check::pin`] once it accepts the release.
pub fn verify_forge(
    bundle: &str,
    expected: &forge::Expected<'_>,
    options: Options<'_>,
    artifacts: &[&Path],
) -> Result<ForgeVerified<Verified>, ForgeError> {
    let policy = forge_policy(bundle, expected)?;
    let verified = verify(bundle, &Trust::Identity(&policy), options, artifacts)?;
    let source = sigstore::source_repository(bundle).map_err(Error::from)?;
    let check = forge::check_source(
        expected,
        &verified.project,
        &verified.key_id,
        verified.issuer.as_deref(),
        source.as_ref(),
    )?
    .declaring_pin_workflow(verified.pin_workflow);
    Ok(ForgeVerified { verified, check })
}

/// [`verify_forge`] for a forge project's supplementary release list.
pub fn verify_forge_release_list(
    bundle: &str,
    expected: &forge::Expected<'_>,
    options: Options<'_>,
) -> Result<ForgeVerified<VerifiedList>, ForgeError> {
    let policy = forge_policy(bundle, expected)?;
    let verified = verify_release_list(bundle, &Trust::Identity(&policy), options)?;
    let source = sigstore::source_repository(bundle).map_err(Error::from)?;
    let check = forge::check_source(
        expected,
        &verified.list.predicate.project,
        &verified.key_id,
        verified.issuer.as_deref(),
        source.as_ref(),
    )?
    .declaring_pin_workflow(verified.pin_workflow);
    Ok(ForgeVerified { verified, check })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::forge::{Continuity, Evidence, Expected, ForgePin, IdentityError, PinSource};

    /// jdx/hk's v2.3.0 packslip, as its release workflow published it.
    const HK: &str = include_str!("../tests/fixtures/hk-v2.3.0.sigstore.json");

    fn options(root: &TrustedRoot) -> Options<'_> {
        Options {
            require_log: true,
            trusted_root: root,
        }
    }

    #[test]
    fn a_published_certificate_records_the_repository_ids() {
        let source = sigstore::source_repository(HK).unwrap().unwrap();
        assert_eq!(source.uri, "https://github.com/jdx/hk");
        assert_eq!(source.id.as_deref(), Some("922514152"));
        assert_eq!(source.owner_uri.as_deref(), Some("https://github.com/jdx"));
        assert_eq!(source.owner_id.as_deref(), Some("216188"));
    }

    #[test]
    fn a_verified_report_lists_every_artifact_with_its_signed_digest() {
        let root = sigstore::trusted_root(None).unwrap();
        let ok =
            verify_forge(HK, &Expected::new("github.com/jdx/hk"), options(&root), &[]).unwrap();
        let report = &ok.verified;
        assert_eq!(report.artifacts.len(), report.artifact_count);
        let linux = report
            .artifacts
            .iter()
            .find(|a| a.artifact.name == "hk-x86_64-unknown-linux-gnu.tar.gz")
            .unwrap();
        assert_eq!(linux.artifact.os.as_deref(), Some("linux"));
        assert_eq!(linux.artifact.arch.as_deref(), Some("x86_64"));
        assert_eq!(linux.sha256.len(), 64);
        let json = serde_json::to_value(report).unwrap();
        let first = &json["artifacts"][0];
        assert!(first["name"].is_string() && first["sha256"].is_string());
        assert!(first["size"].is_u64());
    }

    #[cfg(feature = "schema")]
    #[test]
    fn the_report_schema_requires_only_fields_the_report_always_has() {
        let root = sigstore::trusted_root(None).unwrap();
        let ok =
            verify_forge(HK, &Expected::new("github.com/jdx/hk"), options(&root), &[]).unwrap();
        let report = serde_json::to_value(&ok.verified).unwrap();
        // hk pins its workflow, so `pin_workflow` is skipped in this report.
        assert!(report.get("pin_workflow").is_none());
        let schema = crate::verify_report_schema();
        for key in schema["required"].as_array().unwrap() {
            let key = key.as_str().unwrap();
            assert!(report.get(key).is_some(), "{key} is required but absent");
        }
        let artifact_schema = &schema["$defs"]["VerifiedArtifact"]["required"];
        for key in artifact_schema.as_array().unwrap() {
            let key = key.as_str().unwrap();
            assert!(report["artifacts"][0].get(key).is_some(), "{key} absent");
        }
    }

    #[test]
    fn a_published_release_verifies_by_repository_id() {
        let root = sigstore::trusted_root(None).unwrap();
        let ok =
            verify_forge(HK, &Expected::new("github.com/jdx/hk"), options(&root), &[]).unwrap();
        assert_eq!(ok.verified.project, "github.com/jdx/hk");
        assert_eq!(ok.check.continuity, Continuity::Same);
        let pin = ok.check.pin.clone().unwrap();
        assert_eq!(pin, ForgePin::of("github.com/jdx/hk", "922514152"));
        assert!(
            ok.check
                .continues_signer("https://github.com/jdx/hk/.github/workflows/release.yml")
        );

        // GitHub resolves jdx/HK as jdx/hk, so asking for it in another case
        // is asking for this project, with no pin or forge lookup needed.
        let ok =
            verify_forge(HK, &Expected::new("github.com/JDX/HK"), options(&root), &[]).unwrap();
        assert_eq!(ok.check.continuity, Continuity::Same);
        // So does an identity prefix, the policy a GitHub name implies; the
        // workflow's path inside the repository keeps its case.
        let prefix = |prefix: &str| Policy {
            issuer: Some(sigstore::GITHUB_ISSUER.into()),
            identity: None,
            identity_prefix: Some(prefix.into()),
        };
        let policy = prefix("https://github.com/JDX/HK/");
        assert!(verify(HK, &Trust::Identity(&policy), options(&root), &[]).is_ok());
        let policy = prefix("https://github.com/jdx/hk/.GITHUB/");
        assert!(matches!(
            verify(HK, &Trust::Identity(&policy), options(&root), &[]),
            Err(Error::Sigstore(sigstore::Error::IdentityPrefix { .. }))
        ));
        // So does a pinned identity, apart from the workflow's path and ref.
        let exact = |identity: &str| Policy {
            issuer: Some(sigstore::GITHUB_ISSUER.into()),
            identity: Some(identity.into()),
            identity_prefix: None,
        };
        let policy =
            exact("https://github.com/JDX/HK/.github/workflows/release.yml@refs/tags/v2.3.0");
        assert!(verify(HK, &Trust::Identity(&policy), options(&root), &[]).is_ok());
        let policy =
            exact("https://github.com/jdx/hk/.github/workflows/Release.yml@refs/tags/v2.3.0");
        assert!(matches!(
            verify(HK, &Trust::Identity(&policy), options(&root), &[]),
            Err(Error::Sigstore(sigstore::Error::Verification(_)))
        ));

        // Were hk renamed to hook, a user asking for the new name with the
        // pin would still take this release, signed under the old name.
        let pinned = ForgePin::of("github.com/jdx/hook", "922514152");
        let ok = verify_forge(
            HK,
            &Expected::new("github.com/jdx/hook").pinned(Some(&pinned)),
            options(&root),
            &[],
        )
        .unwrap();
        assert_eq!(
            ok.check.continuity,
            Continuity::Renamed {
                requested: "github.com/jdx/hook".into(),
                signed: "github.com/jdx/hk".into(),
            }
        );
        // Without the pin or a forge lookup, another name is refused.
        let err = verify_forge(
            HK,
            &Expected::new("github.com/jdx/hook"),
            options(&root),
            &[],
        )
        .unwrap_err();
        assert!(
            matches!(
                err,
                ForgeError::Identity(IdentityError::ProjectMismatch { .. })
            ),
            "{err}"
        );
        // A pin for another repository under the same name is a recreated name.
        let other = ForgePin::of("github.com/jdx/hk", "1");
        let err = verify_forge(
            HK,
            &Expected::new("github.com/jdx/hk").pinned(Some(&other)),
            options(&root),
            &[],
        )
        .unwrap_err();
        assert!(
            matches!(
                err,
                ForgeError::Identity(IdentityError::DifferentRepository {
                    evidence: Evidence::Pin,
                    ..
                })
            ),
            "{err}"
        );
        // A monorepo tool of the repository is not the repository.
        let err = verify_forge(
            HK,
            &Expected::new("github.com/jdx/hk/tool"),
            options(&root),
            &[],
        )
        .unwrap_err();
        assert!(
            matches!(
                err,
                ForgeError::Identity(IdentityError::ProjectMismatch { .. })
            ),
            "{err}"
        );
        // Only forge projects.
        let err = verify_forge(HK, &Expected::new("hk.jdx.dev"), options(&root), &[]).unwrap_err();
        assert!(
            matches!(err, ForgeError::Identity(IdentityError::NotForge(_))),
            "{err}"
        );
    }

    #[test]
    fn a_published_release_is_held_to_every_pin() {
        let root = sigstore::trusted_root(None).unwrap();
        let pins = [
            (
                PinSource::Local,
                ForgePin::of("github.com/jdx/hk", "922514152"),
            ),
            (PinSource::Lockfile, ForgePin::of("github.com/jdx/hk", "1")),
        ];
        let err = verify_forge(
            HK,
            &Expected::new("github.com/jdx/hk").pinned_by(&pins),
            options(&root),
            &[],
        )
        .unwrap_err();
        assert!(
            matches!(
                err,
                ForgeError::Identity(IdentityError::DifferentRepository {
                    evidence: Evidence::LockfilePin,
                    ..
                })
            ),
            "{err}"
        );
        let ok = verify_forge(
            HK,
            &Expected::new("github.com/jdx/hk").pinned_by(&pins[..1]),
            options(&root),
            &[],
        )
        .unwrap();
        assert_eq!(ok.check.continuity, Continuity::Same);
    }

    #[test]
    fn a_bundle_claims_a_project_before_it_is_verified() {
        let claimed = peek_unverified(HK).unwrap();
        assert_eq!(
            claimed,
            Claimed {
                predicate_type: crate::model::PREDICATE_TYPE.into(),
                project: "github.com/jdx/hk".into(),
                version: Some("2.3.0".into()),
            }
        );

        // The claim is whatever the statement says, signed or not: here a
        // release list for another project, under hk's signature.
        use base64::Engine as _;
        let mut bundle: serde_json::Value = serde_json::from_str(HK).unwrap();
        let list = serde_json::json!({
            "_type": crate::model::STATEMENT_TYPE,
            "subject": [],
            "predicateType": crate::model::RELEASES_PREDICATE_TYPE,
            "predicate": { "project": "github.com/evil/x", "version": "9.9.9" },
        });
        bundle["dsseEnvelope"]["payload"] = base64::engine::general_purpose::STANDARD
            .encode(list.to_string())
            .into();
        let forged = bundle.to_string();
        let claimed = peek_unverified(&forged).unwrap();
        assert_eq!(claimed.project, "github.com/evil/x");
        assert_eq!(claimed.version, None, "a release list has no version");
        let root = sigstore::trusted_root(None).unwrap();
        assert!(
            verify_forge_release_list(&forged, &Expected::new("github.com/evil/x"), options(&root))
                .is_err()
        );

        assert!(peek_unverified("not a bundle").is_err());
    }
}