ctb_formats_docker/
docker.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Docker image and container archive validation utilities.
21
22#[expect(
23    clippy::wildcard_imports,
24    reason = "Standard workspace crate prelude"
25)]
26pub(crate) use ctb_utilities::*;
27
28use anyhow::{Context, Result};
29use sha2::{Digest, Sha256};
30use std::collections::HashSet;
31use std::io::Read;
32
33pub mod cli;
34
35/// Returns a fixture asset byte vector if present.
36#[cfg(test)]
37pub fn get_docker_data(key: &str) -> Option<Vec<u8>> {
38    ctb_utilities::load_manifest_fixture(env!("CARGO_MANIFEST_DIR"), key)
39}
40
41/// Represents an entry in `manifest.json`.
42#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
43#[serde(rename_all = "PascalCase")]
44pub struct DockerManifestEntry {
45    pub config: String,
46    #[serde(default)]
47    pub repo_tags: Option<Vec<String>>,
48    pub layers: Vec<String>,
49    #[serde(default)]
50    pub layer_sources: Option<serde_json::Value>,
51}
52
53/// Represents `index.json`.
54#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
55#[serde(rename_all = "camelCase")]
56pub struct OciIndex {
57    pub schema_version: u32,
58    #[serde(default)]
59    pub media_type: Option<String>,
60    pub manifests: Vec<OciIndexManifest>,
61}
62
63/// Manifest descriptor in `index.json`.
64#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
65#[serde(rename_all = "camelCase")]
66pub struct OciIndexManifest {
67    pub media_type: String,
68    pub digest: String,
69    pub size: u64,
70    #[serde(default)]
71    pub annotations: Option<serde_json::Value>,
72}
73
74/// Represents `oci-layout`.
75#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
76#[serde(rename_all = "camelCase")]
77pub struct OciLayout {
78    pub image_layout_version: String,
79}
80
81/// Record of a blob whose computed SHA-256 does not match its filename hash.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct BlobChecksumMismatch {
84    pub blob_path: String,
85    pub expected_hash: String,
86    pub computed_hash: String,
87}
88
89/// Summary report of docker image archive validation.
90#[derive(Debug, Clone, Default)]
91pub struct ValidationReport {
92    pub validated_metadata: HashSet<String>,
93    pub total_blobs_checked: usize,
94    pub valid_blobs_count: usize,
95    pub checksum_mismatches: Vec<BlobChecksumMismatch>,
96    pub missing_blobs: Vec<String>,
97    pub unreferenced_blobs: Vec<String>,
98    pub referenced_blobs_count: usize,
99}
100
101impl ValidationReport {
102    /// Returns true if validation succeeded according to strictness settings.
103    pub fn is_success(&self, strict: bool) -> bool {
104        self.validated_metadata.contains("manifest.json")
105            && self.checksum_mismatches.is_empty()
106            && self.missing_blobs.is_empty()
107            && (!strict || self.unreferenced_blobs.is_empty())
108    }
109}
110
111/// Strips leading `./` or `/` prefixes from tar entry paths.
112fn normalize_path(path: &str) -> String {
113    let mut p = path;
114    while let Some(stripped) = p.strip_prefix("./") {
115        p = stripped;
116    }
117    p.trim_start_matches('/').to_string()
118}
119
120/// Extracts a clean hex digest from a blob reference string.
121fn extract_blob_hash(ref_str: &str) -> String {
122    let mut s = ref_str;
123    if let Some(stripped) = s.strip_prefix("blobs/sha256/") {
124        s = stripped;
125    }
126    if let Some(stripped) = s.strip_prefix("sha256:") {
127        s = stripped;
128    }
129    if let Some(stripped) = s.strip_suffix(".json") {
130        s = stripped;
131    }
132    if let Some(stripped) = s.strip_suffix("/layer.tar") {
133        s = stripped;
134    }
135    s.trim_matches('/').to_string()
136}
137
138/// Parses and validates one of the image metadata JSON files.
139fn process_metadata_entry<R: Read>(
140    normalized_path: &str,
141    entry: &mut tar::Entry<R>,
142    referenced_blobs: &mut HashSet<String>,
143    report: &mut ValidationReport,
144) -> Result<bool> {
145    match normalized_path {
146        "oci-layout" => {
147            let mut content = Vec::new();
148            entry
149                .read_to_end(&mut content)
150                .context("Failed reading oci-layout")?;
151            serde_json::from_slice::<OciLayout>(&content)
152                .context("Invalid JSON in oci-layout")?;
153            report.validated_metadata.insert("oci-layout".to_string());
154            Ok(true)
155        }
156        "repositories" => {
157            let mut content = Vec::new();
158            entry
159                .read_to_end(&mut content)
160                .context("Failed reading repositories")?;
161            serde_json::from_slice::<serde_json::Value>(&content)
162                .context("Invalid JSON in repositories")?;
163            report.validated_metadata.insert("repositories".to_string());
164            Ok(true)
165        }
166        "index.json" => {
167            let mut content = Vec::new();
168            entry
169                .read_to_end(&mut content)
170                .context("Failed reading index.json")?;
171            let index: OciIndex = serde_json::from_slice(&content)
172                .context("Invalid JSON in index.json")?;
173            for manifest in &index.manifests {
174                let digest = extract_blob_hash(&manifest.digest);
175                referenced_blobs.insert(digest.to_ascii_lowercase());
176            }
177            report.validated_metadata.insert("index.json".to_string());
178            Ok(true)
179        }
180        "manifest.json" => {
181            let mut content = Vec::new();
182            entry
183                .read_to_end(&mut content)
184                .context("Failed reading manifest.json")?;
185            let entries: Vec<DockerManifestEntry> =
186                serde_json::from_slice(&content)
187                    .context("Invalid JSON in manifest.json")?;
188            for m in &entries {
189                let config_hash = extract_blob_hash(&m.config);
190                referenced_blobs.insert(config_hash.to_ascii_lowercase());
191                for layer in &m.layers {
192                    let layer_hash = extract_blob_hash(layer);
193                    referenced_blobs.insert(layer_hash.to_ascii_lowercase());
194                }
195            }
196            report
197                .validated_metadata
198                .insert("manifest.json".to_string());
199            Ok(true)
200        }
201        _ => Ok(false),
202    }
203}
204
205/// Computes SHA-256 for a blob entry and validates it against its filename.
206fn process_blob_entry<R: Read>(
207    normalized_path: &str,
208    expected_hash: &str,
209    entry: &mut tar::Entry<R>,
210    found_blobs: &mut HashSet<String>,
211    report: &mut ValidationReport,
212) -> Result<()> {
213    let expected_hash = expected_hash.trim_end_matches('/');
214    let mut hasher = Sha256::new();
215    let mut buffer = vec![0_u8; 65536];
216
217    loop {
218        let n = entry
219            .read(&mut buffer)
220            .context("Failed to read blob chunk")?;
221        if n == 0 {
222            break;
223        }
224        let slice = buffer
225            .get(..n)
226            .ok_or_else(|| anyhow::anyhow!("Buffer slice bounds error"))?;
227        hasher.update(slice);
228    }
229
230    let computed_digest = ctb_utilities::string::to_hex(&hasher.finalize());
231    report.total_blobs_checked = report.total_blobs_checked.saturating_add(1);
232    let expected_lower = expected_hash.to_ascii_lowercase();
233
234    if computed_digest.eq_ignore_ascii_case(&expected_lower) {
235        report.valid_blobs_count = report.valid_blobs_count.saturating_add(1);
236    } else {
237        report.checksum_mismatches.push(BlobChecksumMismatch {
238            blob_path: normalized_path.to_string(),
239            expected_hash: expected_lower.clone(),
240            computed_hash: computed_digest,
241        });
242    }
243    found_blobs.insert(expected_lower);
244    Ok(())
245}
246
247/// Streams a tar archive, verifying JSON metadata and blob checksums.
248pub fn validate_docker_archive<R: Read>(
249    reader: R,
250    _strict: bool,
251) -> Result<ValidationReport> {
252    let mut report = ValidationReport::default();
253    let mut referenced_blobs = HashSet::<String>::new();
254    let mut found_blobs = HashSet::<String>::new();
255
256    let mut archive = tar::Archive::new(reader);
257    let entries = archive.entries().context("Failed to read tar entries")?;
258
259    for entry_result in entries {
260        let mut entry = entry_result.context("Failed to read tar entry")?;
261        if entry.header().entry_type().is_dir() {
262            continue;
263        }
264
265        let raw_path = entry.path().context("Invalid tar entry path")?;
266        let path_str = raw_path.to_string_lossy();
267        let normalized_path = normalize_path(&path_str);
268
269        let was_metadata = process_metadata_entry(
270            &normalized_path,
271            &mut entry,
272            &mut referenced_blobs,
273            &mut report,
274        )?;
275
276        if !was_metadata
277            && let Some(expected_hash) =
278                normalized_path.strip_prefix("blobs/sha256/")
279        {
280            process_blob_entry(
281                &normalized_path,
282                expected_hash,
283                &mut entry,
284                &mut found_blobs,
285                &mut report,
286            )?;
287        }
288    }
289
290    if !report.validated_metadata.contains("manifest.json") {
291        anyhow::bail!("Archive is missing required manifest.json");
292    }
293
294    report.referenced_blobs_count = referenced_blobs.len();
295
296    for ref_blob in &referenced_blobs {
297        if !found_blobs.contains(ref_blob) {
298            report.missing_blobs.push(ref_blob.clone());
299        }
300    }
301    report.missing_blobs.sort();
302
303    for found_blob in &found_blobs {
304        if !referenced_blobs.contains(found_blob) {
305            report.unreferenced_blobs.push(found_blob.clone());
306        }
307    }
308    report.unreferenced_blobs.sort();
309
310    Ok(report)
311}
312
313#[cfg(test)]
314#[allow(
315    clippy::panic,
316    clippy::expect_used,
317    clippy::unwrap_used,
318    clippy::unwrap_in_result,
319    clippy::panic_in_result_fn,
320    clippy::indexing_slicing,
321    clippy::arithmetic_side_effects,
322    reason = "Standard repository test boilerplate"
323)]
324mod tests {
325    use super::*;
326    use std::io::Cursor;
327
328    #[crate::ctb_test]
329    fn test_validate_hello_world_fixture() {
330        let fixture_bytes =
331            get_docker_data("fixtures/docker-hello-world/hello-world.tar")
332                .expect("Load hello-world.tar fixture");
333
334        let report =
335            validate_docker_archive(Cursor::new(&fixture_bytes), false)
336                .expect("Validate hello-world.tar");
337
338        assert!(report.validated_metadata.contains("manifest.json"));
339        assert!(report.validated_metadata.contains("index.json"));
340        assert!(report.validated_metadata.contains("oci-layout"));
341        assert!(report.validated_metadata.contains("repositories"));
342        assert_eq!(report.missing_blobs.len(), 0);
343        assert_eq!(report.checksum_mismatches.len(), 0);
344        assert_eq!(report.valid_blobs_count, 4);
345        assert!(report.is_success(false));
346    }
347
348    #[crate::ctb_test]
349    fn test_validate_synthetic_valid_archive() {
350        let mut builder = tar::Builder::new(Vec::new());
351
352        let oci_layout = b"{\"imageLayoutVersion\": \"1.0.0\"}";
353        let mut header = tar::Header::new_gnu();
354        header.set_size(u64::try_from(oci_layout.len()).unwrap());
355        header.set_mode(0o644);
356        header.set_cksum();
357        builder
358            .append_data(&mut header, "oci-layout", &oci_layout[..])
359            .unwrap();
360
361        let repos = b"{\"repo\":{\"latest\":\"layer1\"}}";
362        let mut header = tar::Header::new_gnu();
363        header.set_size(u64::try_from(repos.len()).unwrap());
364        header.set_mode(0o644);
365        header.set_cksum();
366        builder
367            .append_data(&mut header, "repositories", &repos[..])
368            .unwrap();
369
370        let layer_content = b"fake layer content 123";
371        let layer_hash = ctb_formats_checksum::sha256_hex(layer_content);
372
373        let config_content = b"{\"architecture\":\"amd64\"}";
374        let config_hash = ctb_formats_checksum::sha256_hex(config_content);
375
376        let manifest_json = format!(
377            "[{{\"Config\":\"blobs/sha256/{config_hash}\",\"Layers\":[\"blobs/sha256/{layer_hash}\"]}}]"
378        );
379        let mut header = tar::Header::new_gnu();
380        header.set_size(u64::try_from(manifest_json.len()).unwrap());
381        header.set_mode(0o644);
382        header.set_cksum();
383        builder
384            .append_data(&mut header, "manifest.json", manifest_json.as_bytes())
385            .unwrap();
386
387        let mut header = tar::Header::new_gnu();
388        header.set_size(u64::try_from(config_content.len()).unwrap());
389        header.set_mode(0o644);
390        header.set_cksum();
391        builder
392            .append_data(
393                &mut header,
394                format!("blobs/sha256/{config_hash}"),
395                &config_content[..],
396            )
397            .unwrap();
398
399        let mut header = tar::Header::new_gnu();
400        header.set_size(u64::try_from(layer_content.len()).unwrap());
401        header.set_mode(0o644);
402        header.set_cksum();
403        builder
404            .append_data(
405                &mut header,
406                format!("blobs/sha256/{layer_hash}"),
407                &layer_content[..],
408            )
409            .unwrap();
410
411        let tar_bytes = builder.into_inner().unwrap();
412        let report =
413            validate_docker_archive(Cursor::new(&tar_bytes), true).unwrap();
414
415        assert!(report.is_success(true));
416        assert_eq!(report.valid_blobs_count, 2);
417        assert_eq!(report.checksum_mismatches.len(), 0);
418        assert_eq!(report.missing_blobs.len(), 0);
419        assert_eq!(report.unreferenced_blobs.len(), 0);
420    }
421
422    #[crate::ctb_test]
423    fn test_validate_checksum_mismatch() {
424        let mut builder = tar::Builder::new(Vec::new());
425
426        let fake_hash =
427            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
428        let manifest_json = format!(
429            "[{{\"Config\":\"blobs/sha256/{fake_hash}\",\"Layers\":[]}}]"
430        );
431        let mut header = tar::Header::new_gnu();
432        header.set_size(u64::try_from(manifest_json.len()).unwrap());
433        header.set_mode(0o644);
434        header.set_cksum();
435        builder
436            .append_data(&mut header, "manifest.json", manifest_json.as_bytes())
437            .unwrap();
438
439        let corrupt_content = b"not matching hash";
440        let mut header = tar::Header::new_gnu();
441        header.set_size(u64::try_from(corrupt_content.len()).unwrap());
442        header.set_mode(0o644);
443        header.set_cksum();
444        builder
445            .append_data(
446                &mut header,
447                format!("blobs/sha256/{fake_hash}"),
448                &corrupt_content[..],
449            )
450            .unwrap();
451
452        let tar_bytes = builder.into_inner().unwrap();
453        let report =
454            validate_docker_archive(Cursor::new(&tar_bytes), false).unwrap();
455
456        assert!(!report.is_success(false));
457        assert_eq!(report.checksum_mismatches.len(), 1);
458        assert_eq!(report.checksum_mismatches[0].expected_hash, fake_hash);
459    }
460
461    #[crate::ctb_test]
462    fn test_validate_missing_blob() {
463        let mut builder = tar::Builder::new(Vec::new());
464
465        let missing_hash =
466            "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
467        let manifest_json = format!(
468            "[{{\"Config\":\"blobs/sha256/{missing_hash}\",\"Layers\":[]}}]"
469        );
470        let mut header = tar::Header::new_gnu();
471        header.set_size(u64::try_from(manifest_json.len()).unwrap());
472        header.set_mode(0o644);
473        header.set_cksum();
474        builder
475            .append_data(&mut header, "manifest.json", manifest_json.as_bytes())
476            .unwrap();
477
478        let tar_bytes = builder.into_inner().unwrap();
479        let report =
480            validate_docker_archive(Cursor::new(&tar_bytes), false).unwrap();
481
482        assert!(!report.is_success(false));
483        assert_eq!(report.missing_blobs.len(), 1);
484        assert_eq!(report.missing_blobs[0], missing_hash);
485    }
486
487    #[crate::ctb_test]
488    fn test_validate_strict_mode() {
489        let fixture_bytes =
490            get_docker_data("fixtures/docker-hello-world/hello-world.tar")
491                .expect("Load hello-world.tar fixture");
492
493        // Without strict: passes even with unreferenced blob
494        let report_non_strict =
495            validate_docker_archive(Cursor::new(&fixture_bytes), false)
496                .expect("Validate without strict");
497        assert!(report_non_strict.is_success(false));
498        assert_eq!(report_non_strict.unreferenced_blobs.len(), 1);
499
500        // With strict: fails due to unreferenced blob
501        assert!(!report_non_strict.is_success(true));
502    }
503
504    #[crate::ctb_test]
505    fn test_validate_invalid_json() {
506        let mut builder = tar::Builder::new(Vec::new());
507
508        let bad_json = b"not valid json {{{";
509        let mut header = tar::Header::new_gnu();
510        header.set_size(u64::try_from(bad_json.len()).unwrap());
511        header.set_mode(0o644);
512        header.set_cksum();
513        builder
514            .append_data(&mut header, "manifest.json", &bad_json[..])
515            .unwrap();
516
517        let tar_bytes = builder.into_inner().unwrap();
518        let result = validate_docker_archive(Cursor::new(&tar_bytes), false);
519        result.unwrap_err();
520    }
521
522    #[crate::ctb_test]
523    fn test_cli_run_validate_docker_image() {
524        let fixture_path = ctb_utilities::manifest_fixture_path(
525            env!("CARGO_MANIFEST_DIR"),
526            "docker-hello-world/hello-world.tar",
527        );
528        let res = cli::run_validate_docker_image(Some(&fixture_path), false)
529            .expect("Run CLI validation");
530
531        match res {
532            ToolResult::Immediate {
533                exit_code, stdout, ..
534            } => {
535                assert_eq!(exit_code, 0);
536                let text = String::from_utf8_lossy(&stdout);
537                assert!(text.contains("Docker image validation successful:"));
538                assert!(text.contains("manifest.json (valid JSON)"));
539                assert!(text.contains("4 blob checksum(s) verified (SHA-256)"));
540            }
541            _ => panic!("Expected Immediate ToolResult"),
542        }
543
544        // Test strict failure on hello-world fixture (unreferenced blob present)
545        let res_strict =
546            cli::run_validate_docker_image(Some(&fixture_path), true)
547                .expect("Run CLI validation strict");
548        match res_strict {
549            ToolResult::Immediate {
550                exit_code, stderr, ..
551            } => {
552                assert_eq!(exit_code, 1);
553                let text = String::from_utf8_lossy(&stderr);
554                assert!(text.contains("Docker image validation failed:"));
555                assert!(
556                    text.contains("unreferenced blob(s) found (strict mode)")
557                );
558            }
559            _ => panic!("Expected Immediate ToolResult"),
560        }
561    }
562}