Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove async from trustroot trait #350

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ cfg-if = "1.0.0"
chrono = { version = "0.4.27", default-features = false, features = ["serde"] }
const-oid = "0.9.1"
digest = { version = "0.10.3", default-features = false }
dyn-clone = "1.0"
ecdsa = { version = "0.16.7", features = ["pkcs8", "digest", "der", "signing"] }
ed25519 = { version = "2.2.1", features = ["alloc"] }
ed25519-dalek = { version = "2.0.0-rc.2", features = ["pkcs8", "rand_core"] }
Expand Down
13 changes: 5 additions & 8 deletions examples/cosign/verify/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ async fn run_app(

let mut client_builder =
sigstore::cosign::ClientBuilder::default().with_oci_client_config(oci_client_config);
client_builder = client_builder.with_trust_repository(frd).await?;
client_builder = client_builder.with_trust_repository(frd)?;

let cert_chain: Option<Vec<sigstore::registry::Certificate>> = match cli.cert_chain.as_ref() {
None => None,
Expand Down Expand Up @@ -184,7 +184,7 @@ async fn run_app(
}
if let Some(path_to_cert) = cli.cert.as_ref() {
let cert = fs::read(path_to_cert).map_err(|e| anyhow!("Cannot read cert: {:?}", e))?;
let require_rekor_bundle = if !frd.rekor_keys().await?.is_empty() {
let require_rekor_bundle = if !frd.rekor_keys()?.is_empty() {
true
} else {
warn!("certificate based verification is weaker when Rekor integration is disabled");
Expand Down Expand Up @@ -229,18 +229,15 @@ async fn fulcio_and_rekor_data(cli: &Cli) -> anyhow::Result<Box<dyn sigstore::tr
if cli.use_sigstore_tuf_data {
info!("Downloading data from Sigstore TUF repository");

let repo: sigstore::errors::Result<SigstoreTrustRoot> =
SigstoreTrustRoot::new(None).await?.prefetch().await;
let repo: sigstore::errors::Result<SigstoreTrustRoot> = SigstoreTrustRoot::new(None).await;

return Ok(Box::new(repo?));
};

let mut data = sigstore::trust::ManualTrustRoot::default();
if let Some(path) = cli.rekor_pub_key.as_ref() {
data.rekor_key = Some(
fs::read(path)
.map_err(|e| anyhow!("Error reading rekor public key from disk: {}", e))?,
);
data.rekor_keys = Some(vec![fs::read(path)
.map_err(|e| anyhow!("Error reading rekor public key from disk: {}", e))?]);
}

if let Some(path) = cli.fulcio_cert.as_ref() {
Expand Down
35 changes: 22 additions & 13 deletions src/cosign/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,21 @@
// 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.

use std::collections::HashMap;
use std::ops::Add;

use async_trait::async_trait;
use oci_distribution::manifest::OCI_IMAGE_MEDIA_TYPE;
use tracing::warn;
use std::{collections::HashMap, ops::Add};
use tracing::{debug, warn};

use super::constants::{SIGSTORE_OCI_MEDIA_TYPE, SIGSTORE_SIGNATURE_ANNOTATION};
use super::{CosignCapabilities, SignatureLayer};
use crate::cosign::signature_layers::build_signature_layers;
use crate::crypto::CosignVerificationKey;
use crate::registry::{Auth, OciReference, PushResponse};
use crate::{
crypto::certificate_pool::CertificatePool,
cosign::{
constants::{SIGSTORE_OCI_MEDIA_TYPE, SIGSTORE_SIGNATURE_ANNOTATION},
signature_layers::build_signature_layers,
CosignCapabilities, SignatureLayer,
},
crypto::{certificate_pool::CertificatePool, CosignVerificationKey},
errors::{Result, SigstoreError},
registry::{Auth, OciReference, PushResponse},
};
use tracing::debug;

/// Used to generate an empty [OCI Configuration](https://github.com/opencontainers/image-spec/blob/v1.0.0/config.md).
pub const CONFIG_DATA: &str = "{}";
Expand All @@ -43,6 +40,17 @@ pub struct Client<'a> {
pub(crate) fulcio_cert_pool: Option<CertificatePool<'a>>,
}

impl Client<'_> {
/// Yield a `'static` lifetime of the `Client`
pub fn to_owned(&self) -> Client<'static> {
Client {
registry_client: self.registry_client.to_owned(),
rekor_pub_key: self.rekor_pub_key.as_ref().map(|k| k.to_owned()),
fulcio_cert_pool: self.fulcio_cert_pool.as_ref().map(|cp| cp.to_owned()),
}
}
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl CosignCapabilities for Client<'_> {
Expand Down Expand Up @@ -176,6 +184,7 @@ mod tests {
use crate::cosign::tests::{get_fulcio_cert_pool, REKOR_PUB_KEY};
use crate::crypto::SigningScheme;
use crate::mock_client::test::MockOciClient;
use std::sync::Arc;

fn build_test_client(mock_client: MockOciClient) -> Client<'static> {
let rekor_pub_key =
Expand All @@ -196,7 +205,7 @@ mod tests {
String::from("sha256:f3cfc9d0dbf931d3db4685ec659b7ac68e2a578219da4aae65427886e649b06b");
let expected_image = "docker.io/library/busybox:sha256-f3cfc9d0dbf931d3db4685ec659b7ac68e2a578219da4aae65427886e649b06b.sig".parse().unwrap();
let mock_client = MockOciClient {
fetch_manifest_digest_response: Some(Ok(image_digest.clone())),
fetch_manifest_digest_response: Some(Arc::new(Ok(image_digest.clone()))),
pull_response: None,
pull_manifest_response: None,
push_response: None,
Expand Down
9 changes: 3 additions & 6 deletions src/cosign/client_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,12 @@ impl<'a> ClientBuilder<'a> {
///
/// Enables Fulcio and Rekor integration with the given trust repository.
/// See [crate::sigstore::TrustRoot] for more details on trust repositories.
pub async fn with_trust_repository<R: TrustRoot + ?Sized>(
mut self,
repo: &'a R,
) -> Result<Self> {
let rekor_keys = repo.rekor_keys().await?;
pub fn with_trust_repository<R: TrustRoot + ?Sized>(mut self, repo: &'a R) -> Result<Self> {
let rekor_keys = repo.rekor_keys()?;
if !rekor_keys.is_empty() {
self.rekor_pub_key = Some(rekor_keys[0]);
}
self.fulcio_certs = repo.fulcio_certs().await?;
self.fulcio_certs = repo.fulcio_certs()?;

Ok(self)
}
Expand Down
14 changes: 14 additions & 0 deletions src/crypto/certificate_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,20 @@ pub(crate) struct CertificatePool<'a> {
intermediates: Vec<CertificateDer<'a>>,
}

impl CertificatePool<'_> {
/// Yield a `'static` lifetime of the `CertificatePool`
pub(crate) fn to_owned(&self) -> CertificatePool<'static> {
CertificatePool {
trusted_roots: self.trusted_roots.iter().map(|ta| ta.to_owned()).collect(),
intermediates: self
.intermediates
.iter()
.map(|c| c.as_ref().to_owned().into())
.collect(),
}
}
}

impl<'a> CertificatePool<'a> {
/// Builds a `CertificatePool` instance using the provided list of [`Certificate`].
pub(crate) fn from_certificates<R, I>(
Expand Down
3 changes: 1 addition & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,12 @@
//!
//! let mut repo = sigstore::trust::ManualTrustRoot {
//! fulcio_certs: Some(vec![fulcio_cert.try_into().unwrap()]),
//! rekor_key: Some(rekor_pub_key),
//! rekor_keys: Some(vec![rekor_pub_key]),
//! ..Default::default()
//! };
//!
//! let mut client = sigstore::cosign::ClientBuilder::default()
//! .with_trust_repository(&repo)
//! .await
//! .expect("Cannot construct cosign client from given materials")
//! .build()
//! .expect("Unexpected failure while building Client");
Expand Down
20 changes: 11 additions & 9 deletions src/mock_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@ pub(crate) mod test {
secrets::RegistryAuth,
Reference,
};
use std::sync::Arc;

#[derive(Default)]
#[derive(Default, Clone)]
pub struct MockOciClient {
pub fetch_manifest_digest_response: Option<anyhow::Result<String>>,
pub pull_response: Option<anyhow::Result<ImageData>>,
pub pull_manifest_response: Option<anyhow::Result<(OciManifest, String)>>,
pub push_response: Option<anyhow::Result<PushResponse>>,
// Note: all the `Result` objects have to be wrapped inside of an `Arc` to be able to clone them
pub fetch_manifest_digest_response: Option<Arc<anyhow::Result<String>>>,
pub pull_response: Option<Arc<anyhow::Result<ImageData>>>,
pub pull_manifest_response: Option<Arc<anyhow::Result<(OciManifest, String)>>>,
pub push_response: Option<Arc<anyhow::Result<PushResponse>>>,
}

impl crate::registry::ClientCapabilitiesDeps for MockOciClient {}
Expand All @@ -51,7 +53,7 @@ pub(crate) mod test {
error: String::from("No fetch_manifest_digest_response provided!"),
})?;

match mock_response {
match mock_response.as_ref() {
Ok(r) => Ok(r.clone()),
Err(e) => Err(SigstoreError::RegistryFetchManifestError {
image: image.whole(),
Expand All @@ -74,7 +76,7 @@ pub(crate) mod test {
error: String::from("No pull_response provided!"),
})?;

match mock_response {
match mock_response.as_ref() {
Ok(r) => Ok(r.clone()),
Err(e) => Err(SigstoreError::RegistryPullError {
image: image.whole(),
Expand All @@ -95,7 +97,7 @@ pub(crate) mod test {
}
})?;

match mock_response {
match mock_response.as_ref() {
Ok(r) => Ok(r.clone()),
Err(e) => Err(SigstoreError::RegistryPullError {
image: image.whole(),
Expand All @@ -120,7 +122,7 @@ pub(crate) mod test {
error: String::from("No push_response provided!"),
})?;

match mock_response {
match mock_response.as_ref() {
Ok(r) => Ok(PushResponse {
config_url: r.config_url.clone(),
manifest_url: r.manifest_url.clone(),
Expand Down
7 changes: 5 additions & 2 deletions src/registry/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub(crate) use oci_caching_client::*;
use crate::errors::Result;

use async_trait::async_trait;
use dyn_clone::DynClone;

/// Workaround to ensure the `Send + Sync` supertraits are
/// required by ClientCapabilities only when the target
Expand All @@ -43,7 +44,7 @@ use async_trait::async_trait;
/// to define ClientCapabilities twice (one with `#[cfg(target_arch = "wasm32")]`,
/// the other with `#[cfg(not(target_arch = "wasm32"))]`
#[cfg(not(target_arch = "wasm32"))]
pub(crate) trait ClientCapabilitiesDeps: Send + Sync {}
pub(crate) trait ClientCapabilitiesDeps: Send + Sync + DynClone {}

/// Workaround to ensure the `Send + Sync` supertraits are
/// required by ClientCapabilities only when the target
Expand All @@ -53,7 +54,7 @@ pub(crate) trait ClientCapabilitiesDeps: Send + Sync {}
/// to define ClientCapabilities twice (one with `#[cfg(target_arch = "wasm32")]`,
/// the other with `#[cfg(not(target_arch = "wasm32"))]`
#[cfg(target_arch = "wasm32")]
pub(crate) trait ClientCapabilitiesDeps {}
pub(crate) trait ClientCapabilitiesDeps: DynClone {}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
Expand Down Expand Up @@ -87,3 +88,5 @@ pub(crate) trait ClientCapabilities: ClientCapabilitiesDeps {
manifest: Option<oci_distribution::manifest::OciImageManifest>,
) -> Result<oci_distribution::client::PushResponse>;
}

dyn_clone::clone_trait_object!(ClientCapabilities);
1 change: 1 addition & 0 deletions src/registry/oci_caching_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use tracing::{debug, error};
///
/// For testing purposes, use instead the client inside of the
/// `mock_client` module.
#[derive(Clone)]
pub(crate) struct OciCachingClient {
pub registry_client: oci_distribution::Client,
}
Expand Down
1 change: 1 addition & 0 deletions src/registry/oci_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use async_trait::async_trait;
///
/// For testing purposes, use instead the client inside of the
/// `mock_client` module.
#[derive(Clone)]
pub(crate) struct OciClient {
pub registry_client: oci_distribution::Client,
}
Expand Down
18 changes: 7 additions & 11 deletions src/trust/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,42 +13,38 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use async_trait::async_trait;
use webpki::types::CertificateDer;

#[cfg(feature = "sigstore-trust-root")]
pub mod sigstore;

/// A `TrustRoot` owns all key material necessary for establishing a root of trust.
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
pub trait TrustRoot: Send + Sync {
async fn fulcio_certs(&self) -> crate::errors::Result<Vec<CertificateDer>>;
async fn rekor_keys(&self) -> crate::errors::Result<Vec<&[u8]>>;
fn fulcio_certs(&self) -> crate::errors::Result<Vec<CertificateDer>>;
fn rekor_keys(&self) -> crate::errors::Result<Vec<&[u8]>>;
}

/// A `ManualTrustRoot` is a [TrustRoot] with out-of-band trust materials.
/// As it does not establish a trust root with TUF, users must initialize its materials themselves.
#[derive(Debug, Default)]
pub struct ManualTrustRoot<'a> {
pub fulcio_certs: Option<Vec<CertificateDer<'a>>>,
pub rekor_key: Option<Vec<u8>>,
pub rekor_keys: Option<Vec<Vec<u8>>>,
}

#[cfg(not(target_arch = "wasm32"))]
#[async_trait]
impl TrustRoot for ManualTrustRoot<'_> {
#[cfg(not(target_arch = "wasm32"))]
async fn fulcio_certs(&self) -> crate::errors::Result<Vec<CertificateDer>> {
fn fulcio_certs(&self) -> crate::errors::Result<Vec<CertificateDer>> {
Ok(match &self.fulcio_certs {
Some(certs) => certs.clone(),
None => Vec::new(),
})
}

async fn rekor_keys(&self) -> crate::errors::Result<Vec<&[u8]>> {
Ok(match &self.rekor_key {
Some(key) => vec![&key[..]],
fn rekor_keys(&self) -> crate::errors::Result<Vec<&[u8]>> {
Ok(match &self.rekor_keys {
Some(keys) => keys.iter().map(|k| k.as_slice()).collect(),
None => Vec::new(),
})
}
Expand Down
Loading
Loading