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
use std::env::temp_dir;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use anyhow::{bail, Context as _};
use oci_client::client::ClientProtocol;
use oci_client::client::ImageData;
use oci_client::Reference;
use oci_wasm::WASM_LAYER_MEDIA_TYPE;
use oci_wasm::WASM_MANIFEST_MEDIA_TYPE;
use tokio::fs;
use tokio::io::AsyncWriteExt;
use wascap::jwt;

use crate::RegistryConfig;
use crate::{tls, UseParFileCache};

const PROVIDER_ARCHIVE_MEDIA_TYPE: &str = "application/vnd.wasmcloud.provider.archive.layer.v1+par";
const WASM_MEDIA_TYPE: &str = "application/vnd.module.wasm.content.layer.v1+wasm";
const OCI_MEDIA_TYPE: &str = "application/vnd.oci.image.layer.v1.tar";

/// Whether to update an OCI artifact cache
#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum OciArtifactCacheUpdate {
    /// Do not update the OCI artifact cache
    #[default]
    Ignore,
    /// Update the cache
    Update,
}

/// OCI artifact fetcher
#[derive(Clone, Debug)]
pub struct OciFetcher {
    additional_ca_paths: Vec<PathBuf>,
    allow_latest: bool,
    allow_insecure: bool,
    auth: oci_client::secrets::RegistryAuth,
}

impl Default for OciFetcher {
    fn default() -> Self {
        Self {
            additional_ca_paths: Vec::default(),
            allow_latest: false,
            allow_insecure: false,
            auth: oci_client::secrets::RegistryAuth::Anonymous,
        }
    }
}

impl From<&RegistryConfig> for OciFetcher {
    fn from(
        RegistryConfig {
            auth,
            allow_latest,
            allow_insecure,
            additional_ca_paths,
            ..
        }: &RegistryConfig,
    ) -> Self {
        Self {
            auth: auth.into(),
            allow_latest: *allow_latest,
            allow_insecure: *allow_insecure,
            additional_ca_paths: additional_ca_paths.clone(),
        }
    }
}

impl From<RegistryConfig> for OciFetcher {
    fn from(
        RegistryConfig {
            auth,
            allow_latest,
            allow_insecure,
            additional_ca_paths,
            ..
        }: RegistryConfig,
    ) -> Self {
        Self {
            auth: auth.into(),
            allow_latest,
            allow_insecure,
            additional_ca_paths,
        }
    }
}

/// Default directory in which OCI artifacts are cached
pub async fn oci_cache_dir() -> anyhow::Result<PathBuf> {
    let path = temp_dir().join("wasmcloud_ocicache");
    if !fs::try_exists(&path).await? {
        fs::create_dir_all(&path).await?;
    }
    Ok(path)
}

#[allow(unused)]
async fn cache_oci_image(
    image: ImageData,
    cache_filepath: impl AsRef<Path>,
    digest_filepath: impl AsRef<Path>,
) -> std::io::Result<()> {
    let mut cache_file = fs::File::create(cache_filepath).await?;
    let content = image
        .layers
        .into_iter()
        .flat_map(|l| l.data)
        .collect::<Vec<_>>();
    cache_file.write_all(&content).await?;
    cache_file.flush().await?;
    if let Some(digest) = image.digest {
        let mut digest_file = fs::File::create(digest_filepath).await?;
        digest_file.write_all(digest.as_bytes()).await?;
        digest_file.flush().await?;
    }
    Ok(())
}

fn prune_filepath(img: &str) -> String {
    let mut img = img.replace(':', "_");
    img = img.replace('/', "_");
    img = img.replace('.', "_");
    img
}

/// A type to indicate whether there was a cache hit or miss when loading artifacts
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CacheResult {
    Hit,
    Miss,
}

impl OciFetcher {
    /// Fetch an OCI artifact to a path and return that path. Returns the path and whether or not
    /// there was a cache hit/miss
    pub async fn fetch_path(
        &self,
        output_dir: impl AsRef<Path>,
        img: impl AsRef<str>,
        accepted_media_types: Vec<&str>,
        cache: OciArtifactCacheUpdate,
    ) -> anyhow::Result<(PathBuf, CacheResult)> {
        let output_dir = output_dir.as_ref();
        let img = img.as_ref().to_lowercase(); // the OCI spec does not allow for capital letters in references
        if !self.allow_latest && img.ends_with(":latest") {
            bail!("fetching images tagged 'latest' is currently prohibited in this host. This option can be overridden with WASMCLOUD_OCI_ALLOW_LATEST")
        }
        let pruned_filepath = prune_filepath(&img);
        let cache_file = output_dir.join(&pruned_filepath);
        let mut digest_file = output_dir.join(&pruned_filepath).clone();
        digest_file.set_extension("digest");

        let img = Reference::from_str(&img)?;

        let protocol = if self.allow_insecure {
            ClientProtocol::HttpsExcept(vec![img.registry().to_string()])
        } else {
            ClientProtocol::Https
        };
        let mut certs = tls::NATIVE_ROOTS_OCI.to_vec();
        if !self.additional_ca_paths.is_empty() {
            certs.extend(
                tls::load_certs_from_paths(&self.additional_ca_paths)
                    .context("failed to load CA certs from provided paths")?
                    .iter()
                    .map(|cert| oci_client::client::Certificate {
                        encoding: oci_client::client::CertificateEncoding::Der,
                        data: cert.to_vec(),
                    }),
            );
        }
        let c = oci_client::Client::new(oci_client::client::ClientConfig {
            protocol,
            extra_root_certificates: certs,
            ..Default::default()
        });

        // In case of a cache miss where the file does not exist, pull a fresh OCI Image
        if fs::metadata(&cache_file).await.is_ok() {
            let (_, oci_digest) = c
                .pull_manifest(&img, &self.auth)
                .await
                .context("failed to fetch OCI manifest")?;
            // If the digest file doesn't exist that is ok, we just unwrap to an empty string
            let file_digest = fs::read_to_string(&digest_file).await.unwrap_or_default();
            if !oci_digest.is_empty() && !file_digest.is_empty() && file_digest == oci_digest {
                return Ok((cache_file, CacheResult::Hit));
            }
        }

        let imgdata = c
            .pull(&img, &self.auth, accepted_media_types)
            .await
            .context("failed to fetch OCI bytes")?;
        // As a client, we should reject invalid OCI artifacts
        if imgdata
            .manifest
            .as_ref()
            .map(|m| m.media_type.as_deref().unwrap_or_default() == WASM_MANIFEST_MEDIA_TYPE)
            .unwrap_or(false)
            && imgdata.layers.len() > 1
        {
            bail!(
                "Found invalid OCI wasm artifact, expected single layer, found {} layers",
                imgdata.layers.len()
            )
        }
        // Update the OCI artifact cache if specified
        if let OciArtifactCacheUpdate::Update = cache {
            cache_oci_image(imgdata, &cache_file, digest_file)
                .await
                .context("failed to cache OCI bytes")?;
        }

        Ok((cache_file, CacheResult::Miss))
    }

    /// Fetch component from OCI
    ///
    /// # Errors
    ///
    /// Returns an error if either fetching fails or reading the fetched OCI path fails
    pub async fn fetch_component(&self, oci_ref: impl AsRef<str>) -> anyhow::Result<Vec<u8>> {
        let (path, _) = self
            .fetch_path(
                oci_cache_dir().await?,
                oci_ref,
                vec![WASM_MEDIA_TYPE, OCI_MEDIA_TYPE, WASM_LAYER_MEDIA_TYPE],
                OciArtifactCacheUpdate::Update,
            )
            .await
            .context("failed to fetch OCI path")?;
        fs::read(&path)
            .await
            .with_context(|| format!("failed to read `{}`", path.display()))
    }

    /// Fetch provider from OCI
    ///
    /// # Errors
    ///
    /// Returns an error if either fetching fails or reading the fetched OCI path fails
    pub async fn fetch_provider(
        &self,
        oci_ref: impl AsRef<str>,
        host_id: impl AsRef<str>,
    ) -> anyhow::Result<(PathBuf, Option<jwt::Token<jwt::CapabilityProvider>>)> {
        let (path, cache) = self
            .fetch_path(
                oci_cache_dir().await?,
                oci_ref.as_ref(),
                vec![PROVIDER_ARCHIVE_MEDIA_TYPE, OCI_MEDIA_TYPE],
                OciArtifactCacheUpdate::Update,
            )
            .await
            .context("failed to fetch OCI path")?;
        let should_cache = match cache {
            CacheResult::Miss => UseParFileCache::Ignore,
            CacheResult::Hit => UseParFileCache::Use,
        };
        crate::par::read(&path, host_id, oci_ref, should_cache)
            .await
            .with_context(|| format!("failed to read `{}`", path.display()))
    }

    /// Used to set additional CA paths that will be used as part of fetching components and providers
    pub fn with_additional_ca_paths(mut self, paths: &[impl AsRef<Path>]) -> Self {
        self.additional_ca_paths = paths.iter().map(AsRef::as_ref).map(PathBuf::from).collect();
        self
    }
}