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
//
// 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.

use super::{ClientCapabilities, ClientCapabilitiesDeps};
use crate::errors::{Result, SigstoreError};

use async_trait::async_trait;
use cached::proc_macro::cached;
use serde::Serialize;
use sha2::{Digest, Sha256};
use tracing::{debug, error};

/// Internal client for an OCI Registry. This performs actual
/// calls against the remote registry and caches the results
/// for 60 seconds.
///
/// For testing purposes, use instead the client inside of the
/// `mock_client` module.
pub(crate) struct OciCachingClient {
    pub registry_client: oci_client::Client,
}

#[cached(
    time = 60,
    result = true,
    sync_writes = "default",
    key = "String",
    convert = r#"{ format!("{}", image) }"#,
    with_cached_flag = true
)]
async fn fetch_manifest_digest_cached(
    client: &mut oci_client::Client,
    image: &oci_client::Reference,
    auth: &oci_client::secrets::RegistryAuth,
) -> Result<cached::Return<String>> {
    client
        .fetch_manifest_digest(image, auth)
        .await
        .map_err(|e| SigstoreError::RegistryFetchManifestError {
            image: image.whole(),
            error: e.to_string(),
        })
        .map(cached::Return::new)
}

/// Internal struct, used to calculate a unique hash of the pull
/// settings. This is required to cache pull results.
#[derive(Serialize, Debug)]
struct PullSettings<'a> {
    image: String,
    auth: super::config::Auth,
    pub accepted_media_types: Vec<&'a str>,
}

impl<'a> PullSettings<'a> {
    fn new(
        image: &oci_client::Reference,
        auth: &oci_client::secrets::RegistryAuth,
        accepted_media_types: Vec<&'a str>,
    ) -> PullSettings<'a> {
        let image_str = image.whole();
        let auth_sigstore: super::config::Auth = From::from(auth);

        PullSettings {
            image: image_str,
            auth: auth_sigstore,
            accepted_media_types,
        }
    }

    #[allow(clippy::unwrap_used)]
    pub fn image(&self) -> oci_client::Reference {
        // we can use `unwrap` here, because this will never fail
        let reference: oci_client::Reference = self.image.parse().unwrap();
        reference
    }

    pub fn auth(&self) -> oci_client::secrets::RegistryAuth {
        let internal_auth: &super::config::Auth = &self.auth;
        let a: oci_client::secrets::RegistryAuth = internal_auth.into();
        a
    }

    // This function returns a hash of the PullSettings struct.
    // The has is computed by doing a canonical JSON representation of
    // the struct.
    //
    // This method cannot error, because its value is used by the `cached`
    // macro, which doesn't allow error handling.
    // Because of that the method will return the '0' value when something goes
    // wrong during the serialization operation. This is very unlikely to happen
    pub fn hash(&self) -> String {
        let buf = match serde_json_canonicalizer::to_vec(self) {
            Ok(vec) => vec,
            Err(e) => {
                error!(err=?e, settings=?self, "Cannot perform canonical serialization");
                return "0".to_string();
            }
        };

        let mut hasher = Sha256::new();
        hasher.update(&buf);
        let result = hasher.finalize();
        result
            .iter()
            .map(|v| format!("{v:x}"))
            .collect::<Vec<String>>()
            .join("")
    }
}

// Pulls an OCI artifact.
// Details about this cache:
//   * the cache is time bound: cached values are purged after 60 seconds
//   * only successful results are cached
#[cached(
    time = 60,
    result = true,
    sync_writes = "default",
    key = "String",
    convert = r#"{ settings.hash() }"#,
    with_cached_flag = true
)]
async fn pull_cached(
    client: &mut oci_client::Client,
    settings: PullSettings<'_>,
) -> Result<cached::Return<oci_client::client::ImageData>> {
    let auth = settings.auth();
    let image = settings.image();

    client
        .pull(&image, &auth, settings.accepted_media_types)
        .await
        .map_err(|e| SigstoreError::RegistryPullError {
            image: image.whole(),
            error: e.to_string(),
        })
        .map(cached::Return::new)
}

/// Internal struct, used to calculate a unique hash of the pull manifest
/// settings. This is required to cache pull manifest results.
#[derive(Serialize, Debug)]
struct PullManifestSettings {
    image: String,
    auth: super::config::Auth,
}

impl PullManifestSettings {
    fn new(
        image: &oci_client::Reference,
        auth: &oci_client::secrets::RegistryAuth,
    ) -> PullManifestSettings {
        let image_str = image.whole();
        let auth_sigstore: super::config::Auth = From::from(auth);

        PullManifestSettings {
            image: image_str,
            auth: auth_sigstore,
        }
    }

    #[allow(clippy::unwrap_used)]
    pub fn image(&self) -> oci_client::Reference {
        // we can use `unwrap` here, because this will never fail
        let reference: oci_client::Reference = self.image.parse().unwrap();
        reference
    }

    pub fn auth(&self) -> oci_client::secrets::RegistryAuth {
        let internal_auth: &super::config::Auth = &self.auth;
        let a: oci_client::secrets::RegistryAuth = internal_auth.into();
        a
    }

    // This function returns a hash of the PullManifestSettings struct.
    // The has is computed by doing a canonical JSON representation of
    // the struct.
    //
    // This method cannot error, because its value is used by the `cached`
    // macro, which doesn't allow error handling.
    // Because of that the method will return the '0' value when something goes
    // wrong during the serialization operation. This is very unlikely to happen
    pub fn hash(&self) -> String {
        let buf = match serde_json_canonicalizer::to_vec(self) {
            Ok(vec) => vec,
            Err(e) => {
                error!(err=?e, settings=?self, "Cannot perform canonical serialization");
                return "0".to_string();
            }
        };

        let mut hasher = Sha256::new();
        hasher.update(&buf);
        let result = hasher.finalize();
        result
            .iter()
            .map(|v| format!("{v:x}"))
            .collect::<Vec<String>>()
            .join("")
    }
}

// Pulls an OCI manifest.
// Details about this cache:
//   * the cache is time bound: cached values are purged after 60 seconds
//   * only successful results are cached
#[cached(
    time = 60,
    result = true,
    sync_writes = "default",
    key = "String",
    convert = r#"{ settings.hash() }"#,
    with_cached_flag = true
)]
async fn pull_manifest_cached(
    client: &mut oci_client::Client,
    settings: PullManifestSettings,
) -> Result<cached::Return<(oci_client::manifest::OciManifest, String)>> {
    let image = settings.image();
    let auth = settings.auth();
    client
        .pull_manifest(&image, &auth)
        .await
        .map_err(|e| SigstoreError::RegistryPullManifestError {
            image: image.whole(),
            error: e.to_string(),
        })
        .map(cached::Return::new)
}

/// Internal struct, used to calculate a unique hash of the pull referrers
/// settings. This is required to cache pull referrers results.
#[derive(Serialize, Debug)]
struct PullReferrersSettings {
    image: String,
    auth: super::config::Auth,
    artifact_type: Option<String>,
}

impl PullReferrersSettings {
    fn new(
        image: &oci_client::Reference,
        auth: &oci_client::secrets::RegistryAuth,
        artifact_type: Option<&str>,
    ) -> PullReferrersSettings {
        let image_str = image.whole();
        let auth_sigstore: super::config::Auth = From::from(auth);

        PullReferrersSettings {
            image: image_str,
            auth: auth_sigstore,
            artifact_type: artifact_type.map(str::to_owned),
        }
    }

    #[allow(clippy::unwrap_used)]
    pub fn image(&self) -> oci_client::Reference {
        // we can use `unwrap` here, because this will never fail
        let reference: oci_client::Reference = self.image.parse().unwrap();
        reference
    }

    pub fn auth(&self) -> oci_client::secrets::RegistryAuth {
        let internal_auth: &super::config::Auth = &self.auth;
        let a: oci_client::secrets::RegistryAuth = internal_auth.into();
        a
    }

    // This function returns a hash of the PullReferrersSettings struct.
    // The hash is computed by doing a canonical JSON representation of
    // the struct.
    //
    // This method cannot error, because its value is used by the `cached`
    // macro, which doesn't allow error handling.
    // Because of that the method will return the '0' value when something goes
    // wrong during the serialization operation. This is very unlikely to happen
    pub fn hash(&self) -> String {
        let buf = match serde_json_canonicalizer::to_vec(self) {
            Ok(vec) => vec,
            Err(e) => {
                error!(err=?e, settings=?self, "Cannot perform canonical serialization");
                return "0".to_string();
            }
        };

        let mut hasher = Sha256::new();
        hasher.update(&buf);
        let result = hasher.finalize();
        result
            .iter()
            .map(|v| format!("{v:x}"))
            .collect::<Vec<String>>()
            .join("")
    }
}

/// Pulls OCI referrers.
/// Details about this cache:
///   * the cache is time bound: cached values are purged after 60 seconds
///   * only successful results are cached
#[cached(
    time = 60,
    result = true,
    sync_writes = "default",
    key = "String",
    convert = r#"{ settings.hash() }"#,
    with_cached_flag = true
)]
async fn pull_referrers_cached(
    client: &mut oci_client::Client,
    settings: PullReferrersSettings,
) -> Result<cached::Return<oci_client::manifest::OciImageIndex>> {
    let image = settings.image();
    let auth = settings.auth();
    let artifact_type = settings.artifact_type.as_deref();
    client
        .auth(&image, &auth, oci_client::RegistryOperation::Pull)
        .await
        .map_err(|e| SigstoreError::RegistryFetchManifestError {
            image: image.whole(),
            error: e.to_string(),
        })?;
    client
        .pull_referrers(&image, artifact_type)
        .await
        .map_err(|e| SigstoreError::RegistryPullManifestError {
            image: image.whole(),
            error: e.to_string(),
        })
        .map(cached::Return::new)
}

impl ClientCapabilitiesDeps for OciCachingClient {}

#[async_trait]
impl ClientCapabilities for OciCachingClient {
    async fn fetch_manifest_digest(
        &mut self,
        image: &oci_client::Reference,
        auth: &oci_client::secrets::RegistryAuth,
    ) -> Result<String> {
        fetch_manifest_digest_cached(&mut self.registry_client, image, auth)
            .await
            .map(|digest| {
                if digest.was_cached {
                    debug!(?image, "Got image digest from cache");
                } else {
                    debug!(?image, "Got image digest by querying remote registry");
                }
                digest.value
            })
    }

    async fn pull(
        &mut self,
        image: &oci_client::Reference,
        auth: &oci_client::secrets::RegistryAuth,
        accepted_media_types: Vec<&str>,
    ) -> Result<oci_client::client::ImageData> {
        let pull_settings = PullSettings::new(image, auth, accepted_media_types);

        pull_cached(&mut self.registry_client, pull_settings)
            .await
            .map(|data| {
                if data.was_cached {
                    debug!(?image, "Got image data from cache");
                } else {
                    debug!(?image, "Got image data by querying remote registry");
                }
                data.value
            })
    }

    async fn pull_manifest(
        &mut self,
        image: &oci_client::Reference,
        auth: &oci_client::secrets::RegistryAuth,
    ) -> Result<(oci_client::manifest::OciManifest, String)> {
        let pull_manifest_settings = PullManifestSettings::new(image, auth);

        pull_manifest_cached(&mut self.registry_client, pull_manifest_settings)
            .await
            .map(|data| {
                if data.was_cached {
                    debug!(?image, "Got image manifest from cache");
                } else {
                    debug!(?image, "Got image manifest by querying remote registry");
                }
                data.value
            })
    }

    async fn push(
        &mut self,
        image_ref: &oci_client::Reference,
        layers: &[oci_client::client::ImageLayer],
        config: oci_client::client::Config,
        auth: &oci_client::secrets::RegistryAuth,
        manifest: Option<oci_client::manifest::OciImageManifest>,
    ) -> Result<oci_client::client::PushResponse> {
        self.registry_client
            .push(image_ref, layers, config, auth, manifest)
            .await
            .map_err(|e| SigstoreError::RegistryPushError {
                image: image_ref.whole(),
                error: e.to_string(),
            })
    }

    async fn pull_referrers(
        &mut self,
        image: &oci_client::Reference,
        auth: &oci_client::secrets::RegistryAuth,
        artifact_type: Option<&str>,
    ) -> Result<oci_client::manifest::OciImageIndex> {
        let settings = PullReferrersSettings::new(image, auth, artifact_type);
        pull_referrers_cached(&mut self.registry_client, settings)
            .await
            .map(|data| {
                if data.was_cached {
                    debug!(?image, "Got image referrers from cache");
                } else {
                    debug!(?image, "Got image referrers by querying remote registry");
                }
                data.value
            })
    }
}