a3s-box-runtime 0.8.0

MicroVM runtime engine — VM lifecycle, OCI images, attestation, networking
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
//! Utility functions for the build engine.

use std::collections::HashMap;
use std::path::Path;

use a3s_box_core::error::{BoxError, Result};

use super::super::layer::sha256_bytes;

/// Check if a filename looks like a tar archive.
pub(super) fn is_tar_archive(name: &str) -> bool {
    let lower = name.to_lowercase();
    lower.ends_with(".tar")
        || lower.ends_with(".tar.gz")
        || lower.ends_with(".tgz")
        || lower.ends_with(".tar.bz2")
        || lower.ends_with(".tbz2")
        || lower.ends_with(".tar.xz")
        || lower.ends_with(".txz")
}

/// Extract a tar archive to a destination directory.
pub(super) fn extract_tar_to_dst(archive_path: &Path, dst: &Path) -> Result<()> {
    use bzip2::read::BzDecoder;
    use flate2::read::GzDecoder;
    use std::io::BufReader;
    use xz2::read::XzDecoder;

    std::fs::create_dir_all(dst).map_err(|e| {
        BoxError::BuildError(format!(
            "Failed to create extraction directory {}: {}",
            dst.display(),
            e
        ))
    })?;

    let file = std::fs::File::open(archive_path).map_err(|e| {
        BoxError::BuildError(format!(
            "Failed to open archive {}: {}",
            archive_path.display(),
            e
        ))
    })?;

    let name = archive_path.to_str().unwrap_or("").to_lowercase();

    if name.ends_with(".tar.gz") || name.ends_with(".tgz") {
        let decoder = GzDecoder::new(BufReader::new(file));
        let mut archive = tar::Archive::new(decoder);
        archive.unpack(dst).map_err(|e| {
            BoxError::BuildError(format!(
                "Failed to extract tar.gz {}: {}",
                archive_path.display(),
                e
            ))
        })?;
    } else if name.ends_with(".tar.bz2") || name.ends_with(".tbz2") {
        let decoder = BzDecoder::new(BufReader::new(file));
        let mut archive = tar::Archive::new(decoder);
        archive.unpack(dst).map_err(|e| {
            BoxError::BuildError(format!(
                "Failed to extract tar.bz2 {}: {}",
                archive_path.display(),
                e
            ))
        })?;
    } else if name.ends_with(".tar.xz") || name.ends_with(".txz") {
        let decoder = XzDecoder::new(BufReader::new(file));
        let mut archive = tar::Archive::new(decoder);
        archive.unpack(dst).map_err(|e| {
            BoxError::BuildError(format!(
                "Failed to extract tar.xz {}: {}",
                archive_path.display(),
                e
            ))
        })?;
    } else if name.ends_with(".tar") {
        let mut archive = tar::Archive::new(BufReader::new(file));
        archive.unpack(dst).map_err(|e| {
            BoxError::BuildError(format!(
                "Failed to extract tar {}: {}",
                archive_path.display(),
                e
            ))
        })?;
    } else {
        return Err(BoxError::BuildError(format!(
            "Unsupported archive format: {}",
            archive_path.display()
        )));
    }

    Ok(())
}

/// Resolve a path relative to a working directory.
///
/// If `path` is absolute, return it as-is. Otherwise, join with `workdir`.
pub(super) fn resolve_path(workdir: &str, path: &str) -> String {
    if path.starts_with('/') {
        path.to_string()
    } else {
        format!("{}/{}", workdir.trim_end_matches('/'), path)
    }
}

/// Expand `${VAR}` and `$VAR` references in a string using build args.
pub(super) fn expand_args(s: &str, args: &HashMap<String, String>) -> String {
    let mut result = s.to_string();
    for (key, value) in args {
        result = result.replace(&format!("${{{}}}", key), value);
        result = result.replace(&format!("${}", key), value);
    }
    result
}

/// Compute the diff_id (SHA256 of uncompressed layer content).
pub(super) fn compute_diff_id(layer_path: &Path) -> Result<String> {
    let data = std::fs::read(layer_path)
        .map_err(|e| BoxError::BuildError(format!("Failed to read layer for diff_id: {}", e)))?;

    // Decompress gzip to get raw tar
    use flate2::read::GzDecoder;
    use std::io::Read;

    let decoder = GzDecoder::new(&data[..]);
    let mut uncompressed = Vec::new();
    std::io::BufReader::new(decoder)
        .read_to_end(&mut uncompressed)
        .map_err(|e| {
            BoxError::BuildError(format!("Failed to decompress layer for diff_id: {}", e))
        })?;

    Ok(sha256_bytes(&uncompressed))
}

/// Recursively copy a directory.
pub(super) fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
    std::fs::create_dir_all(dst).map_err(|e| {
        BoxError::BuildError(format!(
            "Failed to create directory {}: {}",
            dst.display(),
            e
        ))
    })?;

    for entry in std::fs::read_dir(src).map_err(|e| {
        BoxError::BuildError(format!("Failed to read directory {}: {}", src.display(), e))
    })? {
        let entry =
            entry.map_err(|e| BoxError::BuildError(format!("Failed to read entry: {}", e)))?;
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());

        if src_path.is_dir() {
            copy_dir_recursive(&src_path, &dst_path)?;
        } else {
            std::fs::copy(&src_path, &dst_path).map_err(|e| {
                BoxError::BuildError(format!(
                    "Failed to copy {} to {}: {}",
                    src_path.display(),
                    dst_path.display(),
                    e
                ))
            })?;
        }
    }
    Ok(())
}

/// Format a byte size as a human-readable string.
pub(super) fn format_size(bytes: u64) -> String {
    if bytes >= 1024 * 1024 * 1024 {
        format!("{:.1} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
    } else if bytes >= 1024 * 1024 {
        format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
    } else if bytes >= 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else {
        format!("{} B", bytes)
    }
}

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

    // --- is_tar_archive tests ---

    #[test]
    fn test_is_tar_archive_tar() {
        assert!(is_tar_archive("file.tar"));
    }

    #[test]
    fn test_is_tar_archive_tar_gz() {
        assert!(is_tar_archive("file.tar.gz"));
        assert!(is_tar_archive("file.tgz"));
    }

    #[test]
    fn test_is_tar_archive_tar_bz2() {
        assert!(is_tar_archive("file.tar.bz2"));
        assert!(is_tar_archive("file.tbz2"));
    }

    #[test]
    fn test_is_tar_archive_tar_xz() {
        assert!(is_tar_archive("file.tar.xz"));
        assert!(is_tar_archive("file.txz"));
    }

    #[test]
    fn test_is_tar_archive_case_insensitive() {
        assert!(is_tar_archive("FILE.TAR.GZ"));
        assert!(is_tar_archive("Data.Tar.Bz2"));
        assert!(is_tar_archive("ARCHIVE.TAR.XZ"));
    }

    #[test]
    fn test_is_tar_archive_non_archive() {
        assert!(!is_tar_archive("file.txt"));
        assert!(!is_tar_archive("file.zip"));
        assert!(!is_tar_archive("file.gz"));
        assert!(!is_tar_archive("file.bz2"));
        assert!(!is_tar_archive("file.xz"));
    }

    // --- extract_tar_to_dst tests ---

    /// Helper: create a tar archive with a single file.
    fn create_test_tar(
        dir: &std::path::Path,
        filename: &str,
        content: &[u8],
    ) -> std::path::PathBuf {
        let tar_path = dir.join(filename);
        let file = std::fs::File::create(&tar_path).unwrap();
        let mut builder = tar::Builder::new(file);

        let mut header = tar::Header::new_gnu();
        header.set_size(content.len() as u64);
        header.set_mode(0o644);
        header.set_cksum();
        builder
            .append_data(&mut header, "test.txt", content)
            .unwrap();
        builder.finish().unwrap();

        tar_path
    }

    #[test]
    fn test_extract_plain_tar() {
        let tmp = tempfile::tempdir().unwrap();
        let tar_path = create_test_tar(tmp.path(), "test.tar", b"hello tar");

        let dst = tmp.path().join("out");
        extract_tar_to_dst(&tar_path, &dst).unwrap();
        assert!(dst.join("test.txt").exists());
    }

    #[test]
    fn test_extract_tar_gz() {
        use flate2::write::GzEncoder;
        use flate2::Compression;
        use std::io::Write;

        let tmp = tempfile::tempdir().unwrap();

        // Create a tar in memory
        let mut tar_data = Vec::new();
        {
            let mut builder = tar::Builder::new(&mut tar_data);
            let mut header = tar::Header::new_gnu();
            let content = b"hello gzip";
            header.set_size(content.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            builder
                .append_data(&mut header, "test.txt", &content[..])
                .unwrap();
            builder.finish().unwrap();
        }

        // Gzip compress
        let gz_path = tmp.path().join("test.tar.gz");
        let gz_file = std::fs::File::create(&gz_path).unwrap();
        let mut encoder = GzEncoder::new(gz_file, Compression::default());
        encoder.write_all(&tar_data).unwrap();
        encoder.finish().unwrap();

        let dst = tmp.path().join("out");
        extract_tar_to_dst(&gz_path, &dst).unwrap();
        assert!(dst.join("test.txt").exists());
    }

    #[test]
    fn test_extract_tar_bz2() {
        use bzip2::write::BzEncoder;
        use bzip2::Compression;
        use std::io::Write;

        let tmp = tempfile::tempdir().unwrap();

        // Create a tar in memory
        let mut tar_data = Vec::new();
        {
            let mut builder = tar::Builder::new(&mut tar_data);
            let mut header = tar::Header::new_gnu();
            let content = b"hello bzip2";
            header.set_size(content.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            builder
                .append_data(&mut header, "test.txt", &content[..])
                .unwrap();
            builder.finish().unwrap();
        }

        // Bzip2 compress
        let bz2_path = tmp.path().join("test.tar.bz2");
        let bz2_file = std::fs::File::create(&bz2_path).unwrap();
        let mut encoder = BzEncoder::new(bz2_file, Compression::default());
        encoder.write_all(&tar_data).unwrap();
        encoder.finish().unwrap();

        let dst = tmp.path().join("out");
        extract_tar_to_dst(&bz2_path, &dst).unwrap();
        assert!(dst.join("test.txt").exists());
    }

    #[test]
    fn test_extract_tar_xz() {
        use std::io::Write;
        use xz2::write::XzEncoder;

        let tmp = tempfile::tempdir().unwrap();

        // Create a tar in memory
        let mut tar_data = Vec::new();
        {
            let mut builder = tar::Builder::new(&mut tar_data);
            let mut header = tar::Header::new_gnu();
            let content = b"hello xz";
            header.set_size(content.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            builder
                .append_data(&mut header, "test.txt", &content[..])
                .unwrap();
            builder.finish().unwrap();
        }

        // XZ compress
        let xz_path = tmp.path().join("test.tar.xz");
        let xz_file = std::fs::File::create(&xz_path).unwrap();
        let mut encoder = XzEncoder::new(xz_file, 6);
        encoder.write_all(&tar_data).unwrap();
        encoder.finish().unwrap();

        let dst = tmp.path().join("out");
        extract_tar_to_dst(&xz_path, &dst).unwrap();
        assert!(dst.join("test.txt").exists());
    }

    #[test]
    fn test_extract_nonexistent_file_fails() {
        let tmp = tempfile::tempdir().unwrap();
        let result = extract_tar_to_dst(
            &tmp.path().join("nonexistent.tar.gz"),
            &tmp.path().join("out"),
        );
        assert!(result.is_err());
    }

    // --- resolve_path tests ---

    #[test]
    fn test_resolve_path_absolute() {
        assert_eq!(resolve_path("/work", "/etc/config"), "/etc/config");
    }

    #[test]
    fn test_resolve_path_relative() {
        assert_eq!(resolve_path("/work", "src/main.rs"), "/work/src/main.rs");
    }

    // --- format_size tests ---

    #[test]
    fn test_format_size_bytes() {
        assert_eq!(format_size(42), "42 B");
    }

    #[test]
    fn test_format_size_kb() {
        assert_eq!(format_size(2048), "2.0 KB");
    }

    #[test]
    fn test_format_size_mb() {
        assert_eq!(format_size(5 * 1024 * 1024), "5.0 MB");
    }

    #[test]
    fn test_format_size_gb() {
        assert_eq!(format_size(2 * 1024 * 1024 * 1024), "2.0 GB");
    }
}