forjar 1.6.2

Rust-native Infrastructure as Code — bare-metal first, BLAKE3 state, provenance tracing
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
//! FJ-2104: Base image layer extraction from OCI layout directories.
//!
//! Reads an existing OCI layout (e.g., pulled via `skopeo copy`) to extract
//! layer descriptors and diff_ids for use as base layers in `assemble_image()`.

use crate::core::types::{OciDescriptor, OciImageConfig, OciIndex, OciManifest};
use std::path::Path;

/// Validate that `digest` is a `sha256:`-prefixed lowercase 64-char hex digest
/// and return the bare hex portion.
///
/// The OCI layout under `state/images/<image>` is populated from an externally
/// pulled image (e.g. `skopeo copy`), so the digests inside `index.json` and the
/// manifest are untrusted. Without validation a crafted digest such as
/// `sha256:../../../../etc/passwd` would escape `blobs/sha256/` and cause an
/// arbitrary file read (and, in `copy_base_blobs`, an arbitrary file write).
///
/// A strict `^[0-9a-f]{64}$` check rejects other algorithms, uppercase, wrong
/// lengths, and any `/` or `.` path separators, so the returned hex is safe to
/// join onto a path.
fn validate_sha256_hex(digest: &str) -> Result<&str, String> {
    let hex = digest
        .strip_prefix("sha256:")
        .ok_or_else(|| format!("unsupported digest algorithm: {digest}"))?;
    if hex.len() == 64
        && hex
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
    {
        Ok(hex)
    } else {
        Err(format!("invalid sha256 digest: {digest}"))
    }
}

/// Extracted base image information.
#[derive(Debug, Clone)]
pub struct BaseImageLayers {
    /// Layer descriptors from the base image manifest (ordered bottom→top).
    pub layers: Vec<OciDescriptor>,
    /// DiffIDs from the base image config (uncompressed SHA-256).
    pub diff_ids: Vec<String>,
    /// History from the base image config.
    pub history: Vec<crate::core::types::OciHistoryEntry>,
    /// Architecture (e.g., "amd64").
    pub architecture: String,
    /// OS (e.g., "linux").
    pub os: String,
    /// Runtime config from base image.
    pub config: crate::core::types::OciRuntimeConfig,
}

/// Read an OCI layout directory and extract base image layer information.
///
/// The layout directory must contain:
/// - `index.json` — OCI index pointing to manifest
/// - `blobs/sha256/...` — manifest and config blobs
///
/// # Examples
///
/// ```no_run
/// use forjar::core::store::base_image::extract_base_layers;
///
/// let layers = extract_base_layers(std::path::Path::new("state/images/ubuntu")).unwrap();
/// assert!(!layers.layers.is_empty());
/// assert_eq!(layers.layers.len(), layers.diff_ids.len());
/// ```
pub fn extract_base_layers(layout_dir: &Path) -> Result<BaseImageLayers, String> {
    // 1. Read and parse index.json
    let index_path = layout_dir.join("index.json");
    let index_data = std::fs::read(&index_path).map_err(|e| format!("read index.json: {e}"))?;
    let index: OciIndex =
        serde_json::from_slice(&index_data).map_err(|e| format!("parse index.json: {e}"))?;

    if index.manifests.is_empty() {
        return Err("index.json has no manifests".into());
    }

    // 2. Read the first manifest
    let manifest_desc = &index.manifests[0];
    let manifest_data = read_blob(layout_dir, &manifest_desc.digest)?;
    let manifest: OciManifest =
        serde_json::from_slice(&manifest_data).map_err(|e| format!("parse manifest: {e}"))?;

    // 3. Read the image config
    let config_data = read_blob(layout_dir, &manifest.config.digest)?;
    let config: OciImageConfig =
        serde_json::from_slice(&config_data).map_err(|e| format!("parse image config: {e}"))?;

    // 4. Validate layer count matches diff_ids
    if manifest.layers.len() != config.rootfs.diff_ids.len() {
        return Err(format!(
            "layer count mismatch: manifest has {} layers, config has {} diff_ids",
            manifest.layers.len(),
            config.rootfs.diff_ids.len(),
        ));
    }

    Ok(BaseImageLayers {
        layers: manifest.layers,
        diff_ids: config.rootfs.diff_ids,
        history: config.history,
        architecture: config.architecture,
        os: config.os,
        config: config.config,
    })
}

/// Read a blob from the OCI layout's blobs directory.
fn read_blob(layout_dir: &Path, digest: &str) -> Result<Vec<u8>, String> {
    let hex = validate_sha256_hex(digest)?;
    let blob_path = layout_dir.join(format!("blobs/sha256/{hex}"));
    std::fs::read(&blob_path).map_err(|e| format!("read blob {digest}: {e}"))
}

/// Verify that all base image layer blobs exist in the layout directory.
///
/// Returns a list of missing blob digests.
pub fn verify_base_blobs(layout_dir: &Path, layers: &BaseImageLayers) -> Vec<String> {
    layers
        .layers
        .iter()
        .filter(|layer| match validate_sha256_hex(&layer.digest) {
            // An invalid/traversal digest is treated as missing: it does not
            // correspond to a legitimate blob inside `blobs/sha256/`.
            Ok(hex) => !layout_dir.join(format!("blobs/sha256/{hex}")).exists(),
            Err(_) => true,
        })
        .map(|layer| layer.digest.clone())
        .collect()
}

/// Copy base image layer blobs from source layout to destination layout.
///
/// Only copies blobs that don't already exist in the destination.
pub fn copy_base_blobs(
    src_layout: &Path,
    dst_layout: &Path,
    layers: &BaseImageLayers,
) -> Result<u64, String> {
    let dst_blobs = dst_layout.join("blobs/sha256");
    std::fs::create_dir_all(&dst_blobs)
        .map_err(|e| format!("create destination blobs dir: {e}"))?;

    let mut bytes_copied: u64 = 0;
    for layer in &layers.layers {
        let hex = validate_sha256_hex(&layer.digest)?;
        let dst_path = dst_blobs.join(hex);
        if dst_path.exists() {
            continue;
        }
        let src_path = src_layout.join(format!("blobs/sha256/{hex}"));
        std::fs::copy(&src_path, &dst_path)
            .map_err(|e| format!("copy blob {}: {e}", layer.digest))?;
        bytes_copied += layer.size;
    }
    Ok(bytes_copied)
}

/// Format base image info for human output.
pub fn format_base_info(base_ref: &str, layers: &BaseImageLayers) -> String {
    let total_size: u64 = layers.layers.iter().map(|l| l.size).sum();
    format!(
        "Base: {} ({}/{}, {} layers, {:.1} MB)",
        base_ref,
        layers.architecture,
        layers.os,
        layers.layers.len(),
        total_size as f64 / (1024.0 * 1024.0),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::types::{OciDescriptor, OciImageConfig, OciIndex, OciManifest};

    const CONFIG_HEX: &str = "aabbccdd00112233445566778899aabbccddeeff00112233445566778899aabb";
    const LAYER_HEX: &str = "11223344556677889900aabbccddeeff00112233445566778899aabbccddeeff";
    const MANIFEST_HEX: &str = "ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100";

    fn create_test_layout(dir: &Path) {
        let blobs = dir.join("blobs/sha256");
        std::fs::create_dir_all(&blobs).unwrap();

        // Config
        let config = OciImageConfig::linux_amd64(vec!["sha256:diff1".into()]);
        let config_json = serde_json::to_vec(&config).unwrap();
        std::fs::write(blobs.join(CONFIG_HEX), &config_json).unwrap();

        // Layer blob
        std::fs::write(blobs.join(LAYER_HEX), b"fake-layer-data").unwrap();

        // Manifest
        let manifest = OciManifest::new(
            format!("sha256:{CONFIG_HEX}"),
            vec![OciDescriptor::gzip_layer(format!("sha256:{LAYER_HEX}"), 15)],
        );
        let manifest_json = serde_json::to_vec(&manifest).unwrap();
        std::fs::write(blobs.join(MANIFEST_HEX), &manifest_json).unwrap();

        // Index
        let index = OciIndex::single(OciDescriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            digest: format!("sha256:{MANIFEST_HEX}"),
            size: manifest_json.len() as u64,
            annotations: std::collections::HashMap::new(),
        });
        std::fs::write(
            dir.join("index.json"),
            serde_json::to_vec_pretty(&index).unwrap(),
        )
        .unwrap();

        std::fs::write(dir.join("oci-layout"), r#"{"imageLayoutVersion":"1.0.0"}"#).unwrap();
    }

    #[test]
    fn extract_base_layers_valid() {
        let dir = tempfile::tempdir().unwrap();
        create_test_layout(dir.path());
        let result = extract_base_layers(dir.path()).unwrap();
        assert_eq!(result.layers.len(), 1);
        assert_eq!(result.diff_ids.len(), 1);
        assert_eq!(result.architecture, "amd64");
        assert_eq!(result.os, "linux");
    }

    #[test]
    fn extract_base_layers_missing_index() {
        let dir = tempfile::tempdir().unwrap();
        let result = extract_base_layers(dir.path());
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("index.json"));
    }

    #[test]
    fn verify_base_blobs_all_present() {
        let dir = tempfile::tempdir().unwrap();
        create_test_layout(dir.path());
        let layers = extract_base_layers(dir.path()).unwrap();
        let missing = verify_base_blobs(dir.path(), &layers);
        assert!(missing.is_empty());
    }

    #[test]
    fn verify_base_blobs_missing() {
        let dir = tempfile::tempdir().unwrap();
        create_test_layout(dir.path());
        let mut layers = extract_base_layers(dir.path()).unwrap();
        // Add a fake layer that doesn't exist
        layers
            .layers
            .push(OciDescriptor::gzip_layer("sha256:nonexistent".into(), 100));
        let missing = verify_base_blobs(dir.path(), &layers);
        assert_eq!(missing.len(), 1);
        assert!(missing[0].contains("nonexistent"));
    }

    #[test]
    fn copy_base_blobs_to_new_dir() {
        let src = tempfile::tempdir().unwrap();
        create_test_layout(src.path());
        let layers = extract_base_layers(src.path()).unwrap();

        let dst = tempfile::tempdir().unwrap();
        let bytes = copy_base_blobs(src.path(), dst.path(), &layers).unwrap();
        assert!(bytes > 0);

        // Verify blob exists in destination
        let missing = verify_base_blobs(dst.path(), &layers);
        assert!(missing.is_empty());
    }

    #[test]
    fn copy_base_blobs_skip_existing() {
        let src = tempfile::tempdir().unwrap();
        create_test_layout(src.path());
        let layers = extract_base_layers(src.path()).unwrap();

        let dst = tempfile::tempdir().unwrap();
        let bytes1 = copy_base_blobs(src.path(), dst.path(), &layers).unwrap();
        let bytes2 = copy_base_blobs(src.path(), dst.path(), &layers).unwrap();
        assert!(bytes1 > 0);
        assert_eq!(bytes2, 0); // already exists
    }

    #[test]
    fn format_base_info_output() {
        let layers = BaseImageLayers {
            layers: vec![
                OciDescriptor::gzip_layer("sha256:a".into(), 5_000_000),
                OciDescriptor::gzip_layer("sha256:b".into(), 3_000_000),
            ],
            diff_ids: vec!["sha256:da".into(), "sha256:db".into()],
            history: vec![],
            architecture: "arm64".into(),
            os: "linux".into(),
            config: Default::default(),
        };
        let info = format_base_info("ubuntu:22.04", &layers);
        assert!(info.contains("ubuntu:22.04"));
        assert!(info.contains("arm64/linux"));
        assert!(info.contains("2 layers"));
        assert!(info.contains("MB"));
    }

    #[test]
    fn validate_sha256_hex_accepts_valid() {
        let digest = format!("sha256:{CONFIG_HEX}");
        assert_eq!(validate_sha256_hex(&digest).unwrap(), CONFIG_HEX);
    }

    #[test]
    fn validate_sha256_hex_rejects_traversal() {
        assert!(validate_sha256_hex("sha256:../../../../etc/passwd").is_err());
    }

    #[test]
    fn validate_sha256_hex_rejects_wrong_algorithm() {
        assert!(validate_sha256_hex(&format!("sha512:{CONFIG_HEX}")).is_err());
        // No prefix at all.
        assert!(validate_sha256_hex(CONFIG_HEX).is_err());
    }

    #[test]
    fn validate_sha256_hex_rejects_uppercase() {
        assert!(validate_sha256_hex(&format!("sha256:{}", CONFIG_HEX.to_uppercase())).is_err());
    }

    #[test]
    fn validate_sha256_hex_rejects_wrong_length() {
        assert!(validate_sha256_hex("sha256:abc123").is_err());
        // 63 chars (one short).
        assert!(validate_sha256_hex(&format!("sha256:{}", &CONFIG_HEX[..63])).is_err());
        // 65 chars (one long).
        assert!(validate_sha256_hex(&format!("sha256:{CONFIG_HEX}a")).is_err());
    }

    #[test]
    fn read_blob_rejects_traversal_digest() {
        let dir = tempfile::tempdir().unwrap();
        create_test_layout(dir.path());
        let result = read_blob(dir.path(), "sha256:../../../../etc/passwd");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("invalid sha256 digest"));
    }

    #[test]
    fn extract_base_layers_rejects_traversal_manifest_digest() {
        // A crafted index.json whose manifest digest escapes blobs/sha256/.
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("blobs/sha256")).unwrap();
        let index = OciIndex::single(OciDescriptor {
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            digest: "sha256:../../../../etc/passwd".into(),
            size: 0,
            annotations: std::collections::HashMap::new(),
        });
        std::fs::write(
            dir.path().join("index.json"),
            serde_json::to_vec(&index).unwrap(),
        )
        .unwrap();
        let result = extract_base_layers(dir.path());
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("invalid sha256 digest"));
    }

    #[test]
    fn copy_base_blobs_rejects_traversal_digest() {
        let src = tempfile::tempdir().unwrap();
        create_test_layout(src.path());
        let mut layers = extract_base_layers(src.path()).unwrap();
        // A malicious source layout supplies a layer digest with `..`.
        layers.layers.push(OciDescriptor::gzip_layer(
            "sha256:../../../../tmp/forjar-traversal-write".into(),
            100,
        ));
        let dst = tempfile::tempdir().unwrap();
        let result = copy_base_blobs(src.path(), dst.path(), &layers);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("invalid sha256 digest"));
    }

    #[test]
    fn extract_base_layers_empty_index() {
        let dir = tempfile::tempdir().unwrap();
        let index = OciIndex {
            schema_version: 2,
            manifests: vec![],
            annotations: std::collections::HashMap::new(),
        };
        std::fs::write(
            dir.path().join("index.json"),
            serde_json::to_vec(&index).unwrap(),
        )
        .unwrap();
        let result = extract_base_layers(dir.path());
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("no manifests"));
    }
}