ocilot 0.2.0

cli and library for interacting with OCI registries
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
use base64::Engine;
use bon::Builder;
use jiff::Timestamp;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use snafu::{OptionExt, ResultExt};
use std::env::consts;
use std::str::FromStr;
use std::{collections::HashMap, fmt};

/// Handles all the supported media type enumerations by this tool.
/// Since OCI specification allows custom types this is rather limited currently
/// but should be expanded to treat any unrecognized MediaType as a Custom variant
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MediaType {
    ImageIndex,
    Manifest,
    Config,
    Layer(Compression),
    DockerManifestList,
    DockerManifest,
    DockerContainerImage,
    DockerImageRootfs(Compression),
}

impl MediaType {
    pub fn compression(&self) -> Compression {
        match self {
            Self::DockerImageRootfs(compression) => {
                if *compression == Compression::None {
                    Compression::Gzip
                } else {
                    compression.clone()
                }
            }
            Self::Layer(compression) => compression.clone(),
            _ => Compression::None,
        }
    }
}

impl Serialize for MediaType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let string = match self {
            Self::ImageIndex => "application/vnd.oci.image.index.v1+json".into(),
            Self::Manifest => "application/vnd.oci.image.manifest.v1+json".into(),
            Self::Config => "application/vnd.oci.image.config.v1+json".into(),
            Self::Layer(compression) => format!(
                "application/vnd.oci.image.layer.v1.tar{}",
                compression.to_ext()
            ),
            Self::DockerManifestList => {
                "application/vnd.docker.distribution.manifest.list.v2+json".into()
            }
            Self::DockerManifest => "application/vnd.docker.distribution.manifest.v2+json".into(),
            Self::DockerContainerImage => "application/vnd.docker.container.image.v1+json".into(),
            Self::DockerImageRootfs(compression) => format!(
                "application/vnd.docker.image.rootfs.diff.tar{}",
                compression.to_ext()
            ),
        };
        serializer.serialize_str(string.as_str())
    }
}

impl<'de> Deserialize<'de> for MediaType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let string = String::deserialize(deserializer)?;
        if string.starts_with("application/vnd.docker.image.rootfs.diff.tar") {
            let compression = Compression::new(string.as_str());
            Ok(MediaType::DockerImageRootfs(compression))
        } else if string.starts_with("application/vnd.oci.image.layer.v1.tar") {
            let compression = Compression::new(string.as_str());
            Ok(MediaType::Layer(compression))
        } else {
            match string.as_ref() {
                "application/vnd.docker.distribution.manifest.list.v2+json" => {
                    Ok(MediaType::DockerManifestList)
                }
                "application/vnd.docker.distribution.manifest.v2+json" => {
                    Ok(MediaType::DockerManifest)
                }
                "application/vnd.docker.container.image.v1+json" => {
                    Ok(MediaType::DockerContainerImage)
                }
                "application/vnd.oci.image.manifest.v1+json" => Ok(MediaType::Manifest),
                "application/vnd.oci.image.index.v1+json" => Ok(MediaType::ImageIndex),
                "application/vnd.oci.image.config.v1+json" => Ok(MediaType::Config),
                variant => Err(D::Error::unknown_variant(
                    variant,
                    &[
                        "application/vnd.docker.image.rootfs.diff.tar.*",
                        "application/vnd.docker.container.image.v1+json",
                        "application/vnd.docker.distribution.manifest.list.v2+json",
                        "application/vnd.docker.distribution.manifest.v2+json",
                        "application/vnd.oci.image.index.v1+json",
                        "application/vnd.oci.image.manifest.v1+json",
                        "application/vnd.oci.image.config.v1+json",
                    ],
                )),
            }
        }
    }
}

/// Helper enum to specify the compression algorithm used
/// with a layer
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Compression {
    Gzip,
    Bzip2,
    Lz4,
    Xz,
    Zstd,
    None,
}

impl Compression {
    pub fn new(string: &str) -> Self {
        if string.ends_with(".gz") || string.ends_with(".gzip2") {
            Compression::Gzip
        } else if string.ends_with(".xz") {
            Compression::Xz
        } else if string.ends_with(".lz4") {
            Compression::Lz4
        } else if string.ends_with(".zst") {
            Compression::Zstd
        } else if string.ends_with(".bz2") || string.ends_with(".bzip2") {
            Compression::Bzip2
        } else {
            Compression::None
        }
    }

    pub fn to_ext(&self) -> &str {
        match self {
            Self::Gzip => ".gz",
            Self::Bzip2 => ".bz2",
            Self::Lz4 => ".lz4",
            Self::Xz => ".xz",
            Self::Zstd => ".zst",
            Self::None => "",
        }
    }
}

/// This defines the format of a manifest.json file in a tarball representation of
/// an image that docker/podman/finch/nerdctl can use load on.
#[derive(Builder, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct TarballManifest {
    #[builder(into)]
    pub config: String,
    #[builder(into)]
    pub repo_tags: Vec<String>,
    #[builder(into)]
    pub layers: Vec<String>,
}

/// Represents the frequently used platform identifiers both in json format and as the
/// commandline <os>/<architecture> format.
#[derive(Builder, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Platform {
    #[builder(into)]
    pub architecture: String,
    #[builder(into)]
    pub os: String,
}

impl Default for Platform {
    fn default() -> Self {
        let arch = match consts::ARCH {
            "arm" | "aarch64" | "longaarch64" => "arm64",
            _ => "amd64",
        };
        Self {
            os: "linux".to_string(),
            architecture: arch.to_string(),
        }
    }
}

impl FromStr for Platform {
    type Err = crate::error::Error;

    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
        let (os, architecture) = value.split_once('/').context(
            crate::error::InvalidPlatformFormatSnafu {
                value: value.to_string(),
            },
        )?;
        snafu::ensure!(
            !os.is_empty() && !architecture.is_empty(),
            crate::error::InvalidPlatformEmptySnafu {
                value: value.to_string(),
            }
        );
        Ok(Self {
            architecture: architecture.to_string(),
            os: os.to_string(),
        })
    }
}

impl TryFrom<String> for Platform {
    type Error = crate::error::Error;

    fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
        value.parse()
    }
}

impl fmt::Display for Platform {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("{}/{}", self.os, self.architecture))
    }
}

/// Represents the config block inside of an image config and frequently utilized fields
#[derive(Builder, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct Config {
    #[builder(into)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    #[builder(into)]
    #[serde(default)]
    pub env: Vec<String>,
    #[builder(into)]
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cmd: Vec<String>,
    #[builder(into)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub working_dir: Option<String>,
    #[builder(into)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_build: Option<String>,
    #[builder(into)]
    #[serde(default)]
    pub args_escaped: bool,
    #[builder(into)]
    #[serde(default)]
    pub labels: HashMap<String, String>,
}

/// Represents a history log entry in an image config
#[derive(Builder, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub struct History {
    #[builder(into)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created: Option<Timestamp>,
    #[builder(into)]
    pub created_by: String,
    #[builder(into)]
    pub comment: String,
    #[builder(into)]
    #[serde(default)]
    pub empty_layer: bool,
}

/// Represents the shape of an image configuration blob
#[derive(Builder, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ImageConfig {
    #[builder(into)]
    pub architecture: String,
    #[builder(into)]
    pub config: Config,
    #[builder(into)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created: Option<Timestamp>,
    #[builder(into)]
    pub history: Vec<History>,
    #[builder(into)]
    pub os: String,
}

/// Helper structure that represents the response type of a
/// list tags operation on an oci registry.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct TagList {
    pub name: String,
    pub tags: Vec<String>,
}

/// Helper structure that represents the response type of a
/// catalog operation on an oci registry
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct RepositoryList {
    pub repositories: Vec<String>,
}

/// The officially supported error codes as defined by the OCI
/// distribution specification.
#[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ErrorCode {
    /// Blob unknown to registry.
    BlobUnknown,
    /// Blob upload invalid.
    BlobUploadInvalid,
    /// Blob upload unknown to registry.
    BlobUploadUnknown,
    /// Provided digest did not match uploaded content.
    DigestInvalid,
    /// Blob unknown to registry.
    ManifestBlobUnknown,
    /// Manifest invalid.
    ManifestInvalid,
    /// Manifest unknown.
    ManifestUnknown,
    /// Invalid repository name.
    NameInvalid,
    /// Repository name not known to registry.
    NameUnknown,
    /// Provided length did not match content length.
    SizeInvalid,
    /// Authentication required.
    Unauthorized,
    /// Requested access to the resource is denied.
    Denied,
    /// The operation is unsupported.
    Unsupported,
    /// Too many requests.
    #[serde(rename = "TOOMANYREQUESTS")]
    TooManyRequests,
}

/// The standard specification of an error returned from an OCI registry.
#[derive(Serialize, Deserialize, Debug)]
pub struct ErrorInfo {
    pub code: ErrorCode,
    #[serde(default)]
    pub message: Option<String>,
    #[serde(default)]
    pub detail: Option<String>,
}

impl fmt::Display for ErrorInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let message = if let Some(message) = self.message.as_ref() {
            if let Some(detail) = self.detail.as_ref() {
                format!("{message}: {detail}")
            } else {
                message.clone()
            }
        } else if let Some(detail) = self.detail.as_ref() {
            detail.clone()
        } else {
            "unknown error occured".to_string()
        };
        let code = match self.code {
            ErrorCode::BlobUnknown => "blob unknown",
            ErrorCode::BlobUploadInvalid => "blob upload invalid",
            ErrorCode::BlobUploadUnknown => "blob upload unknown",
            ErrorCode::Denied => "denied",
            ErrorCode::DigestInvalid => "digest invalid",
            ErrorCode::ManifestBlobUnknown => "manifest blob unknown",
            ErrorCode::ManifestInvalid => "manifest invalid",
            ErrorCode::ManifestUnknown => "manifest unknown",
            ErrorCode::NameInvalid => "name invalid",
            ErrorCode::NameUnknown => "name unknown",
            ErrorCode::SizeInvalid => "size invalid",
            ErrorCode::TooManyRequests => "too many requests",
            ErrorCode::Unauthorized => "unauthorized",
            ErrorCode::Unsupported => "unsupported",
        };
        f.write_fmt(format_args!("[{code}] {message}"))
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ErrorResponse {
    pub errors: Vec<ErrorInfo>,
}

impl fmt::Display for ErrorResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "{}",
            self.errors
                .iter()
                .map(|x| x.to_string())
                .collect::<Vec<_>>()
                .join("\n")
        ))
    }
}

/// Represents an authorization token
#[derive(Debug, Clone)]
pub enum Token {
    Bearer(String),
    Basic { username: String, password: String },
}

impl Token {
    /// Build a token from a parsed docker auth file entry.
    ///
    /// Returns `Ok(None)` when the entry has neither an identity token nor
    /// a basic auth blob. Returns `Err(InvalidAuth)` when the basic auth
    /// blob is present but cannot be decoded as `username:password`. This
    /// replaces the previous `unwrap`-based implementation that would
    /// panic on malformed config files (#9).
    pub fn parse(value: DockerAuth) -> Result<Option<Self>, crate::error::Error> {
        if let Some(identitytoken) = value.identitytoken {
            return Ok(Some(Self::Bearer(identitytoken)));
        }
        let Some(auth) = value.auth else {
            return Ok(None);
        };
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(auth)
            .context(crate::error::AuthBase64DecodeSnafu {
                context: "docker auth",
            })?;
        let decoded =
            std::str::from_utf8(&decoded).context(crate::error::AuthUtf8Snafu {
                context: "docker auth",
            })?;
        let (username, password) =
            decoded
                .split_once(':')
                .context(crate::error::AuthMissingSeparatorSnafu {
                    context: "docker auth",
                })?;
        Ok(Some(Self::Basic {
            username: username.to_string(),
            password: password.to_string(),
        }))
    }
}

/// View model for the common docker/finch config for finding authorizations
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
pub struct DockerConfig {
    #[serde(default)]
    pub auths: HashMap<String, DockerAuth>,
}

#[derive(Serialize, Deserialize, Debug, Default, Clone)]
pub struct DockerAuth {
    pub auth: Option<String>,
    pub identitytoken: Option<String>,
}

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

    #[test]
    fn platform_parses_valid() {
        let p: Platform = "linux/amd64".parse().expect("should parse");
        assert_eq!(p.os, "linux");
        assert_eq!(p.architecture, "amd64");
    }

    #[test]
    fn platform_rejects_missing_separator() {
        let err = "linux".parse::<Platform>().expect_err("should fail");
        assert!(matches!(
            err,
            crate::error::Error::InvalidPlatformFormat { .. }
        ));
    }

    #[test]
    fn platform_rejects_empty_components() {
        assert!(matches!(
            "/amd64".parse::<Platform>(),
            Err(crate::error::Error::InvalidPlatformEmpty { .. })
        ));
        assert!(matches!(
            "linux/".parse::<Platform>(),
            Err(crate::error::Error::InvalidPlatformEmpty { .. })
        ));
    }

    #[test]
    fn platform_try_from_string_round_trips_display() {
        let p = Platform::try_from("linux/arm64".to_string()).unwrap();
        assert_eq!(p.to_string(), "linux/arm64");
    }
}