packslip 1.11.2

A vendor-neutral signed release manifest: what shipped, and how to verify it
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
//! Signing and verification through sigstore. A packslip is a sigstore
//! bundle carrying the statement as an in-toto DSSE envelope. It is signed
//! either keylessly, with an ephemeral key certified by Fulcio for an OIDC
//! identity, or with a long-lived Ed25519 key; either way the signature is
//! logged to Rekor, and the bundle carries the log entry.

use base64::Engine as _;
use base64::engine::general_purpose::{STANDARD as BASE64, URL_SAFE_NO_PAD};
#[cfg(feature = "sign")]
use ed25519_dalek::Signer as _;
use sha2::Digest as _;
#[cfg(feature = "sign")]
use sigstore_bundle::{BundleV03, VerificationMaterialV03};
#[cfg(feature = "sign")]
use sigstore_oidc::IdentityToken;
#[cfg(feature = "sign")]
use sigstore_rekor::{DsseEntry, RekorClient};
#[cfg(feature = "sign")]
use sigstore_sign::SigningContext;
#[cfg(feature = "sign")]
use sigstore_trust_root::SigstoreInstance;
use sigstore_trust_root::{SIGSTORE_PRODUCTION_TRUSTED_ROOT, TrustedRoot};
use sigstore_types::{Artifact, Bundle, DerPublicKey, Sha256Hash, SignatureContent};
#[cfg(feature = "sign")]
use sigstore_types::{DsseEnvelope, DsseSignature, KeyId, PayloadBytes, SignatureBytes};
use sigstore_verify::VerificationPolicy;

#[cfg(feature = "sign")]
use crate::minisign::SecretKey;
use crate::minisign::{PublicKey, key_id_hex};

pub const GITHUB_ISSUER: &str = "https://token.actions.githubusercontent.com";
pub const GITLAB_ISSUER: &str = "https://gitlab.com";
/// The public-good Rekor log that key signatures are submitted to; keyless
/// signing takes its log from the instance's embedded signing config.
#[cfg(feature = "sign")]
const PUBLIC_REKOR_URL: &str = "https://rekor.sigstore.dev";
pub const IN_TOTO_PAYLOAD_TYPE: &str = "application/vnd.in-toto+json";

/// The environment variable a caller may set to hand over an OIDC token
/// directly, when no ambient CI credential is available.
pub const TOKEN_ENV: &str = "SIGSTORE_ID_TOKEN";

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(
        "no OIDC identity available: run inside a CI job with an id-token permission, or set {TOKEN_ENV}"
    )]
    NoIdentity,
    #[error("identity token: {0}")]
    Token(String),
    #[error("signing: {0}")]
    Sign(String),
    #[error("transparency log: {0}")]
    Log(String),
    #[error("bundle is not valid JSON: {0}")]
    BundleJson(String),
    #[error("bundle does not carry a DSSE envelope")]
    NotDsse,
    #[error("bundle payload type is {0:?}, expected {IN_TOTO_PAYLOAD_TYPE}")]
    PayloadType(String),
    #[error("bundle payload is not an in-toto statement: {0}")]
    Payload(String),
    #[error("trusted root: {0}")]
    TrustedRoot(String),
    #[error("bundle does not verify: {0}")]
    Verification(String),
    #[error("signature does not verify with the pinned key {0}")]
    BadKeySignature(String),
    #[error("bundle carries a certificate but a key was pinned; pin an identity instead")]
    KeyPinnedForCertificate,
    #[error("bundle carries a public key hint but an identity was pinned; pin the key instead")]
    IdentityPinnedForKey,
    #[error("signed by {actual:?}, expected an identity starting with {expected:?}")]
    IdentityPrefix { actual: String, expected: String },
    #[error("bundle has no transparency log entry; pass --allow-unlogged to accept one")]
    Unlogged,
    #[error(
        "no identity to verify against for {0:?}: pass --identity, --identity-prefix, or --issuer for a keyless release, or --pubkey for a key-signed one"
    )]
    NoPolicy(String),
    /// Like [`Error::NoPolicy`], for a command that has no key to pin.
    #[error(
        "no identity to verify against for {0:?}: pass --identity, --identity-prefix, or --issuer"
    )]
    NoIdentityPolicy(String),
}

#[cfg(feature = "sign")]
fn runtime() -> Result<tokio::runtime::Runtime, Error> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| Error::Sign(format!("tokio runtime: {e}")))
}

/// An OIDC identity ready to sign with, and what Fulcio will put in the
/// certificate for it.
#[cfg(feature = "sign")]
pub struct OidcIdentity {
    token: IdentityToken,
    /// The certificate subject identity: a workflow URI for CI, an email
    /// for a person.
    pub identity: String,
    pub issuer: String,
}

#[cfg(feature = "sign")]
impl std::fmt::Debug for OidcIdentity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OidcIdentity")
            .field("identity", &self.identity)
            .field("issuer", &self.issuer)
            .finish_non_exhaustive()
    }
}

#[cfg(feature = "sign")]
impl OidcIdentity {
    fn from_token(token: IdentityToken) -> Result<OidcIdentity, Error> {
        let identity = certificate_identity(token.expose_secret())?;
        Ok(OidcIdentity {
            issuer: token.issuer().to_string(),
            identity,
            token,
        })
    }
}

/// The identity from `SIGSTORE_ID_TOKEN`, or the ambient CI credential
/// (GitHub Actions, GitLab CI, Buildkite, and the others sigstore knows).
#[cfg(feature = "sign")]
pub fn ambient_identity() -> Result<OidcIdentity, Error> {
    if let Ok(raw) = std::env::var(TOKEN_ENV)
        && !raw.trim().is_empty()
    {
        let token = IdentityToken::from_jwt(raw.trim()).map_err(|e| Error::Token(e.to_string()))?;
        return OidcIdentity::from_token(token);
    }
    let rt = runtime()?;
    let detected = rt
        .block_on(IdentityToken::detect_ambient())
        .map_err(|e| Error::Token(e.to_string()))?;
    match detected {
        Some(token) => OidcIdentity::from_token(token),
        None => Err(Error::NoIdentity),
    }
}

/// What Fulcio writes as the certificate's subject for this token: for CI
/// tokens the workflow URI, otherwise the verified email or the subject.
pub fn certificate_identity(jwt: &str) -> Result<String, Error> {
    let payload = jwt
        .split('.')
        .nth(1)
        .ok_or_else(|| Error::Token("not a JWT".into()))?;
    let bytes = URL_SAFE_NO_PAD
        .decode(payload)
        .map_err(|_| Error::Token("payload is not base64url".into()))?;
    let claims: serde_json::Value =
        serde_json::from_slice(&bytes).map_err(|e| Error::Token(e.to_string()))?;
    let str_claim = |name: &str| claims.get(name).and_then(|v| v.as_str());
    let issuer = str_claim("iss").unwrap_or_default();
    if issuer == GITHUB_ISSUER
        && let Some(workflow) = str_claim("job_workflow_ref")
    {
        return Ok(format!("https://github.com/{workflow}"));
    }
    if let Some(ci_config) = str_claim("ci_config_ref_uri") {
        return Ok(format!("https://{ci_config}"));
    }
    if let Some(email) = str_claim("email")
        && claims
            .get("email_verified")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
    {
        return Ok(email.to_string());
    }
    str_claim("sub")
        .map(str::to_string)
        .ok_or_else(|| Error::Token("no sub claim".into()))
}

/// Who signs.
#[cfg(feature = "sign")]
pub enum Signer {
    /// Keyless, with an OIDC identity.
    Oidc(OidcIdentity),
    /// A long-lived Ed25519 key. With `log`, the signature is recorded in
    /// Rekor; without it the bundle carries no log entry and consumers
    /// must opt in to accept it.
    Key { key: SecretKey, log: bool },
}

#[cfg(feature = "sign")]
impl Signer {
    /// The `identity` block a document signed by this signer declares.
    pub fn identity(&self) -> crate::model::Identity {
        match self {
            Signer::Oidc(oidc) => crate::model::Identity {
                scheme: crate::model::Scheme::SigstoreOidc,
                key_id: oidc.identity.clone(),
                issuer: Some(oidc.issuer.clone()),
                pin_workflow: None,
            },
            Signer::Key { key, .. } => crate::model::Identity {
                scheme: crate::model::Scheme::SigstoreKey,
                key_id: key_id_hex(&key.public_key().key_id),
                issuer: None,
                pin_workflow: None,
            },
        }
    }
}

/// The Ed25519 public key as DER SubjectPublicKeyInfo, which is how
/// sigstore and Rekor want keys.
pub fn spki_der(key: &PublicKey) -> Vec<u8> {
    const PREFIX: [u8; 12] = [
        0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
    ];
    let mut der = PREFIX.to_vec();
    der.extend_from_slice(key.key.as_bytes());
    der
}

#[cfg(feature = "sign")]
fn spki_pem(key: &PublicKey) -> String {
    let b64 = BASE64.encode(spki_der(key));
    let mut pem = String::from("-----BEGIN PUBLIC KEY-----\n");
    for chunk in b64.as_bytes().chunks(64) {
        pem.push_str(std::str::from_utf8(chunk).unwrap_or_default());
        pem.push('\n');
    }
    pem.push_str("-----END PUBLIC KEY-----\n");
    pem
}

/// The key hint a bundle carries for a pinned key: base64 of the sha256
/// of the DER key, the convention cosign uses.
pub fn key_hint(key: &PublicKey) -> String {
    BASE64.encode(sha2::Sha256::digest(spki_der(key)))
}

/// Sign `statement` (the payload bytes) into a sigstore bundle, returned
/// as JSON.
#[cfg(feature = "sign")]
pub fn sign(signer: Signer, statement: &[u8]) -> Result<String, Error> {
    let rt = runtime()?;
    let bundle = match signer {
        Signer::Oidc(oidc) => {
            let context = SigningContext::from_embedded(SigstoreInstance::PublicGood)
                .map_err(|e| Error::Sign(e.to_string()))?;
            let signer = context.signer(oidc.token);
            rt.block_on(signer.sign_raw_statement(statement))
                .map_err(|e| Error::Sign(e.to_string()))?
        }
        Signer::Key { key, log } => {
            let pae = sigstore_types::pae(IN_TOTO_PAYLOAD_TYPE, statement);
            let signature = key.signing_key().sign(&pae);
            let envelope = DsseEnvelope::new(
                IN_TOTO_PAYLOAD_TYPE.to_string(),
                PayloadBytes::from_bytes(statement),
                DsseSignature::new(
                    SignatureBytes::from_bytes(&signature.to_bytes()),
                    KeyId::default(),
                ),
            );
            let public = key.public_key();
            let mut bundle = BundleV03::new(
                VerificationMaterialV03::PublicKey {
                    hint: key_hint(&public),
                },
                SignatureContent::DsseEnvelope(envelope.clone()),
            );
            if log {
                // sigstore-rekor builds a DSSE entry only from a certificate,
                // so a key-signed one is deserialized from its wire form.
                let entry: DsseEntry = serde_json::from_value(serde_json::json!({
                    "apiVersion": "0.0.1",
                    "kind": "dsse",
                    "spec": {
                        "proposedContent": {
                            "envelope": serde_json::to_string(&envelope)
                                .map_err(|e| Error::Sign(e.to_string()))?,
                            "verifiers": [BASE64.encode(spki_pem(&public))],
                        },
                    },
                }))
                .map_err(|e| Error::Sign(e.to_string()))?;
                let rekor =
                    RekorClient::new(PUBLIC_REKOR_URL).map_err(|e| Error::Log(e.to_string()))?;
                let log_entry = rt
                    .block_on(rekor.create_dsse_entry(entry))
                    .map_err(|e| Error::Log(e.to_string()))?;
                let entry = log_entry
                    .to_bundle_entry(sigstore_types::KindVersion::DsseV001)
                    .map_err(|e| Error::Log(e.to_string()))?;
                bundle = bundle.with_tlog_entry(entry);
            }
            bundle.into_bundle()
        }
    };
    bundle.to_json().map_err(|e| Error::Sign(e.to_string()))
}

/// Who a consumer accepts as a keyless signer.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Policy {
    /// The exact OIDC issuer, when pinned.
    pub issuer: Option<String>,
    /// The certificate identity, when pinned. A GitHub or GitLab
    /// repository's name in it matches in any ASCII case, as the forge
    /// resolves it; the rest of the identity, including a workflow's path
    /// and ref, matches exactly.
    pub identity: Option<String>,
    /// A prefix the certificate identity must start with, for pinning a
    /// repository rather than one workflow file and ref. A GitHub or GitLab
    /// repository's name in it matches in any ASCII case, as the forge
    /// resolves it; the rest of the prefix matches exactly.
    pub identity_prefix: Option<String>,
}

impl Policy {
    /// An identity-prefix policy for a project on a forge the tooling
    /// knows: `github.com/owner/repo` must be signed by a workflow of that
    /// repository through GitHub's issuer, and likewise for gitlab.com.
    /// That is narrower than what the name implies, which also accepts a
    /// reusable workflow of another repository when the certificate's
    /// source repository is the project's: verify under
    /// [`crate::forge::policy`] and then apply
    /// [`crate::forge::check_source`] for that, as
    /// [`crate::verify::verify_forge`] does.
    pub fn for_project(project: &str) -> Option<Policy> {
        // A GitHub project may name a tool inside a monorepo
        // (`github.com/owner/repo/tool`); the workflow that signs it
        // belongs to the repository, so only owner and repo form the pin.
        if let Some((host, owner, repo)) = crate::model::repository(project) {
            return Some(Policy {
                issuer: Some(GITHUB_ISSUER.into()),
                identity: None,
                identity_prefix: Some(format!("https://{host}/{owner}/{repo}/")),
            });
        }
        let (host, path) = project.split_once('/')?;
        if path.is_empty() || path.split('/').count() < 2 {
            return None;
        }
        match host {
            // GitLab subgroups make project paths arbitrary depth, so the
            // whole path is the pin and subpaths are not distinguished.
            "gitlab.com" => Some(Policy {
                issuer: Some(GITLAB_ISSUER.into()),
                identity: None,
                identity_prefix: Some(format!("https://gitlab.com/{path}//")),
            }),
            _ => None,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.issuer.is_none() && self.identity.is_none() && self.identity_prefix.is_none()
    }

    /// One line saying what the policy pins.
    pub fn describe(&self) -> String {
        let mut parts = Vec::new();
        if let Some(id) = &self.identity {
            parts.push(format!("identity {id}"));
        }
        if let Some(prefix) = &self.identity_prefix {
            parts.push(format!("identity under {prefix}"));
        }
        if let Some(issuer) = &self.issuer {
            parts.push(format!("issuer {issuer}"));
        }
        parts.join(", ")
    }
}

/// What the consumer pinned.
pub enum Trust<'a> {
    /// An identity policy for a keyless bundle.
    Identity(&'a Policy),
    /// A long-lived public key for a key-signed bundle.
    Key(&'a PublicKey),
}

impl Trust<'_> {
    /// One line saying what is pinned.
    pub fn describe(&self) -> String {
        match self {
            Trust::Identity(policy) => policy.describe(),
            Trust::Key(key) => format!("key {}", key_id_hex(&key.key_id)),
        }
    }
}

/// Who signed, as verification established it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SignedBy {
    /// A certificate identity and its issuer.
    Identity { identity: String, issuer: String },
    /// The pinned key, by minisign key id.
    Key { key_id: String },
}

/// What verifying a bundle established.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BundleVerified {
    /// The signed statement bytes, exactly as they were signed.
    pub statement: Vec<u8>,
    pub signed_by: SignedBy,
    /// When Rekor integrated the entry, as a Unix timestamp; none for an
    /// unlogged bundle a consumer chose to accept.
    pub integrated_time: Option<i64>,
}

/// Fulcio's Source Repository URI extension.
const SOURCE_REPOSITORY_URI: &str = "1.3.6.1.4.1.57264.1.12";
/// Fulcio's Source Repository Identifier extension: GitHub's
/// `repository_id`, GitLab's `project_id`.
const SOURCE_REPOSITORY_ID: &str = "1.3.6.1.4.1.57264.1.15";
/// Fulcio's Source Repository Owner URI extension.
const SOURCE_REPOSITORY_OWNER_URI: &str = "1.3.6.1.4.1.57264.1.16";
/// Fulcio's Source Repository Owner Identifier extension: GitHub's
/// `repository_owner_id`, GitLab's `namespace_id`.
const SOURCE_REPOSITORY_OWNER_ID: &str = "1.3.6.1.4.1.57264.1.17";

/// The repository a keyless signer's CI run was based on, as Fulcio
/// recorded it in the certificate from the forge's OIDC token.
///
/// A forge's numeric repository ID does not change when a repository is
/// renamed or transferred to another owner, so it tells the same repository
/// from a new one that took its old name. [`crate::forge::check`] compares
/// only that ID; the owner's fields describe who owned the repository when
/// the certificate was issued and are not part of a project's identity.
/// GitHub Actions and GitLab CI certificates carry all four fields;
/// certificates Fulcio issued before it recorded them, and those for other
/// identities, carry none.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct SourceRepository {
    /// The repository's URL when the certificate was issued:
    /// `https://github.com/owner/repo`.
    pub uri: String,
    /// The forge's immutable repository ID, a decimal string on GitHub and
    /// GitLab.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// The owner's URL when the certificate was issued:
    /// `https://github.com/owner`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner_uri: Option<String>,
    /// The forge's immutable ID of the repository's owner (a GitHub user or
    /// organization, a GitLab namespace).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner_id: Option<String>,
}

impl SourceRepository {
    /// A source repository with only its URL, as a certificate from before
    /// Fulcio recorded the IDs has. With [`SourceRepository::with_id`] and
    /// [`SourceRepository::with_owner`], it describes a certificate without
    /// one at hand, for a consumer's tests of [`crate::forge::check`].
    pub fn new(uri: impl Into<String>) -> SourceRepository {
        SourceRepository {
            uri: uri.into(),
            id: None,
            owner_uri: None,
            owner_id: None,
        }
    }

    /// With the forge's repository ID.
    pub fn with_id(self, id: impl Into<String>) -> SourceRepository {
        SourceRepository {
            id: Some(id.into()),
            ..self
        }
    }

    /// With the owner's URL (`https://github.com/owner`) and the forge's ID
    /// for it.
    pub fn with_owner(self, uri: impl Into<String>, id: impl Into<String>) -> SourceRepository {
        SourceRepository {
            owner_uri: Some(uri.into()),
            owner_id: Some(id.into()),
            ..self
        }
    }

    /// The source repository a DER certificate records, or none when it has
    /// no Source Repository URI extension. Verifies nothing.
    pub fn from_certificate(der: &[u8]) -> Result<Option<SourceRepository>, Error> {
        use x509_cert::der::Decode as _;
        use x509_cert::der::asn1::Utf8StringRef;
        use x509_cert::der::oid::ObjectIdentifier;

        let cert = x509_cert::Certificate::from_der(der)
            .map_err(|e| Error::Verification(format!("certificate does not parse: {e}")))?;
        let extensions = cert
            .tbs_certificate()
            .extensions()
            .map(Vec::as_slice)
            .unwrap_or_default();
        let value = |oid: &str| -> Result<Option<String>, Error> {
            let oid = ObjectIdentifier::new_unwrap(oid);
            let Some(ext) = extensions.iter().find(|e| e.extn_id == oid) else {
                return Ok(None);
            };
            // Fulcio encodes these as DER UTF8Strings inside the extension's
            // octet string. An empty value means the forge had none to give.
            let text = Utf8StringRef::from_der(ext.extn_value.as_bytes()).map_err(|e| {
                Error::Verification(format!("certificate extension {oid} is malformed: {e}"))
            })?;
            Ok(Some(text.as_str().to_string()).filter(|s| !s.is_empty()))
        };
        let Some(uri) = value(SOURCE_REPOSITORY_URI)? else {
            return Ok(None);
        };
        Ok(Some(SourceRepository {
            uri,
            id: value(SOURCE_REPOSITORY_ID)?,
            owner_uri: value(SOURCE_REPOSITORY_OWNER_URI)?,
            owner_id: value(SOURCE_REPOSITORY_OWNER_ID)?,
        }))
    }
}

/// The source repository the signing certificate in a bundle records:
/// none for a key-signed bundle or a certificate without the extensions.
/// Verifies nothing. It may filter discovery candidates, but establishes no
/// authority: authenticate the bundle before trusting the returned identity.
/// [`crate::verify::verify_forge`] does both.
pub fn source_repository(bundle_json: &str) -> Result<Option<SourceRepository>, Error> {
    let bundle = Bundle::from_json(bundle_json).map_err(|e| Error::BundleJson(e.to_string()))?;
    match bundle.signing_certificate() {
        Some(cert) => SourceRepository::from_certificate(cert.as_bytes()),
        None => Ok(None),
    }
}

/// The trusted root: a file's contents, or the production root embedded in
/// this build.
pub fn trusted_root(json: Option<&str>) -> Result<TrustedRoot, Error> {
    TrustedRoot::from_json(json.unwrap_or(SIGSTORE_PRODUCTION_TRUSTED_ROOT))
        .map_err(|e| Error::TrustedRoot(e.to_string()))
}

/// The statement bytes inside a bundle, without verifying anything. For
/// `show`, and for deciding what to pin before verifying.
pub fn peek_statement(bundle_json: &str) -> Result<Vec<u8>, Error> {
    let bundle = Bundle::from_json(bundle_json).map_err(|e| Error::BundleJson(e.to_string()))?;
    let SignatureContent::DsseEnvelope(envelope) = &bundle.content else {
        return Err(Error::NotDsse);
    };
    if envelope.payload_type != IN_TOTO_PAYLOAD_TYPE {
        return Err(Error::PayloadType(envelope.payload_type.clone()));
    }
    Ok(envelope.payload.as_bytes().to_vec())
}

/// Verify a bundle against what the consumer pinned, requiring a Rekor
/// entry unless `require_log` is off. Returns the signed statement bytes.
///
/// For an identity: the certificate chains to the trusted root and was
/// valid when the log recorded the entry, the entry is in the log, the
/// DSSE signature checks out, and the signer satisfies the policy. For a
/// key: the DSSE signature checks out with that key, and the log entry, if
/// present or required, is verified against the trusted root.
pub fn verify(
    bundle_json: &str,
    trust: &Trust<'_>,
    require_log: bool,
    trusted_root: &TrustedRoot,
) -> Result<BundleVerified, Error> {
    let bundle = Bundle::from_json(bundle_json).map_err(|e| Error::BundleJson(e.to_string()))?;
    let SignatureContent::DsseEnvelope(envelope) = &bundle.content else {
        return Err(Error::NotDsse);
    };
    if envelope.payload_type != IN_TOTO_PAYLOAD_TYPE {
        return Err(Error::PayloadType(envelope.payload_type.clone()));
    }
    let statement = envelope.payload.as_bytes().to_vec();
    // sigstore binds a DSSE bundle to an artifact by subject digest; the
    // statement's own first subject is that artifact. The caller checks
    // the statement's contents and any real files afterwards.
    let parsed: serde_json::Value =
        serde_json::from_slice(&statement).map_err(|e| Error::Payload(e.to_string()))?;
    let first = parsed["subject"][0]["digest"]["sha256"]
        .as_str()
        .ok_or_else(|| Error::Payload("no subject with a sha256".into()))?;
    let digest = Sha256Hash::from_hex(first).map_err(|e| Error::Payload(e.to_string()))?;
    let artifact = Artifact::from_digest(digest);
    let logged = !bundle.verification_material.tlog_entries.is_empty();
    if require_log && !logged {
        return Err(Error::Unlogged);
    }
    let has_certificate = bundle.signing_certificate().is_some();

    match trust {
        Trust::Identity(policy) => {
            if !has_certificate {
                return Err(Error::IdentityPinnedForKey);
            }
            let mut verification = VerificationPolicy::any_identity();
            if !require_log {
                verification = verification.skip_tlog_unsafe();
            }
            if let Some(issuer) = &policy.issuer {
                verification = verification.require_issuer(issuer.clone());
            }
            let result = sigstore_verify::verify(artifact, &bundle, &verification, trusted_root)
                .map_err(|e| Error::Verification(e.to_string()))?;
            let identity = result
                .identity()
                .map(|identity| identity.as_str().to_owned())
                .ok_or_else(|| Error::Verification("certificate has no subject identity".into()))?;
            let issuer = result
                .issuer()
                .map(str::to_owned)
                .ok_or_else(|| Error::Verification("certificate has no issuer".into()))?;
            // A GitHub or GitLab repository's name compares without regard
            // to case, as the forge resolves it, so packslip compares the
            // pinned identity itself rather than sigstore's exact match.
            if let Some(expected) = &policy.identity
                && !crate::forge::same_url(&identity, expected)
            {
                return Err(Error::Verification(format!(
                    "identity mismatch: expected {expected}, got {identity}"
                )));
            }
            if let Some(prefix) = &policy.identity_prefix
                && !crate::forge::identity_has_prefix(&identity, prefix)
            {
                return Err(Error::IdentityPrefix {
                    actual: identity,
                    expected: prefix.clone(),
                });
            }
            Ok(BundleVerified {
                statement,
                signed_by: SignedBy::Identity { identity, issuer },
                integrated_time: result.integrated_time().map(|t| t.as_second()),
            })
        }
        Trust::Key(key) => {
            if has_certificate {
                return Err(Error::KeyPinnedForCertificate);
            }
            let key_id = key_id_hex(&key.key_id);
            // The signature itself, with our own key type.
            let pae = envelope.pae();
            let ok = <[u8; 64]>::try_from(envelope.signature.sig.as_bytes())
                .ok()
                .map(|b| ed25519_dalek::Signature::from_bytes(&b))
                .is_some_and(|sig| ed25519_dalek::Verifier::verify(&key.key, &pae, &sig).is_ok());
            if !ok {
                return Err(Error::BadKeySignature(key_id));
            }
            // The log entry, when there is one: inclusion, checkpoint, and
            // consistency with the envelope, by sigstore's verifier.
            let integrated_time = if logged {
                let der = DerPublicKey::from_bytes(&spki_der(key));
                let result = sigstore_verify::verify(
                    artifact,
                    &bundle,
                    &sigstore_verify::PublicKeyVerificationPolicy::new(der),
                    trusted_root,
                )
                .map_err(|e| Error::Verification(e.to_string()))?;
                result.integrated_time().map(|t| t.as_second())
            } else {
                None
            };
            Ok(BundleVerified {
                statement,
                signed_by: SignedBy::Key { key_id },
                integrated_time,
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn jwt(claims: serde_json::Value) -> String {
        let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"RS256","typ":"JWT"}"#);
        let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
        format!("{header}.{payload}.sig")
    }

    #[test]
    fn github_actions_identity_is_the_workflow_uri() {
        let token = jwt(serde_json::json!({
            "iss": GITHUB_ISSUER,
            "sub": "repo:jdx/mise:ref:refs/tags/v1.0.0",
            "job_workflow_ref": "jdx/mise/.github/workflows/release.yml@refs/tags/v1.0.0",
            "aud": "sigstore", "exp": 4102444800u64,
        }));
        assert_eq!(
            certificate_identity(&token).unwrap(),
            "https://github.com/jdx/mise/.github/workflows/release.yml@refs/tags/v1.0.0"
        );
        let email = jwt(serde_json::json!({
            "iss": "https://accounts.google.com", "sub": "123",
            "email": "me@example.com", "email_verified": true,
            "aud": "sigstore", "exp": 4102444800u64,
        }));
        assert_eq!(certificate_identity(&email).unwrap(), "me@example.com");
        let unverified = jwt(serde_json::json!({
            "iss": "https://x", "sub": "123", "email": "me@example.com",
            "aud": "sigstore", "exp": 4102444800u64,
        }));
        assert_eq!(certificate_identity(&unverified).unwrap(), "123");
        assert!(certificate_identity("garbage").is_err());
    }

    #[test]
    fn forge_projects_imply_a_policy() {
        let p = Policy::for_project("github.com/jdx/mise").unwrap();
        assert_eq!(p.issuer.as_deref(), Some(GITHUB_ISSUER));
        assert_eq!(
            p.identity_prefix.as_deref(),
            Some("https://github.com/jdx/mise/")
        );
        let sub = Policy::for_project("github.com/oxc-project/oxc/oxlint").unwrap();
        assert_eq!(
            sub.identity_prefix.as_deref(),
            Some("https://github.com/oxc-project/oxc/")
        );
        assert!(Policy::for_project("mise.jdx.dev").is_none());
        assert!(Policy::for_project("github.com/jdx").is_none());
        assert!(Policy::for_project("gitlab.com/group/proj").is_some());
        assert_eq!(
            p.describe(),
            "identity under https://github.com/jdx/mise/, issuer https://token.actions.githubusercontent.com"
        );
    }

    #[test]
    fn a_certificate_that_does_not_parse_is_an_error() {
        assert!(matches!(
            SourceRepository::from_certificate(b"not a certificate"),
            Err(Error::Verification(_))
        ));
    }

    #[test]
    fn embedded_trusted_root_parses() {
        trusted_root(None).unwrap();
    }

    #[test]
    #[cfg(feature = "sign")]
    fn key_signed_bundles_round_trip_unlogged() {
        let root = trusted_root(None).unwrap();
        let key = SecretKey::from_seed([7u8; 32]);
        let statement = br#"{"_type":"https://in-toto.io/Statement/v1","subject":[{"name":"a","digest":{"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}],"predicateType":"x","predicate":{}}"#;
        let bundle = sign(
            Signer::Key {
                key: key.clone(),
                log: false,
            },
            statement,
        )
        .unwrap();
        assert!(bundle.contains("\"publicKey\""), "{bundle}");
        assert_eq!(peek_statement(&bundle).unwrap(), statement);
        assert_eq!(source_repository(&bundle).unwrap(), None);

        let public = key.public_key();
        let err = verify(&bundle, &Trust::Key(&public), true, &root).unwrap_err();
        assert!(matches!(err, Error::Unlogged), "{err}");
        let ok = verify(&bundle, &Trust::Key(&public), false, &root).unwrap();
        assert_eq!(ok.statement, statement);
        assert_eq!(
            ok.signed_by,
            SignedBy::Key {
                key_id: key_id_hex(&public.key_id)
            }
        );
        assert_eq!(ok.integrated_time, None);

        let other = SecretKey::from_seed([8u8; 32]).public_key();
        let err = verify(&bundle, &Trust::Key(&other), false, &root).unwrap_err();
        assert!(matches!(err, Error::BadKeySignature(_)), "{err}");
        let err = verify(&bundle, &Trust::Identity(&Policy::default()), false, &root).unwrap_err();
        assert!(matches!(err, Error::IdentityPinnedForKey), "{err}");

        let tampered = bundle.replace("\"payload\":\"", "\"payload\":\"e");
        assert!(verify(&tampered, &Trust::Key(&public), false, &root).is_err());
        assert!(matches!(
            verify("nope", &Trust::Key(&public), false, &root).unwrap_err(),
            Error::BundleJson(_)
        ));
    }

    #[test]
    #[cfg(feature = "sign")]
    fn spki_and_hint_are_stable() {
        let key = SecretKey::from_seed([1u8; 32]).public_key();
        let der = spki_der(&key);
        assert_eq!(der.len(), 44);
        assert_eq!(&der[12..], key.key.as_bytes());
        assert_eq!(key_hint(&key).len(), 44);
        assert!(spki_pem(&key).starts_with("-----BEGIN PUBLIC KEY-----\n"));
    }
}