sigstore 0.14.0

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

//! Structs providing cosign verification capabilities
//!
//! The focus of this crate is to provide the verification capabilities of cosign,
//! not the signing one.
//!
//! Sigstore verification can be done using [`sigstore::cosign::Client`](crate::cosign::client::Client).
//! Instances of this struct can be created via the [`sigstore::cosign::ClientBuilder`](crate::cosign::client_builder::ClientBuilder).
//!
//! ## What is currently supported
//!
//! The crate implements the following verification mechanisms:
//!
//!   * Verify using a given key
//!   * Verify bundle produced by transparency log (Rekor)
//!   * Verify signature produced in keyless mode, using Fulcio Web-PKI
//!
//! Signature annotations and certificate email can be provided at verification time.
//!
//! ## Unit testing inside of our own libraries
//!
//! In case you want to mock sigstore interactions inside of your own code, you
//! can implement the [`CosignCapabilities`] trait inside of your test suite.

use std::collections::BTreeMap;

use async_trait::async_trait;
use tracing::warn;

use crate::errors::{Result, SigstoreApplicationConstraintsError, SigstoreVerifyConstraintsError};
use crate::registry::{Auth, PushResponse};

use crate::crypto::{CosignVerificationKey, Signature};
use crate::errors::SigstoreError;
use pkcs8::der::Decode;
use x509_cert::Certificate;

pub mod bundle;
pub mod bundle_content;
pub(crate) mod constants;
pub(crate) mod intoto;
pub mod signature_layers;
pub use signature_layers::SignatureLayer;

pub mod client;
pub use self::client::Client;

pub mod client_builder;
pub use self::client_builder::ClientBuilder;

pub mod verification_constraint;
pub use self::constraint::{Constraint, SignConstraintRefVec};
use self::verification_constraint::{VerificationConstraint, VerificationConstraintRefVec};

pub mod payload;
use crate::registry::oci_reference::OciReference;
pub use payload::simple_signing;

pub mod constraint;

#[async_trait]
/// Cosign Abilities that have to be implemented by a
/// Cosign client
pub trait CosignCapabilities {
    /// Calculate the cosign image reference.
    /// This is the location cosign stores signatures.
    async fn triangulate(
        &mut self,
        image: &OciReference,
        auth: &Auth,
    ) -> Result<(OciReference, String)>;

    /// Returns the list of [`SignatureLayer`]
    /// objects associated with the given image, checking both the cosign
    /// SimpleSigning (`.sig` tag) format and the Sigstore Bundle (OCI referrers)
    /// format transparently.
    ///
    /// Triangulation is performed internally: the caller only needs to supply
    /// the original image reference.  Both signature sources are attempted;
    /// individual failures are logged as warnings.  Returns an empty vector
    /// when no layers are found from either source.
    ///
    /// Each layer is verified to ensure it contains legitimate data.
    ///
    /// ## Layers with embedded certificate
    ///
    /// A signature can contain a certificate, this happens when signatures
    /// are produced in keyless mode or when a PKCS11 tokens are used.
    ///
    /// The certificate is added to [`SignatureLayer::certificate_signature`]
    /// only when it can be trusted.
    ///
    /// In order to trust an embedded certificate, the following prerequisites
    /// must be satisfied:
    ///
    /// * The [`sigstore::cosign::Client`](crate::cosign::client::Client) must
    ///   have been created with Rekor integration enabled (see [`crate::trust::sigstore::ManualTrustRoot`])
    /// * The [`sigstore::cosign::Client`](crate::cosign::client::Client) must
    ///   have been created with Fulcio integration enabled (see [`crate::trust::sigstore::ManualTrustRoot`])
    /// * The layer must include a bundle produced by Rekor
    ///
    /// > Note well: the [`trust::sigstore`](crate::trust::sigstore) module provides helper structs and methods
    /// > to obtain this data from the official TUF repository of the Sigstore project.
    ///
    /// When the embedded certificate cannot be verified, [`SignatureLayer::certificate_signature`]
    /// is going to be `None`.
    ///
    /// ## Usage
    ///
    /// These returned objects can then be verified against
    /// [`VerificationConstraints`](crate::cosign::verification_constraint::VerificationConstraint)
    /// using the [`verify_constraints`] function.
    ///
    /// ## Image reference formats
    ///
    /// `source_image` may be either a tag reference (e.g. `registry/repo:tag`)
    /// or a digest reference (e.g. `registry/repo@sha256:...`). Triangulation
    /// is performed internally by issuing a `HEAD` request against the registry,
    /// which works for both forms: digest references simply cause the registry to
    /// echo back the same digest in the response header.
    async fn trusted_signature_layers(
        &mut self,
        auth: &Auth,
        source_image: &OciReference,
    ) -> Result<Vec<SignatureLayer>>;

    /// Push [`SignatureLayer`] objects to the registry. This function will do
    /// the following steps:
    /// * Generate a series of [`oci_client::client::ImageLayer`]s due to
    /// the given [`Vec<SignatureLayer>`].
    /// * Generate a `OciImageManifest` of [`oci_client::manifest::OciManifest`]
    /// due to the given `source_image_digest` and `signature_layers`. It supports
    /// to be extended when newly published
    /// [Referrers API of OCI Registry v1.1.0](https://github.com/opencontainers/distribution-spec/blob/v1.1.0-rc1/spec.md#listing-referrers),
    /// is prepared. At that time,
    /// [an artifact manifest](https://github.com/opencontainers/image-spec/blob/v1.1.0-rc2/artifact.md)
    /// will be created instead of [an image manifest](https://github.com/opencontainers/image-spec/blob/v1.1.0-rc2/manifest.md).
    /// * Push the generated manifest together with the layers
    /// to the `target_reference`. `target_reference` contains information
    /// about the registry, repository and tag.
    ///
    /// The parameters:
    /// - `annotations`: annotations of the generated manifest
    /// - `auth`: Credential used to access the registry
    /// - `target_reference`: target reference to push the manifest
    /// - `signature_layers`: [`SignatureLayer`] objects containing signature information
    async fn push_signature(
        &mut self,
        annotations: Option<BTreeMap<String, String>>,
        auth: &Auth,
        target_reference: &OciReference,
        signature_layers: Vec<SignatureLayer>,
    ) -> Result<PushResponse>;

    /// Verifies the signature produced by cosign when signing the given blob via the `cosign sign-blob` command
    ///
    /// The parameters:
    /// * `cert`: a PEM encoded x509 certificate that contains the public key used to verify the signature.
    ///   Note that cert is not double-base64-encoded like the output of sigstore/cosign is.
    /// * `signature`: the base64 encoded signature of the blob that has to be verified
    /// * `blob`: the contents of the blob
    ///
    /// This function returns `Ok())` when the given signature has been verified, otherwise returns an `Err`.
    fn verify_blob(cert: &str, signature: &str, blob: &[u8]) -> Result<()> {
        let pem = pem::parse(cert)?;
        let cert = Certificate::from_der(pem.contents()).map_err(|e| {
            SigstoreError::CertificateParsingError(format!("parse der into cert failed: {e}"))
        })?;
        let spki = cert.tbs_certificate.subject_public_key_info;
        let ver_key = CosignVerificationKey::try_from(&spki)?;
        let signature = Signature::Base64Encoded(signature.as_bytes());
        ver_key.verify_signature(signature, blob)?;
        Ok(())
    }

    ///
    /// Verifies the signature produced by cosign when signing the given blob via the `cosign sign-blob` command
    ///
    /// The parameters:
    /// * `public_key`: the public key used to verify the signature, PEM encoded
    /// * `signature`: the base64 encoded signature of the blob that has to be verified
    /// * `blob`: the contents of the blob
    ///
    /// This function returns `Ok())` when the given signature has been verified, otherwise returns an `Err`.
    fn verify_blob_with_public_key(public_key: &str, signature: &str, blob: &[u8]) -> Result<()> {
        let ver_key = CosignVerificationKey::try_from_pem(public_key.as_bytes())?;
        let signature = Signature::Base64Encoded(signature.as_bytes());
        ver_key.verify_signature(signature, blob)?;
        Ok(())
    }
}

/// Given a list of trusted `SignatureLayer`, find all the constraints that
/// aren't satisfied by the layers.
///
/// If there's any unsatisfied constraints it means that the image failed
/// verification.
/// If there's no unsatisfied constraints it means that the image passed
/// verification.
///
/// Returns a `Result` with either `Ok()` for passed verification or
/// [`SigstoreVerifyConstraintsError`]
/// which contains a vector of references to unsatisfied constraints.
///
/// See the documentation of the [`cosign::verification_constraint`](crate::cosign::verification_constraint) module for more
/// details about how to define verification constraints.
pub fn verify_constraints<'a, 'b, I>(
    signature_layers: &'a [SignatureLayer],
    constraints: I,
) -> std::result::Result<(), SigstoreVerifyConstraintsError<'b>>
where
    I: Iterator<Item = &'b Box<dyn VerificationConstraint>>,
{
    let unsatisfied_constraints: VerificationConstraintRefVec = constraints.filter(|c| {
        let mut is_c_unsatisfied = true;
        signature_layers.iter().any( | sl | {
            // iterate through all layers and find if at least one layer
            // satisfies constraint. If so, we stop iterating
            match c.verify(sl) {
                Ok(is_sl_verified) => {
                    is_c_unsatisfied = !is_sl_verified;
                    is_sl_verified // if true, stop searching
                }
                Err(e) => {
                    warn!(error = ?e, constraint = ?c, "Skipping layer because constraint verification returned an error");
                    // handle errors as verification failures
                    is_c_unsatisfied = true;
                    false // keep searching to see if other layer satisfies
                }
            }
        });
        is_c_unsatisfied // if true, constraint gets filtered into result
    }).collect();

    if unsatisfied_constraints.is_empty() {
        Ok(())
    } else {
        Err(SigstoreVerifyConstraintsError {
            unsatisfied_constraints,
        })
    }
}

/// Given a [`SignatureLayer`], apply all the constraints to that.
///
/// If there's any constraints that fails to apply, it means the
/// application process fails.
/// If all constraints succeed applying, it means that this layer
/// passes applying constraints process.
///
/// Returns a `Result` with either `Ok()` for success or
/// [`SigstoreApplicationConstraintsError`]
/// which contains a vector of references to unapplied constraints.
///
/// See the documentation of the [`cosign::constraint`](crate::cosign::constraint) module for more
/// details about how to define constraints.
pub fn apply_constraints<'a, 'b, I>(
    signature_layer: &'a mut SignatureLayer,
    constraints: I,
) -> std::result::Result<(), SigstoreApplicationConstraintsError<'b>>
where
    I: Iterator<Item = &'b Box<dyn Constraint>>,
{
    let unapplied_constraints: SignConstraintRefVec = constraints
        .filter(|c| match c.add_constraint(signature_layer) {
            Ok(is_applied) => !is_applied,
            Err(e) => {
                warn!(error = ?e, constraint = ?c, "Applying constraint failed due to error");
                true
            }
        })
        .collect();

    if unapplied_constraints.is_empty() {
        Ok(())
    } else {
        Err(SigstoreApplicationConstraintsError {
            unapplied_constraints,
        })
    }
}

#[cfg(test)]
mod tests {
    use pki_types::CertificateDer;
    use serde_json::json;

    use super::constraint::{AnnotationMarker, PrivateKeySigner};
    use super::verification_constraint::cert_subject_email_verifier::StringVerifier;
    use super::*;
    use crate::cosign::signature_layers::CertificateSubject;
    use crate::cosign::signature_layers::tests::build_correct_signature_layer_with_certificate;
    use crate::cosign::simple_signing::Optional;
    use crate::cosign::verification_constraint::{
        AnnotationVerifier, CertSubjectEmailVerifier, VerificationConstraintVec,
    };
    use crate::crypto::SigningScheme;
    use crate::crypto::certificate_pool::CertificatePool;

    #[cfg(feature = "test-registry")]
    use testcontainers::{core::WaitFor, runners::AsyncRunner};

    #[cfg(feature = "test-remote-registry")]
    mod remote_registry {
        use crate::cosign::verification_constraint::CertSubjectUrlVerifier;
        use crate::cosign::verification_constraint::VerificationConstraintVec;
        use crate::cosign::{Client, ClientBuilder, CosignCapabilities, verify_constraints};
        use crate::registry::Auth;
        use crate::trust::sigstore::SigstoreTrustRoot;

        // These tests verify against real images hosted on ghcr.io that cover all
        // three signature scenarios supported by `trusted_signature_layers`:
        //
        //   - SimpleSigning only  (.sig tag, no OCI referrer bundle)
        //   - Sigstore Bundle only (OCI referrers, no .sig tag)
        //   - Both formats present (layers from both paths must be returned)
        //
        // Run with:  cargo test --features test-remote-registry

        const KUBEWARDEN_CONTROLLER_IMAGE: &str = "ghcr.io/kubewarden/kubewarden-controller";
        const GITHUB_ACTIONS_OIDC_ISSUER: &str = "https://token.actions.githubusercontent.com";

        async fn build_remote_cosign_client() -> Client {
            let trust_root = SigstoreTrustRoot::new(None)
                .await
                .expect("failed to fetch Sigstore trust root");
            ClientBuilder::default()
                .with_trust_repository(&trust_root)
                .expect("failed to configure trust repository")
                .build()
                .expect("failed to build cosign client")
        }

        /// Verify an image signed **only** with a Sigstore Bundle (OCI referrers).
        /// No SimpleSigning `.sig` tag exists for this image, so all returned layers
        /// must come from the Sigstore Bundle path.
        #[tokio::test]
        async fn verify_sigstore_bundle_only() {
            let mut client = build_remote_cosign_client().await;

            let image = format!("{KUBEWARDEN_CONTROLLER_IMAGE}:v1.30.0-rc1")
                .parse()
                .expect("failed to parse image reference");

            let layers = client
                .trusted_signature_layers(&Auth::Anonymous, &image)
                .await
                .expect("failed to get trusted signature layers");

            assert_eq!(
                layers.len(),
                1,
                "expected exactly 1 signature layer from Sigstore Bundle path"
            );
            assert!(
                layers[0].certificate_signature.is_some(),
                "expected certificate_signature to be present (Fulcio validation passed)"
            );

            let vc = CertSubjectUrlVerifier {
                url: "https://github.com/kubewarden/kubewarden-controller/.github/workflows/release.yml@refs/tags/v1.30.0-rc1".to_string(),
                issuer: GITHUB_ACTIONS_OIDC_ISSUER.to_string(),
            };
            let constraints: VerificationConstraintVec = vec![Box::new(vc)];
            verify_constraints(&layers, constraints.iter())
                .expect("verification constraints should be satisfied");
        }

        /// Verify an image signed **only** with SimpleSigning (`.sig` tag).
        /// No OCI referrer bundle exists for this image, so all returned layers
        /// must come from the SimpleSigning path.
        #[tokio::test]
        async fn verify_simple_signing_only() {
            let mut client = build_remote_cosign_client().await;

            let image = format!("{KUBEWARDEN_CONTROLLER_IMAGE}:v1.29.0-rc1")
                .parse()
                .expect("failed to parse image reference");

            let layers = client
                .trusted_signature_layers(&Auth::Anonymous, &image)
                .await
                .expect("failed to get trusted signature layers");

            assert_eq!(
                layers.len(),
                1,
                "expected exactly 1 signature layer from SimpleSigning path"
            );
            assert!(
                layers[0].certificate_signature.is_some(),
                "expected certificate_signature to be present (Fulcio validation passed)"
            );

            let vc = CertSubjectUrlVerifier {
                url: "https://github.com/kubewarden/kubewarden-controller/.github/workflows/release.yml@refs/tags/v1.29.0-rc1".to_string(),
                issuer: GITHUB_ACTIONS_OIDC_ISSUER.to_string(),
            };
            let constraints: VerificationConstraintVec = vec![Box::new(vc)];
            verify_constraints(&layers, constraints.iter())
                .expect("verification constraints should be satisfied");
        }

        /// Verify an image signed with **both** SimpleSigning (`.sig` tag) and
        /// Sigstore Bundle (OCI referrers). `trusted_signature_layers` must return
        /// exactly 2 layers — one from each path.
        #[tokio::test]
        async fn verify_both_simple_signing_and_sigstore_bundle() {
            let mut client = build_remote_cosign_client().await;

            let image = format!("{KUBEWARDEN_CONTROLLER_IMAGE}:v1.31.0-rc1")
                .parse()
                .expect("failed to parse image reference");

            let layers = client
                .trusted_signature_layers(&Auth::Anonymous, &image)
                .await
                .expect("failed to get trusted signature layers");

            assert_eq!(
                layers.len(),
                2,
                "expected exactly 2 signature layers (one from SimpleSigning, one from Sigstore Bundle)"
            );
            for layer in &layers {
                assert!(
                    layer.certificate_signature.is_some(),
                    "expected certificate_signature to be present on all layers (Fulcio validation passed)"
                );
            }

            let vc = CertSubjectUrlVerifier {
                url: "https://github.com/kubewarden/kubewarden-controller/.github/workflows/release.yml@refs/tags/v1.31.0-rc1".to_string(),
                issuer: GITHUB_ACTIONS_OIDC_ISSUER.to_string(),
            };
            let constraints: VerificationConstraintVec = vec![Box::new(vc)];
            verify_constraints(&layers, constraints.iter())
                .expect("verification constraints should be satisfied");
        }
    }

    pub(crate) const REKOR_PUB_KEY: &str = r#"-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwr
kBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==
-----END PUBLIC KEY-----"#;

    pub(crate) const REKOR_PUB_KEY_ID: &str =
        "c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d";

    const FULCIO_CRT_1_PEM: &str = r#"-----BEGIN CERTIFICATE-----
MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAq
MRUwEwYDVQQKEwxzaWdzdG9yZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIx
MDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UEChMMc2lnc3RvcmUu
ZGV2MREwDwYDVQQDEwhzaWdzdG9yZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLSy
A7Ii5k+pNO8ZEWY0ylemWDowOkNa3kL+GZE5Z5GWehL9/A9bRNA3RbrsZ5i0Jcas
taRL7Sp5fp/jD5dxqc/UdTVnlvS16an+2Yfswe/QuLolRUCrcOE2+2iA5+tzd6Nm
MGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYE
FMjFHQBBmiQpMlEk6w2uSu1KBtPsMB8GA1UdIwQYMBaAFMjFHQBBmiQpMlEk6w2u
Su1KBtPsMAoGCCqGSM49BAMDA2gAMGUCMH8liWJfMui6vXXBhjDgY4MwslmN/TJx
Ve/83WrFomwmNf056y1X48F9c4m3a3ozXAIxAKjRay5/aj/jsKKGIkmQatjI8uup
Hr/+CxFvaJWmpYqNkLDGRU+9orzh5hI2RrcuaQ==
-----END CERTIFICATE-----"#;

    const FULCIO_CRT_2_PEM: &str = r#"-----BEGIN CERTIFICATE-----
MIIB9zCCAXygAwIBAgIUALZNAPFdxHPwjeDloDwyYChAO/4wCgYIKoZIzj0EAwMw
KjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0y
MTEwMDcxMzU2NTlaFw0zMTEwMDUxMzU2NThaMCoxFTATBgNVBAoTDHNpZ3N0b3Jl
LmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7
XeFT4rb3PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxex
X69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92j
YzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRY
wB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQ
KsXF+jAKBggqhkjOPQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCM
WP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/VtWB5b9
TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ
-----END CERTIFICATE-----"#;

    #[cfg(feature = "test-registry")]
    const SIGNED_IMAGE: &str = "busybox:1.34";

    pub(crate) fn get_fulcio_cert_pool() -> CertificatePool {
        fn pem_to_der(input: &str) -> CertificateDer<'_> {
            let pem_cert = pem::parse(input).unwrap();
            assert_eq!(pem_cert.tag(), "CERTIFICATE");
            CertificateDer::from(pem_cert.into_contents())
        }
        let certificates = vec![pem_to_der(FULCIO_CRT_1_PEM), pem_to_der(FULCIO_CRT_2_PEM)];

        CertificatePool::from_certificates(certificates, []).unwrap()
    }

    pub(crate) fn get_rekor_public_key() -> (String, CosignVerificationKey) {
        let key =
            CosignVerificationKey::from_pem(REKOR_PUB_KEY.as_bytes(), &SigningScheme::default())
                .expect("Cannot create test REKOR_PUB_KEY");
        (REKOR_PUB_KEY_ID.to_string(), key)
    }

    #[test]
    fn verify_constraints_all_satisfied() {
        let email = "alice@example.com".to_string();
        let issuer = "an issuer".to_string();

        let mut annotations: BTreeMap<String, String> = BTreeMap::new();
        annotations.insert("key1".into(), "value1".into());
        annotations.insert("key2".into(), "value2".into());

        let mut layers: Vec<SignatureLayer> = Vec::new();
        for _ in 0..5 {
            let mut sl = build_correct_signature_layer_with_certificate();
            let mut cert_signature = sl.certificate_signature.unwrap();
            let cert_subj = CertificateSubject::Email(email.clone());
            cert_signature.issuer = Some(issuer.clone());
            cert_signature.subject = cert_subj;
            sl.certificate_signature = Some(cert_signature);

            let mut extra: BTreeMap<String, serde_json::Value> = annotations
                .iter()
                .map(|(k, v)| (k.clone(), json!(v)))
                .collect();
            extra.insert("something extra".into(), json!("value extra"));

            let mut simple_signing = sl.simple_signing;
            let optional = Optional {
                creator: Some("test".into()),
                timestamp: None,
                extra,
            };
            simple_signing.optional = Some(optional);
            sl.simple_signing = simple_signing;

            layers.push(sl);
        }

        let mut constraints: VerificationConstraintVec = Vec::new();
        let vc = CertSubjectEmailVerifier {
            email: StringVerifier::ExactMatch(email.clone()),
            issuer: Some(StringVerifier::ExactMatch(issuer)),
        };
        constraints.push(Box::new(vc));

        let vc = CertSubjectEmailVerifier {
            email: StringVerifier::ExactMatch(email),
            issuer: None,
        };
        constraints.push(Box::new(vc));

        let vc = AnnotationVerifier { annotations };
        constraints.push(Box::new(vc));

        verify_constraints(&layers, constraints.iter()).expect("should not return an error");
    }

    #[test]
    fn verify_constraints_none_satisfied() {
        let email = "alice@example.com".to_string();
        let issuer = "an issuer".to_string();
        let wrong_email = "bob@example.com".to_string();

        let mut layers: Vec<SignatureLayer> = Vec::new();
        for _ in 0..5 {
            let mut sl = build_correct_signature_layer_with_certificate();
            let mut cert_signature = sl.certificate_signature.unwrap();
            let cert_subj = CertificateSubject::Email(email.clone());
            cert_signature.issuer = Some(issuer.clone());
            cert_signature.subject = cert_subj;
            sl.certificate_signature = Some(cert_signature);

            let mut extra: BTreeMap<String, serde_json::Value> = BTreeMap::new();
            extra.insert("something extra".into(), json!("value extra"));

            let mut simple_signing = sl.simple_signing;
            let optional = Optional {
                creator: Some("test".into()),
                timestamp: None,
                extra,
            };
            simple_signing.optional = Some(optional);
            sl.simple_signing = simple_signing;

            layers.push(sl);
        }

        let mut constraints: VerificationConstraintVec = Vec::new();
        let vc = CertSubjectEmailVerifier {
            email: StringVerifier::ExactMatch(wrong_email.clone()),
            issuer: Some(StringVerifier::ExactMatch(issuer)), // correct issuer
        };
        constraints.push(Box::new(vc));

        let vc = CertSubjectEmailVerifier {
            email: StringVerifier::ExactMatch(wrong_email),
            issuer: None, // missing issuer, more relaxed
        };
        constraints.push(Box::new(vc));

        let err =
            verify_constraints(&layers, constraints.iter()).expect_err("we should have an err");
        assert_eq!(err.unsatisfied_constraints.len(), 2);
    }

    #[test]
    fn verify_constraints_some_unsatisfied() {
        let email = "alice@example.com".to_string();
        let issuer = "an issuer".to_string();
        let email_incorrect = "bob@example.com".to_string();

        let mut layers: Vec<SignatureLayer> = Vec::new();
        for _ in 0..5 {
            let mut sl = build_correct_signature_layer_with_certificate();
            let mut cert_signature = sl.certificate_signature.unwrap();
            let cert_subj = CertificateSubject::Email(email.clone());
            cert_signature.issuer = Some(issuer.clone());
            cert_signature.subject = cert_subj;
            sl.certificate_signature = Some(cert_signature);

            let mut extra: BTreeMap<String, serde_json::Value> = BTreeMap::new();
            extra.insert("something extra".into(), json!("value extra"));

            let mut simple_signing = sl.simple_signing;
            let optional = Optional {
                creator: Some("test".into()),
                timestamp: None,
                extra,
            };
            simple_signing.optional = Some(optional);
            sl.simple_signing = simple_signing;

            layers.push(sl);
        }

        let mut constraints: VerificationConstraintVec = Vec::new();
        let satisfied_constraint = CertSubjectEmailVerifier {
            email: StringVerifier::ExactMatch(email),
            issuer: Some(StringVerifier::ExactMatch(issuer)),
        };
        constraints.push(Box::new(satisfied_constraint));

        let unsatisfied_constraint = CertSubjectEmailVerifier {
            email: StringVerifier::ExactMatch(email_incorrect),
            issuer: None,
        };
        constraints.push(Box::new(unsatisfied_constraint));

        let err =
            verify_constraints(&layers, constraints.iter()).expect_err("we should have an err");
        assert_eq!(err.unsatisfied_constraints.len(), 1);
    }

    #[test]
    fn add_constrains_all_succeed() {
        let mut signature_layer = SignatureLayer::new_unsigned(
            &"test_image".parse().unwrap(),
            "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        )
        .expect("create SignatureLayer failed");

        let signer = SigningScheme::ECDSA_P256_SHA256_ASN1
            .create_signer()
            .expect("create signer failed");
        let signer = PrivateKeySigner::new_with_signer(signer);

        let annotations = [(String::from("key"), String::from("value"))].into();
        let annotations = AnnotationMarker::new(annotations);

        let constrains: Vec<Box<dyn Constraint>> = vec![Box::new(signer), Box::new(annotations)];
        apply_constraints(&mut signature_layer, constrains.iter()).expect("no error should occur");
    }

    #[test]
    fn add_constrain_some_failed() {
        let mut signature_layer = SignatureLayer::new_unsigned(
            &"test_image".parse().unwrap(),
            "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        )
        .expect("create SignatureLayer failed");

        let signer = SigningScheme::ECDSA_P256_SHA256_ASN1
            .create_signer()
            .expect("create signer failed");
        let signer = PrivateKeySigner::new_with_signer(signer);
        let another_signer_of_same_layer = SigningScheme::ECDSA_P256_SHA256_ASN1
            .create_signer()
            .expect("create signer failed");
        let another_signer_of_same_layer =
            PrivateKeySigner::new_with_signer(another_signer_of_same_layer);

        let annotations = [(String::from("key"), String::from("value"))].into();
        let annotations = AnnotationMarker::new(annotations);

        let constrains: Vec<Box<dyn Constraint>> = vec![
            Box::new(signer),
            Box::new(annotations),
            Box::new(another_signer_of_same_layer),
        ];
        apply_constraints(&mut signature_layer, constrains.iter())
            .expect_err("no error should occur");
    }

    #[cfg(feature = "test-registry")]
    #[rstest::rstest]
    #[case(SigningScheme::RSA_PSS_SHA256(2048))]
    #[case(SigningScheme::RSA_PKCS1_SHA256(2048))]
    #[case(SigningScheme::ECDSA_P256_SHA256_ASN1)]
    #[case(SigningScheme::ECDSA_P384_SHA384_ASN1)]
    #[case(SigningScheme::ED25519)]
    #[tokio::test]
    #[serial_test::serial]
    async fn sign_verify_image(#[case] signing_scheme: SigningScheme) {
        let test_container = registry_image()
            .start()
            .await
            .expect("failed to start registry");
        let port = test_container
            .get_host_port_ipv4(5000)
            .await
            .expect("failed to get port");

        let mut client = ClientBuilder::default()
            .enable_registry_caching()
            .with_oci_client_config(crate::registry::ClientConfig {
                protocol: crate::registry::ClientProtocol::HttpsExcept(vec![format!(
                    "localhost:{}",
                    port
                )]),
                ..Default::default()
            })
            .build()
            .expect("failed to create oci client");

        let image_ref = format!("localhost:{}/{}", port, SIGNED_IMAGE)
            .parse::<OciReference>()
            .expect("failed to parse reference");
        prepare_image_to_be_signed(&mut client, &image_ref).await;

        let (cosign_signature_image, source_image_digest) = client
            .triangulate(&image_ref, &crate::registry::Auth::Anonymous)
            .await
            .expect("get manifest failed");
        let mut signature_layer = SignatureLayer::new_unsigned(&image_ref, &source_image_digest)
            .expect("create SignatureLayer failed");
        let signer = signing_scheme
            .create_signer()
            .expect("create signer failed");
        let pubkey = signer
            .to_sigstore_keypair()
            .expect("to keypair failed")
            .public_key_to_pem()
            .expect("derive public key failed");

        let signer = PrivateKeySigner::new_with_signer(signer);
        if !signer
            .add_constraint(&mut signature_layer)
            .expect("sign SignatureLayer failed")
        {
            panic!("failed to sign SignatureLayer");
        };

        client
            .push_signature(
                None,
                &Auth::Anonymous,
                &cosign_signature_image,
                vec![signature_layer],
            )
            .await
            .expect("push signature failed");

        dbg!("start to verify");

        let signature_layers = client
            .trusted_signature_layers(&Auth::Anonymous, &image_ref)
            .await
            .expect("get trusted signature layers failed");
        let pk_verifier =
            verification_constraint::PublicKeyVerifier::new(pubkey.as_bytes(), &signing_scheme)
                .expect("create PublicKeyVerifier failed");
        assert_eq!(signature_layers.len(), 1);
        let res = pk_verifier
            .verify(&signature_layers[0])
            .expect("failed to verify");
        assert!(res);
    }

    #[cfg(feature = "test-registry")]
    async fn prepare_image_to_be_signed(client: &mut Client, image_ref: &OciReference) {
        let data = client
            .registry_client
            .pull(
                &SIGNED_IMAGE.parse().expect("failed to parse image ref"),
                &oci_client::secrets::RegistryAuth::Anonymous,
                vec![oci_client::manifest::IMAGE_DOCKER_LAYER_GZIP_MEDIA_TYPE],
            )
            .await
            .expect("pull test image failed");

        client
            .registry_client
            .push(
                &image_ref.oci_reference,
                &data.layers[..],
                data.config.clone(),
                &oci_client::secrets::RegistryAuth::Anonymous,
                None,
            )
            .await
            .expect("push test image failed");
    }

    #[cfg(feature = "test-registry")]
    fn registry_image() -> testcontainers::GenericImage {
        testcontainers::GenericImage::new("docker.io/library/registry", "2")
            .with_wait_for(WaitFor::message_on_stderr("listening on "))
    }
}