1use serde::{Deserialize, Serialize};
25use std::collections::HashMap;
26
27#[derive(Debug, Clone, Default, Deserialize, Serialize)]
32pub struct ImageConfig {
33 #[serde(rename = "Entrypoint")]
38 pub entrypoint: Option<Vec<String>>,
39
40 #[serde(rename = "Cmd")]
45 pub cmd: Option<Vec<String>>,
46
47 #[serde(rename = "WorkingDir")]
49 pub working_dir: Option<String>,
50
51 #[serde(rename = "Env")]
53 pub env: Option<Vec<String>>,
54
55 #[serde(rename = "User")]
58 pub user: Option<String>,
59
60 #[serde(rename = "ExposedPorts")]
63 pub exposed_ports: Option<HashMap<String, serde_json::Value>>,
64
65 #[serde(rename = "Volumes")]
67 pub volumes: Option<HashMap<String, serde_json::Value>>,
68
69 #[serde(rename = "Labels")]
71 pub labels: Option<HashMap<String, String>>,
72
73 #[serde(rename = "StopSignal")]
75 pub stop_signal: Option<String>,
76
77 #[serde(rename = "Shell")]
80 pub shell: Option<Vec<String>>,
81
82 #[serde(rename = "Healthcheck")]
84 pub healthcheck: Option<ImageHealthcheck>,
85}
86
87#[derive(Debug, Clone, Default, Deserialize, Serialize)]
91pub struct ImageHealthcheck {
92 #[serde(rename = "Test")]
94 pub test: Option<Vec<String>>,
95 #[serde(rename = "Interval")]
97 pub interval: Option<u64>,
98 #[serde(rename = "Timeout")]
100 pub timeout: Option<u64>,
101 #[serde(rename = "StartPeriod")]
103 pub start_period: Option<u64>,
104 #[serde(rename = "Retries")]
106 pub retries: Option<u32>,
107}
108
109impl ImageConfig {
110 #[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#[derive(Debug, Deserialize)]
138pub(crate) struct OciImageConfigRoot {
139 pub config: Option<ImageConfig>,
141 #[serde(default)]
146 pub os: Option<String>,
147 #[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 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 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 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 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 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}