a3s-box-runtime 3.2.0

MicroVM runtime engine — VM lifecycle, OCI images, attestation, networking
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
//! Overlayfs mount/unmount operations.
//!
//! Provides host-side overlayfs mounts for CoW rootfs. On Linux 5.11+,
//! unprivileged overlayfs is available in user namespaces. Falls back to
//! `mount(2)` syscall or `mount` command.

use std::path::Path;

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

/// Mount an overlayfs at `merged` with `lower` (read-only), `upper` (writes), `work`.
///
/// Tries in order:
/// 1. `mount(2)` syscall (requires CAP_SYS_ADMIN or unprivileged overlay)
/// 2. `mount` command as fallback
pub fn overlay_mount(lower: &Path, upper: &Path, work: &Path, merged: &Path) -> Result<()> {
    // overlayfs mount options are comma-delimited with no escaping, so a comma in
    // any path would be parsed as an option boundary and silently corrupt the
    // mount. Refuse instead. Box dirs are UUID-based today, so this never trips in
    // practice — it's a guard for any future user-controllable cache/box path.
    for path in [lower, upper, work] {
        if path.to_string_lossy().contains(',') {
            return Err(BoxError::BuildError(format!(
                "overlay path contains a comma, which overlayfs options cannot express: {}",
                path.display()
            )));
        }
    }

    let base_options = overlay_options(lower, upper, work, false);

    // Try mount(2) syscall first
    #[cfg(target_os = "linux")]
    {
        use std::ffi::CString;

        // Metadata-only copy-up avoids copying every executable's contents
        // when Sandbox ownership is shifted for its user namespace. Restrict
        // it to the initial root namespace: rootless overlay uses user.*
        // private xattrs that an untrusted workload could forge. OCI ingestion
        // separately rejects both trusted.overlay.* and user.overlay.* xattrs.
        let metadata_options = overlay_options(lower, upper, work, true);
        let options = if unsafe { libc::geteuid() } == 0 {
            vec![(&metadata_options, true), (&base_options, false)]
        } else {
            vec![(&base_options, false)]
        };
        let source = CString::new("overlay").unwrap();
        let target = CString::new(merged.to_string_lossy().as_ref())
            .map_err(|e| BoxError::BuildError(format!("Invalid merged path for mount: {}", e)))?;
        let fstype = CString::new("overlay").unwrap();
        let mut failures = Vec::new();

        for &(options, metadata_copy) in &options {
            let data = CString::new(options.as_str()).map_err(|error| {
                BoxError::BuildError(format!("Invalid overlay mount options: {error}"))
            })?;
            let ret = unsafe {
                libc::mount(
                    source.as_ptr(),
                    target.as_ptr(),
                    fstype.as_ptr(),
                    0,
                    data.as_ptr() as *const libc::c_void,
                )
            };
            if ret == 0 {
                tracing::debug!(
                    lower = %lower.display(),
                    merged = %merged.display(),
                    metadata_copy,
                    "Overlay mounted via mount(2)"
                );
                return Ok(());
            }
            failures.push(format!(
                "mount(2), metacopy={metadata_copy}: {}",
                std::io::Error::last_os_error()
            ));
        }

        tracing::debug!(
            errors = ?failures,
            "mount(2) failed, trying mount command"
        );

        for &(options, metadata_copy) in &options {
            match std::process::Command::new("mount")
                .args(["-t", "overlay", "overlay", "-o", options])
                .arg(merged)
                .status()
            {
                Ok(status) if status.success() => {
                    tracing::debug!(
                        lower = %lower.display(),
                        merged = %merged.display(),
                        metadata_copy,
                        "Overlay mounted via mount command"
                    );
                    return Ok(());
                }
                Ok(status) => {
                    failures.push(format!("mount command, metacopy={metadata_copy}: {status}"))
                }
                Err(error) => {
                    failures.push(format!("mount command, metacopy={metadata_copy}: {error}"))
                }
            }
        }

        Err(BoxError::BuildError(format!(
            "Failed to mount overlayfs at {}: {}",
            merged.display(),
            failures.join("; ")
        )))
    }

    #[cfg(not(target_os = "linux"))]
    {
        let _ = (lower, upper, work, merged, base_options);
        Err(BoxError::BuildError(
            "Overlayfs is only supported on Linux".to_string(),
        ))
    }
}

fn overlay_options(lower: &Path, upper: &Path, work: &Path, metadata_copy: bool) -> String {
    let mut options = format!(
        "lowerdir={},upperdir={},workdir={}",
        lower.display(),
        upper.display(),
        work.display()
    );
    if metadata_copy {
        options.push_str(",metacopy=on");
    }
    options
}

/// Unmount an overlayfs at `merged`.
pub fn overlay_unmount(merged: &Path) -> Result<()> {
    overlay_unmount_with_mode(merged, true)
}

/// Synchronously unmount an overlayfs before reusing its writable layer.
///
/// A lazy detach is appropriate when a box is being discarded, but it can
/// leave the old mount alive through open namespace references. Reusing the
/// same upper directory before that mount is gone violates overlayfs' single
/// writer expectation and can hide writes from the replacement generation.
pub(crate) fn overlay_unmount_for_reuse(merged: &Path) -> Result<()> {
    overlay_unmount_with_mode(merged, false)
}

fn overlay_unmount_with_mode(merged: &Path, lazy: bool) -> Result<()> {
    #[cfg(target_os = "linux")]
    {
        use std::ffi::CString;

        let target = CString::new(merged.to_string_lossy().as_ref())
            .map_err(|e| BoxError::BuildError(format!("Invalid path for umount: {}", e)))?;

        let flags = if lazy { libc::MNT_DETACH } else { 0 };
        let ret = unsafe { libc::umount2(target.as_ptr(), flags) };

        if ret == 0 {
            tracing::debug!(path = %merged.display(), lazy, "Overlay unmounted");
            return Ok(());
        }

        let errno = std::io::Error::last_os_error();

        // Fallback: try `umount` command
        let mut command = std::process::Command::new("umount");
        if lazy {
            command.arg("-l");
        }
        let status = command
            .arg(merged)
            .status()
            .map_err(|e| BoxError::BuildError(format!("Failed to run umount command: {}", e)))?;

        if status.success() {
            tracing::debug!(path = %merged.display(), lazy, "Overlay unmounted via umount command");
            return Ok(());
        }

        Err(BoxError::BuildError(format!(
            "Failed to {}unmount overlayfs at {}: umount2 returned {}, umount command exited with {}",
            if lazy { "lazily " } else { "synchronously " },
            merged.display(),
            errno,
            status
        )))
    }

    #[cfg(not(target_os = "linux"))]
    {
        let _ = (merged, lazy);
        Ok(())
    }
}

/// Check if overlayfs is supported on this system.
///
/// Always returns `false` on non-Linux platforms (compile-time).
#[cfg(target_os = "linux")]
pub(crate) fn is_overlay_supported() -> bool {
    static OVERLAY_SUPPORTED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();

    cached_overlay_support(&OVERLAY_SUPPORTED, probe_overlay_support)
}

#[cfg(target_os = "linux")]
fn cached_overlay_support(cache: &std::sync::OnceLock<bool>, probe: impl FnOnce() -> bool) -> bool {
    *cache.get_or_init(probe)
}

#[cfg(target_os = "linux")]
fn probe_overlay_support() -> bool {
    // Check /proc/filesystems for overlay support
    if let Ok(fs_list) = std::fs::read_to_string("/proc/filesystems") {
        if !fs_list.contains("overlay") {
            tracing::debug!("Overlay not listed in /proc/filesystems");
            return false;
        }
    } else {
        return false;
    }

    // Try a test mount in a tempdir to verify we have permission
    let tmp = match tempfile::TempDir::new() {
        Ok(t) => t,
        Err(_) => return false,
    };

    let lower = tmp.path().join("lower");
    let upper = tmp.path().join("upper");
    let work = tmp.path().join("work");
    let merged = tmp.path().join("merged");

    for dir in [&lower, &upper, &work, &merged] {
        if std::fs::create_dir_all(dir).is_err() {
            return false;
        }
    }

    let ok = overlay_mount(&lower, &upper, &work, &merged).is_ok();
    if ok {
        let _ = overlay_unmount(&merged);
    }
    ok
}

/// Check if overlayfs is supported on this system.
///
/// Always returns `false` on non-Linux platforms.
#[cfg(not(target_os = "linux"))]
#[allow(dead_code)]
pub(crate) fn is_overlay_supported() -> bool {
    false
}

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

    #[test]
    fn test_is_overlay_supported_returns_bool() {
        // Just verify it doesn't panic
        let _supported = is_overlay_supported();
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn concurrent_overlay_support_queries_probe_once() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::{Arc, Barrier, OnceLock};

        const THREADS: usize = 8;
        let cache = Arc::new(OnceLock::new());
        let calls = Arc::new(AtomicUsize::new(0));
        let barrier = Arc::new(Barrier::new(THREADS));

        std::thread::scope(|scope| {
            let handles = (0..THREADS)
                .map(|_| {
                    let cache = cache.clone();
                    let calls = calls.clone();
                    let barrier = barrier.clone();
                    scope.spawn(move || {
                        barrier.wait();
                        cached_overlay_support(&cache, || {
                            calls.fetch_add(1, Ordering::SeqCst);
                            std::thread::sleep(std::time::Duration::from_millis(20));
                            true
                        })
                    })
                })
                .collect::<Vec<_>>();

            for handle in handles {
                assert!(handle.join().unwrap());
            }
        });

        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[cfg(not(target_os = "linux"))]
    #[test]
    fn test_overlay_not_supported_on_non_linux() {
        assert!(!is_overlay_supported());
    }

    #[cfg(not(target_os = "linux"))]
    #[test]
    fn test_overlay_mount_fails_on_non_linux() {
        let tmp = tempfile::TempDir::new().unwrap();
        let result = overlay_mount(
            &tmp.path().join("l"),
            &tmp.path().join("u"),
            &tmp.path().join("w"),
            &tmp.path().join("m"),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_overlay_mount_rejects_comma_in_mount_option_paths() {
        let tmp = tempfile::TempDir::new().unwrap();
        let lower = tmp.path().join("lower,with-comma");
        let upper = tmp.path().join("upper");
        let work = tmp.path().join("work");
        let merged = tmp.path().join("merged");

        let err = overlay_mount(&lower, &upper, &work, &merged).unwrap_err();

        assert!(err.to_string().contains("contains a comma"));
        assert!(err.to_string().contains("lower,with-comma"));
    }

    #[test]
    fn metadata_copy_option_is_explicit() {
        let lower = Path::new("/cache/lower");
        let upper = Path::new("/box/upper");
        let work = Path::new("/box/work");

        assert_eq!(
            overlay_options(lower, upper, work, false),
            "lowerdir=/cache/lower,upperdir=/box/upper,workdir=/box/work"
        );
        assert_eq!(
            overlay_options(lower, upper, work, true),
            "lowerdir=/cache/lower,upperdir=/box/upper,workdir=/box/work,metacopy=on"
        );
    }

    #[cfg(not(target_os = "linux"))]
    #[test]
    fn test_overlay_unmount_noop_on_non_linux() {
        let tmp = tempfile::TempDir::new().unwrap();
        assert!(overlay_unmount(tmp.path()).is_ok());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_overlay_mount_and_unmount() {
        if !is_overlay_supported() {
            // Skip in environments without overlay support
            return;
        }

        let tmp = tempfile::TempDir::new().unwrap();
        let lower = tmp.path().join("lower");
        let upper = tmp.path().join("upper");
        let work = tmp.path().join("work");
        let merged = tmp.path().join("merged");

        for dir in [&lower, &upper, &work, &merged] {
            std::fs::create_dir_all(dir).unwrap();
        }

        // Create a file in lower
        std::fs::write(lower.join("hello.txt"), "from lower").unwrap();

        // Mount
        overlay_mount(&lower, &upper, &work, &merged).unwrap();

        // Verify lower file visible in merged
        assert_eq!(
            std::fs::read_to_string(merged.join("hello.txt")).unwrap(),
            "from lower"
        );

        // Write to merged — should go to upper
        std::fs::write(merged.join("new.txt"), "from upper").unwrap();
        assert!(upper.join("new.txt").exists());

        // Unmount
        overlay_unmount(&merged).unwrap();
    }
}