Skip to main content

zlayer_registry/
image_config.rs

1//! OCI image configuration parsing
2//!
3//! Parses the OCI image config blob to extract container runtime defaults
4//! such as `Entrypoint`, `Cmd`, `WorkingDir`, `Env`, and `User`.
5//!
6//! The OCI image config JSON has the following structure:
7//! ```json
8//! {
9//!   "config": {
10//!     "Entrypoint": ["/usr/bin/myapp"],
11//!     "Cmd": ["--port", "8080"],
12//!     "WorkingDir": "/app",
13//!     "Env": ["PATH=/usr/local/bin:/usr/bin"],
14//!     "User": "1000:1000",
15//!     "ExposedPorts": {"8080/tcp": {}},
16//!     "Volumes": {"/data": {}},
17//!     "Labels": {"maintainer": "someone"}
18//!   },
19//!   "rootfs": { ... },
20//!   "history": [ ... ]
21//! }
22//! ```
23
24use serde::{Deserialize, Serialize};
25use std::collections::HashMap;
26
27/// Container runtime configuration extracted from an OCI image config blob.
28///
29/// This represents the `config` object inside the OCI image configuration JSON.
30/// Fields map to the corresponding Docker/OCI image config spec fields.
31#[derive(Debug, Clone, Default, Deserialize, Serialize)]
32pub struct ImageConfig {
33    /// The entrypoint for the container (e.g., `["/usr/bin/myapp"]`).
34    ///
35    /// When both `entrypoint` and `cmd` are set, `cmd` provides default
36    /// arguments to the entrypoint.
37    #[serde(rename = "Entrypoint")]
38    pub entrypoint: Option<Vec<String>>,
39
40    /// The default command for the container (e.g., `["--port", "8080"]`).
41    ///
42    /// If `entrypoint` is also set, `cmd` provides default arguments.
43    /// If `entrypoint` is not set, `cmd` is the full command to run.
44    #[serde(rename = "Cmd")]
45    pub cmd: Option<Vec<String>>,
46
47    /// The working directory for the container process.
48    #[serde(rename = "WorkingDir")]
49    pub working_dir: Option<String>,
50
51    /// Environment variables in `KEY=VALUE` format.
52    #[serde(rename = "Env")]
53    pub env: Option<Vec<String>>,
54
55    /// The user (and optionally group) to run the container process as.
56    /// Format: `"user"`, `"user:group"`, `"uid"`, or `"uid:gid"`.
57    #[serde(rename = "User")]
58    pub user: Option<String>,
59
60    /// Ports exposed by the container. Keys are in `"port/protocol"` format
61    /// (e.g., `"8080/tcp"`). Values are empty objects.
62    #[serde(rename = "ExposedPorts")]
63    pub exposed_ports: Option<HashMap<String, serde_json::Value>>,
64
65    /// Volumes defined by the image. Keys are mount paths, values are empty objects.
66    #[serde(rename = "Volumes")]
67    pub volumes: Option<HashMap<String, serde_json::Value>>,
68
69    /// Arbitrary metadata labels.
70    #[serde(rename = "Labels")]
71    pub labels: Option<HashMap<String, String>>,
72
73    /// Signal to send to the container to stop it (e.g., `"SIGTERM"`).
74    #[serde(rename = "StopSignal")]
75    pub stop_signal: Option<String>,
76
77    /// Custom shell for RUN instructions (SHELL instruction).
78    /// Format: `["/bin/bash", "-c"]`.
79    #[serde(rename = "Shell")]
80    pub shell: Option<Vec<String>>,
81
82    /// Healthcheck configuration.
83    #[serde(rename = "Healthcheck")]
84    pub healthcheck: Option<ImageHealthcheck>,
85}
86
87/// Healthcheck configuration from OCI image config.
88///
89/// Durations are stored in nanoseconds (matching the OCI/Docker spec).
90#[derive(Debug, Clone, Default, Deserialize, Serialize)]
91pub struct ImageHealthcheck {
92    /// Test command. First element is the test type: `"CMD"`, `"CMD-SHELL"`, or `"NONE"`.
93    #[serde(rename = "Test")]
94    pub test: Option<Vec<String>>,
95    /// Interval between checks in nanoseconds.
96    #[serde(rename = "Interval")]
97    pub interval: Option<u64>,
98    /// Timeout per check in nanoseconds.
99    #[serde(rename = "Timeout")]
100    pub timeout: Option<u64>,
101    /// Start period in nanoseconds.
102    #[serde(rename = "StartPeriod")]
103    pub start_period: Option<u64>,
104    /// Retries before marking unhealthy.
105    #[serde(rename = "Retries")]
106    pub retries: Option<u32>,
107}
108
109impl ImageConfig {
110    /// Build the full command line by combining entrypoint and cmd.
111    ///
112    /// Follows Docker/OCI semantics:
113    /// - If entrypoint is set, it is the executable and cmd provides default args
114    /// - If only cmd is set, it is the full command
115    /// - If neither is set, returns None
116    #[must_use]
117    pub fn full_command(&self) -> Option<Vec<String>> {
118        match (&self.entrypoint, &self.cmd) {
119            (Some(ep), Some(cmd)) => {
120                let mut full = ep.clone();
121                full.extend(cmd.iter().cloned());
122                Some(full)
123            }
124            (Some(ep), None) => Some(ep.clone()),
125            (None, Some(cmd)) => Some(cmd.clone()),
126            (None, None) => None,
127        }
128    }
129}
130
131/// Top-level OCI image configuration JSON structure.
132///
133/// This wraps the actual container config along with rootfs and history
134/// information. We expose `config` for runtime defaults and the top-level
135/// `os` field for platform-aware dispatch (see
136/// [`crate::fetch_image_os`]).
137#[derive(Debug, Deserialize)]
138pub(crate) struct OciImageConfigRoot {
139    /// The container runtime configuration.
140    pub config: Option<ImageConfig>,
141    /// Operating system the image targets, as written by the image builder
142    /// (`"linux"` / `"windows"` / `"darwin"`). Present on any conforming OCI
143    /// image config; absent on malformed or legacy payloads, in which case
144    /// callers should fall through to a platform-agnostic default.
145    #[serde(default)]
146    pub os: Option<String>,
147    /// Operating system version the image targets, when the builder records
148    /// one. For Windows images this is the host build identifier (e.g.
149    /// `"10.0.20348.2031"`) that drives isolation-mode auto-resolution; for
150    /// most Linux images this is absent.
151    #[serde(
152        rename = "os.version",
153        default,
154        skip_serializing_if = "Option::is_none"
155    )]
156    pub os_version: Option<String>,
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn test_parse_full_config() {
165        let json = r#"{
166            "config": {
167                "Entrypoint": ["/usr/bin/node"],
168                "Cmd": ["server.js"],
169                "WorkingDir": "/app",
170                "Env": ["NODE_ENV=production", "PORT=3000"],
171                "User": "1000:1000",
172                "ExposedPorts": {"3000/tcp": {}},
173                "Volumes": {"/data": {}},
174                "Labels": {"maintainer": "test@example.com"},
175                "StopSignal": "SIGTERM"
176            },
177            "rootfs": {
178                "type": "layers",
179                "diff_ids": ["sha256:abc123"]
180            }
181        }"#;
182
183        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
184        let config = root.config.unwrap();
185
186        assert_eq!(config.entrypoint, Some(vec!["/usr/bin/node".to_string()]));
187        assert_eq!(config.cmd, Some(vec!["server.js".to_string()]));
188        assert_eq!(config.working_dir, Some("/app".to_string()));
189        assert_eq!(
190            config.env,
191            Some(vec![
192                "NODE_ENV=production".to_string(),
193                "PORT=3000".to_string()
194            ])
195        );
196        assert_eq!(config.user, Some("1000:1000".to_string()));
197        assert!(config.exposed_ports.is_some());
198        assert!(config.exposed_ports.unwrap().contains_key("3000/tcp"));
199        assert!(config.volumes.is_some());
200        assert!(config.volumes.unwrap().contains_key("/data"));
201        assert_eq!(
202            config.labels.as_ref().unwrap().get("maintainer"),
203            Some(&"test@example.com".to_string())
204        );
205        assert_eq!(config.stop_signal, Some("SIGTERM".to_string()));
206    }
207
208    #[test]
209    fn test_parse_minimal_config() {
210        let json = r#"{
211            "config": {},
212            "rootfs": {
213                "type": "layers",
214                "diff_ids": []
215            }
216        }"#;
217
218        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
219        let config = root.config.unwrap();
220
221        assert!(config.entrypoint.is_none());
222        assert!(config.cmd.is_none());
223        assert!(config.working_dir.is_none());
224        assert!(config.env.is_none());
225        assert!(config.user.is_none());
226    }
227
228    #[test]
229    fn test_parse_null_config() {
230        let json = r#"{
231            "config": null,
232            "rootfs": {
233                "type": "layers",
234                "diff_ids": []
235            }
236        }"#;
237
238        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
239        assert!(root.config.is_none());
240    }
241
242    #[test]
243    fn test_parse_missing_config() {
244        // Some images might not have a config section at all
245        let json = r#"{
246            "rootfs": {
247                "type": "layers",
248                "diff_ids": []
249            }
250        }"#;
251
252        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
253        assert!(root.config.is_none());
254    }
255
256    #[test]
257    fn test_parse_docker_hub_nginx_like() {
258        // Realistic config from a Docker Hub nginx image
259        let json = r#"{
260            "config": {
261                "Entrypoint": ["/docker-entrypoint.sh"],
262                "Cmd": ["nginx", "-g", "daemon off;"],
263                "WorkingDir": "",
264                "Env": [
265                    "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
266                    "NGINX_VERSION=1.25.3"
267                ],
268                "ExposedPorts": {
269                    "80/tcp": {}
270                },
271                "StopSignal": "SIGQUIT"
272            },
273            "rootfs": {
274                "type": "layers",
275                "diff_ids": [
276                    "sha256:aaa",
277                    "sha256:bbb"
278                ]
279            }
280        }"#;
281
282        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
283        let config = root.config.unwrap();
284
285        assert_eq!(
286            config.entrypoint,
287            Some(vec!["/docker-entrypoint.sh".to_string()])
288        );
289        assert_eq!(
290            config.cmd,
291            Some(vec![
292                "nginx".to_string(),
293                "-g".to_string(),
294                "daemon off;".to_string()
295            ])
296        );
297        // Empty string working_dir should deserialize as Some("")
298        assert_eq!(config.working_dir, Some(String::new()));
299        assert_eq!(config.stop_signal, Some("SIGQUIT".to_string()));
300    }
301
302    #[test]
303    fn test_parse_cmd_only_image() {
304        // Images like ubuntu:latest only have Cmd, no Entrypoint
305        let json = r#"{
306            "config": {
307                "Cmd": ["/bin/bash"],
308                "Env": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"]
309            },
310            "rootfs": {
311                "type": "layers",
312                "diff_ids": ["sha256:abc"]
313            }
314        }"#;
315
316        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
317        let config = root.config.unwrap();
318
319        assert!(config.entrypoint.is_none());
320        assert_eq!(config.cmd, Some(vec!["/bin/bash".to_string()]));
321    }
322
323    #[test]
324    fn test_full_command_both_set() {
325        let config = ImageConfig {
326            entrypoint: Some(vec!["/usr/bin/node".to_string()]),
327            cmd: Some(vec![
328                "server.js".to_string(),
329                "--port".to_string(),
330                "3000".to_string(),
331            ]),
332            ..Default::default()
333        };
334
335        assert_eq!(
336            config.full_command(),
337            Some(vec![
338                "/usr/bin/node".to_string(),
339                "server.js".to_string(),
340                "--port".to_string(),
341                "3000".to_string(),
342            ])
343        );
344    }
345
346    #[test]
347    fn test_full_command_entrypoint_only() {
348        let config = ImageConfig {
349            entrypoint: Some(vec!["/usr/bin/myapp".to_string()]),
350            ..Default::default()
351        };
352
353        assert_eq!(
354            config.full_command(),
355            Some(vec!["/usr/bin/myapp".to_string()])
356        );
357    }
358
359    #[test]
360    fn test_full_command_cmd_only() {
361        let config = ImageConfig {
362            cmd: Some(vec!["/bin/bash".to_string()]),
363            ..Default::default()
364        };
365
366        assert_eq!(config.full_command(), Some(vec!["/bin/bash".to_string()]));
367    }
368
369    #[test]
370    fn test_full_command_neither_set() {
371        let config = ImageConfig::default();
372        assert!(config.full_command().is_none());
373    }
374
375    #[test]
376    fn test_image_config_default() {
377        let config = ImageConfig::default();
378        assert!(config.entrypoint.is_none());
379        assert!(config.cmd.is_none());
380        assert!(config.working_dir.is_none());
381        assert!(config.env.is_none());
382        assert!(config.user.is_none());
383        assert!(config.exposed_ports.is_none());
384        assert!(config.volumes.is_none());
385        assert!(config.labels.is_none());
386        assert!(config.stop_signal.is_none());
387    }
388
389    #[test]
390    fn test_image_config_clone() {
391        let config = ImageConfig {
392            entrypoint: Some(vec!["/bin/sh".to_string()]),
393            cmd: Some(vec!["-c".to_string(), "echo hello".to_string()]),
394            working_dir: Some("/tmp".to_string()),
395            env: Some(vec!["FOO=bar".to_string()]),
396            user: Some("nobody".to_string()),
397            exposed_ports: None,
398            volumes: None,
399            labels: Some(HashMap::from([("key".to_string(), "value".to_string())])),
400            stop_signal: None,
401            shell: None,
402            healthcheck: None,
403        };
404
405        let cloned = config.clone();
406        assert_eq!(cloned.entrypoint, config.entrypoint);
407        assert_eq!(cloned.cmd, config.cmd);
408        assert_eq!(cloned.working_dir, config.working_dir);
409        assert_eq!(cloned.env, config.env);
410        assert_eq!(cloned.user, config.user);
411        assert_eq!(cloned.labels, config.labels);
412    }
413
414    #[test]
415    fn test_parse_extra_fields_ignored() {
416        // The OCI config has many more fields (architecture, os, etc.)
417        // that we don't care about. Verify they are silently ignored.
418        let json = r#"{
419            "architecture": "amd64",
420            "os": "linux",
421            "config": {
422                "Entrypoint": ["/app"],
423                "Hostname": "",
424                "Domainname": "",
425                "AttachStdout": false,
426                "Tty": false,
427                "ArgsEscaped": true
428            },
429            "rootfs": {
430                "type": "layers",
431                "diff_ids": ["sha256:abc"]
432            },
433            "history": [
434                {"created": "2024-01-01T00:00:00Z", "created_by": "COPY . /app"}
435            ]
436        }"#;
437
438        let root: OciImageConfigRoot = serde_json::from_str(json).unwrap();
439        let config = root.config.unwrap();
440        assert_eq!(config.entrypoint, Some(vec!["/app".to_string()]));
441    }
442}