zlayer-registry 0.12.8

OCI container registry client with blob caching
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
//! OCI image configuration parsing
//!
//! Parses the OCI image config blob to extract container runtime defaults
//! such as `Entrypoint`, `Cmd`, `WorkingDir`, `Env`, and `User`.
//!
//! The OCI image config JSON has the following structure:
//! ```json
//! {
//!   "config": {
//!     "Entrypoint": ["/usr/bin/myapp"],
//!     "Cmd": ["--port", "8080"],
//!     "WorkingDir": "/app",
//!     "Env": ["PATH=/usr/local/bin:/usr/bin"],
//!     "User": "1000:1000",
//!     "ExposedPorts": {"8080/tcp": {}},
//!     "Volumes": {"/data": {}},
//!     "Labels": {"maintainer": "someone"}
//!   },
//!   "rootfs": { ... },
//!   "history": [ ... ]
//! }
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Container runtime configuration extracted from an OCI image config blob.
///
/// This represents the `config` object inside the OCI image configuration JSON.
/// Fields map to the corresponding Docker/OCI image config spec fields.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ImageConfig {
    /// The entrypoint for the container (e.g., `["/usr/bin/myapp"]`).
    ///
    /// When both `entrypoint` and `cmd` are set, `cmd` provides default
    /// arguments to the entrypoint.
    #[serde(rename = "Entrypoint")]
    pub entrypoint: Option<Vec<String>>,

    /// The default command for the container (e.g., `["--port", "8080"]`).
    ///
    /// If `entrypoint` is also set, `cmd` provides default arguments.
    /// If `entrypoint` is not set, `cmd` is the full command to run.
    #[serde(rename = "Cmd")]
    pub cmd: Option<Vec<String>>,

    /// The working directory for the container process.
    #[serde(rename = "WorkingDir")]
    pub working_dir: Option<String>,

    /// Environment variables in `KEY=VALUE` format.
    #[serde(rename = "Env")]
    pub env: Option<Vec<String>>,

    /// The user (and optionally group) to run the container process as.
    /// Format: `"user"`, `"user:group"`, `"uid"`, or `"uid:gid"`.
    #[serde(rename = "User")]
    pub user: Option<String>,

    /// Ports exposed by the container. Keys are in `"port/protocol"` format
    /// (e.g., `"8080/tcp"`). Values are empty objects.
    #[serde(rename = "ExposedPorts")]
    pub exposed_ports: Option<HashMap<String, serde_json::Value>>,

    /// Volumes defined by the image. Keys are mount paths, values are empty objects.
    #[serde(rename = "Volumes")]
    pub volumes: Option<HashMap<String, serde_json::Value>>,

    /// Arbitrary metadata labels.
    #[serde(rename = "Labels")]
    pub labels: Option<HashMap<String, String>>,

    /// Signal to send to the container to stop it (e.g., `"SIGTERM"`).
    #[serde(rename = "StopSignal")]
    pub stop_signal: Option<String>,

    /// Custom shell for RUN instructions (SHELL instruction).
    /// Format: `["/bin/bash", "-c"]`.
    #[serde(rename = "Shell")]
    pub shell: Option<Vec<String>>,

    /// Healthcheck configuration.
    #[serde(rename = "Healthcheck")]
    pub healthcheck: Option<ImageHealthcheck>,
}

/// Healthcheck configuration from OCI image config.
///
/// Durations are stored in nanoseconds (matching the OCI/Docker spec).
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ImageHealthcheck {
    /// Test command. First element is the test type: `"CMD"`, `"CMD-SHELL"`, or `"NONE"`.
    #[serde(rename = "Test")]
    pub test: Option<Vec<String>>,
    /// Interval between checks in nanoseconds.
    #[serde(rename = "Interval")]
    pub interval: Option<u64>,
    /// Timeout per check in nanoseconds.
    #[serde(rename = "Timeout")]
    pub timeout: Option<u64>,
    /// Start period in nanoseconds.
    #[serde(rename = "StartPeriod")]
    pub start_period: Option<u64>,
    /// Retries before marking unhealthy.
    #[serde(rename = "Retries")]
    pub retries: Option<u32>,
}

impl ImageConfig {
    /// Build the full command line by combining entrypoint and cmd.
    ///
    /// Follows Docker/OCI semantics:
    /// - If entrypoint is set, it is the executable and cmd provides default args
    /// - If only cmd is set, it is the full command
    /// - If neither is set, returns None
    #[must_use]
    pub fn full_command(&self) -> Option<Vec<String>> {
        match (&self.entrypoint, &self.cmd) {
            (Some(ep), Some(cmd)) => {
                let mut full = ep.clone();
                full.extend(cmd.iter().cloned());
                Some(full)
            }
            (Some(ep), None) => Some(ep.clone()),
            (None, Some(cmd)) => Some(cmd.clone()),
            (None, None) => None,
        }
    }
}

/// Top-level OCI image configuration JSON structure.
///
/// This wraps the actual container config along with rootfs and history
/// information. We expose `config` for runtime defaults and the top-level
/// `os` field for platform-aware dispatch (see
/// [`crate::fetch_image_os`]).
#[derive(Debug, Deserialize)]
pub(crate) struct OciImageConfigRoot {
    /// The container runtime configuration.
    pub config: Option<ImageConfig>,
    /// Operating system the image targets, as written by the image builder
    /// (`"linux"` / `"windows"` / `"darwin"`). Present on any conforming OCI
    /// image config; absent on malformed or legacy payloads, in which case
    /// callers should fall through to a platform-agnostic default.
    #[serde(default)]
    pub os: Option<String>,
    /// Operating system version the image targets, when the builder records
    /// one. For Windows images this is the host build identifier (e.g.
    /// `"10.0.20348.2031"`) that drives isolation-mode auto-resolution; for
    /// most Linux images this is absent.
    #[serde(
        rename = "os.version",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub os_version: Option<String>,
}

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

    #[test]
    fn test_parse_full_config() {
        let json = r#"{
            "config": {
                "Entrypoint": ["/usr/bin/node"],
                "Cmd": ["server.js"],
                "WorkingDir": "/app",
                "Env": ["NODE_ENV=production", "PORT=3000"],
                "User": "1000:1000",
                "ExposedPorts": {"3000/tcp": {}},
                "Volumes": {"/data": {}},
                "Labels": {"maintainer": "test@example.com"},
                "StopSignal": "SIGTERM"
            },
            "rootfs": {
                "type": "layers",
                "diff_ids": ["sha256:abc123"]
            }
        }"#;

        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
        let config = root.config.unwrap();

        assert_eq!(config.entrypoint, Some(vec!["/usr/bin/node".to_string()]));
        assert_eq!(config.cmd, Some(vec!["server.js".to_string()]));
        assert_eq!(config.working_dir, Some("/app".to_string()));
        assert_eq!(
            config.env,
            Some(vec![
                "NODE_ENV=production".to_string(),
                "PORT=3000".to_string()
            ])
        );
        assert_eq!(config.user, Some("1000:1000".to_string()));
        assert!(config.exposed_ports.is_some());
        assert!(config.exposed_ports.unwrap().contains_key("3000/tcp"));
        assert!(config.volumes.is_some());
        assert!(config.volumes.unwrap().contains_key("/data"));
        assert_eq!(
            config.labels.as_ref().unwrap().get("maintainer"),
            Some(&"test@example.com".to_string())
        );
        assert_eq!(config.stop_signal, Some("SIGTERM".to_string()));
    }

    #[test]
    fn test_parse_minimal_config() {
        let json = r#"{
            "config": {},
            "rootfs": {
                "type": "layers",
                "diff_ids": []
            }
        }"#;

        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
        let config = root.config.unwrap();

        assert!(config.entrypoint.is_none());
        assert!(config.cmd.is_none());
        assert!(config.working_dir.is_none());
        assert!(config.env.is_none());
        assert!(config.user.is_none());
    }

    #[test]
    fn test_parse_null_config() {
        let json = r#"{
            "config": null,
            "rootfs": {
                "type": "layers",
                "diff_ids": []
            }
        }"#;

        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
        assert!(root.config.is_none());
    }

    #[test]
    fn test_parse_missing_config() {
        // Some images might not have a config section at all
        let json = r#"{
            "rootfs": {
                "type": "layers",
                "diff_ids": []
            }
        }"#;

        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
        assert!(root.config.is_none());
    }

    #[test]
    fn test_parse_docker_hub_nginx_like() {
        // Realistic config from a Docker Hub nginx image
        let json = r#"{
            "config": {
                "Entrypoint": ["/docker-entrypoint.sh"],
                "Cmd": ["nginx", "-g", "daemon off;"],
                "WorkingDir": "",
                "Env": [
                    "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                    "NGINX_VERSION=1.25.3"
                ],
                "ExposedPorts": {
                    "80/tcp": {}
                },
                "StopSignal": "SIGQUIT"
            },
            "rootfs": {
                "type": "layers",
                "diff_ids": [
                    "sha256:aaa",
                    "sha256:bbb"
                ]
            }
        }"#;

        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
        let config = root.config.unwrap();

        assert_eq!(
            config.entrypoint,
            Some(vec!["/docker-entrypoint.sh".to_string()])
        );
        assert_eq!(
            config.cmd,
            Some(vec![
                "nginx".to_string(),
                "-g".to_string(),
                "daemon off;".to_string()
            ])
        );
        // Empty string working_dir should deserialize as Some("")
        assert_eq!(config.working_dir, Some(String::new()));
        assert_eq!(config.stop_signal, Some("SIGQUIT".to_string()));
    }

    #[test]
    fn test_parse_cmd_only_image() {
        // Images like ubuntu:latest only have Cmd, no Entrypoint
        let json = r#"{
            "config": {
                "Cmd": ["/bin/bash"],
                "Env": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"]
            },
            "rootfs": {
                "type": "layers",
                "diff_ids": ["sha256:abc"]
            }
        }"#;

        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
        let config = root.config.unwrap();

        assert!(config.entrypoint.is_none());
        assert_eq!(config.cmd, Some(vec!["/bin/bash".to_string()]));
    }

    #[test]
    fn test_full_command_both_set() {
        let config = ImageConfig {
            entrypoint: Some(vec!["/usr/bin/node".to_string()]),
            cmd: Some(vec![
                "server.js".to_string(),
                "--port".to_string(),
                "3000".to_string(),
            ]),
            ..Default::default()
        };

        assert_eq!(
            config.full_command(),
            Some(vec![
                "/usr/bin/node".to_string(),
                "server.js".to_string(),
                "--port".to_string(),
                "3000".to_string(),
            ])
        );
    }

    #[test]
    fn test_full_command_entrypoint_only() {
        let config = ImageConfig {
            entrypoint: Some(vec!["/usr/bin/myapp".to_string()]),
            ..Default::default()
        };

        assert_eq!(
            config.full_command(),
            Some(vec!["/usr/bin/myapp".to_string()])
        );
    }

    #[test]
    fn test_full_command_cmd_only() {
        let config = ImageConfig {
            cmd: Some(vec!["/bin/bash".to_string()]),
            ..Default::default()
        };

        assert_eq!(config.full_command(), Some(vec!["/bin/bash".to_string()]));
    }

    #[test]
    fn test_full_command_neither_set() {
        let config = ImageConfig::default();
        assert!(config.full_command().is_none());
    }

    #[test]
    fn test_image_config_default() {
        let config = ImageConfig::default();
        assert!(config.entrypoint.is_none());
        assert!(config.cmd.is_none());
        assert!(config.working_dir.is_none());
        assert!(config.env.is_none());
        assert!(config.user.is_none());
        assert!(config.exposed_ports.is_none());
        assert!(config.volumes.is_none());
        assert!(config.labels.is_none());
        assert!(config.stop_signal.is_none());
    }

    #[test]
    fn test_image_config_clone() {
        let config = ImageConfig {
            entrypoint: Some(vec!["/bin/sh".to_string()]),
            cmd: Some(vec!["-c".to_string(), "echo hello".to_string()]),
            working_dir: Some("/tmp".to_string()),
            env: Some(vec!["FOO=bar".to_string()]),
            user: Some("nobody".to_string()),
            exposed_ports: None,
            volumes: None,
            labels: Some(HashMap::from([("key".to_string(), "value".to_string())])),
            stop_signal: None,
            shell: None,
            healthcheck: None,
        };

        let cloned = config.clone();
        assert_eq!(cloned.entrypoint, config.entrypoint);
        assert_eq!(cloned.cmd, config.cmd);
        assert_eq!(cloned.working_dir, config.working_dir);
        assert_eq!(cloned.env, config.env);
        assert_eq!(cloned.user, config.user);
        assert_eq!(cloned.labels, config.labels);
    }

    #[test]
    fn test_parse_extra_fields_ignored() {
        // The OCI config has many more fields (architecture, os, etc.)
        // that we don't care about. Verify they are silently ignored.
        let json = r#"{
            "architecture": "amd64",
            "os": "linux",
            "config": {
                "Entrypoint": ["/app"],
                "Hostname": "",
                "Domainname": "",
                "AttachStdout": false,
                "Tty": false,
                "ArgsEscaped": true
            },
            "rootfs": {
                "type": "layers",
                "diff_ids": ["sha256:abc"]
            },
            "history": [
                {"created": "2024-01-01T00:00:00Z", "created_by": "COPY . /app"}
            ]
        }"#;

        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
        let config = root.config.unwrap();
        assert_eq!(config.entrypoint, Some(vec!["/app".to_string()]));
    }
}