boxlite 0.9.7

Embeddable virtual machine runtime for secure, isolated code execution
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
411
//! Integration tests for jailer enforcement.
//!
//! Verifies:
//! 1. Jailer is enabled by default on macOS (disabled by default on Linux)
//! 2. Boxes start and execute correctly with jailer enabled (regression guard)
//! 3. Explicitly disabling the jailer still works
//! 4. On Linux: bwrap creates isolated mount/user namespaces

mod common;

use boxlite::runtime::advanced_options::{AdvancedBoxOptions, SecurityOptions};
use boxlite::runtime::options::BoxOptions;
use common::box_test::BoxTestBase;
use std::path::PathBuf;

// ============================================================================
// JAILER-SPECIFIC HELPERS
// ============================================================================

#[cfg(target_os = "macos")]
const MACOS_UNIX_SOCKET_PATH_MAX: usize = 104;

fn jailer_test_home_base_dir() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".boxlite-it")
}

#[cfg(target_os = "macos")]
fn assert_macos_socket_path_budget(home_dir: &std::path::Path) {
    let probe = home_dir
        .join("boxes")
        .join("12345678-1234-1234-1234-123456789abc")
        .join("sockets")
        .join("box.sock");
    let probe_len = probe.to_string_lossy().len();
    let budget = MACOS_UNIX_SOCKET_PATH_MAX - 1;
    assert!(
        probe_len <= budget,
        "Jailer test home base is too long for macOS Unix socket paths \
         (probe={}, len={}, budget={}). Use a shorter base path than {}",
        probe.display(),
        probe_len,
        budget,
        home_dir.display()
    );
}

/// Per-test home for jailer tests under `~/.boxlite-it`.
///
/// Uses a short base path to satisfy macOS 104-char Unix socket path limit.
/// Cleanup: `PerTestBoxHome` (owned by `BoxTestBase` after `.home` is moved)
/// handles per-test TempDir removal via Drop. The base dir `~/.boxlite-it`
/// is left in place (shared across test runs).
struct JailerHome {
    home: boxlite_test_utils::home::PerTestBoxHome,
}

impl JailerHome {
    fn new() -> Self {
        let base = jailer_test_home_base_dir();
        std::fs::create_dir_all(&base).expect("create jailer test home base");
        let home = boxlite_test_utils::home::PerTestBoxHome::new_in(
            base.to_str().expect("base path UTF-8"),
        );

        #[cfg(target_os = "macos")]
        assert_macos_socket_path_budget(&home.path);
        #[cfg(target_os = "macos")]
        {
            let canonical = home
                .path
                .canonicalize()
                .unwrap_or_else(|_| home.path.clone());
            assert!(
                !canonical.starts_with("/private/tmp"),
                "jailer tests must not use /private/tmp as home_dir: {}",
                canonical.display()
            );
        }

        Self { home }
    }
}

fn jailer_enabled_options() -> BoxOptions {
    BoxOptions {
        advanced: AdvancedBoxOptions {
            security: SecurityOptions {
                jailer_enabled: true,
                ..SecurityOptions::default()
            },
            ..Default::default()
        },
        ..common::alpine_opts()
    }
}

fn jailer_disabled_options() -> BoxOptions {
    BoxOptions {
        advanced: AdvancedBoxOptions {
            security: SecurityOptions {
                jailer_enabled: false,
                ..SecurityOptions::default()
            },
            ..Default::default()
        },
        ..common::alpine_opts()
    }
}

#[cfg(target_os = "macos")]
fn with_sandbox_profile(mut options: BoxOptions, profile_path: std::path::PathBuf) -> BoxOptions {
    options.advanced.security.sandbox_profile = Some(profile_path);
    options
}

#[cfg(target_os = "macos")]
fn sandbox_exec_available() -> bool {
    std::path::Path::new("/usr/bin/sandbox-exec").exists()
}

#[cfg(target_os = "macos")]
fn sbpl_escape(path: &std::path::Path) -> String {
    path.display()
        .to_string()
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
}

#[cfg(target_os = "macos")]
fn write_deny_boxes_profile(home_dir: &std::path::Path) -> std::path::PathBuf {
    let raw_boxes = home_dir.join("boxes");
    let canonical_boxes = raw_boxes
        .canonicalize()
        .unwrap_or_else(|_| raw_boxes.clone());

    let mut deny_rules = vec![
        format!(
            "(deny file-read* (subpath \"{}\"))",
            sbpl_escape(raw_boxes.as_path())
        ),
        format!(
            "(deny file-write* (subpath \"{}\"))",
            sbpl_escape(raw_boxes.as_path())
        ),
    ];

    if canonical_boxes != raw_boxes {
        deny_rules.push(format!(
            "(deny file-read* (subpath \"{}\"))",
            sbpl_escape(canonical_boxes.as_path())
        ));
        deny_rules.push(format!(
            "(deny file-write* (subpath \"{}\"))",
            sbpl_escape(canonical_boxes.as_path())
        ));
    }

    let profile = format!("(version 1)\n(allow default)\n{}\n", deny_rules.join("\n"));

    let profile_path = home_dir.join("deny-boxes.sbpl");
    std::fs::write(&profile_path, profile).expect("Failed to write deny profile");
    profile_path
}

// ============================================================================
// DEFAULT CONFIGURATION TESTS
// ============================================================================

/// Verify SecurityOptions::default() enables the jailer (secure by default).
///
/// Since #652 the default profile is fully enabled on every supported
/// platform, so `jailer_enabled` is `true` on both macOS and Linux.
#[test]
fn default_security_options_enable_jailer_on_supported_platforms() {
    let opts = SecurityOptions::default();

    assert!(
        opts.jailer_enabled,
        "Jailer should be enabled by default (secure by default)"
    );
}

/// Verify SecurityOptions::disabled() always disables the jailer.
#[test]
fn development_mode_disables_jailer() {
    let opts = SecurityOptions::disabled();
    assert!(
        !opts.jailer_enabled,
        "Development mode must always disable the jailer"
    );
}

/// Verify SecurityOptions::enabled() enables the jailer on Linux/macOS.
#[test]
fn standard_mode_enables_jailer() {
    let opts = SecurityOptions::enabled();

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    assert!(
        opts.jailer_enabled,
        "Standard mode should enable jailer on Linux/macOS"
    );
}

// ============================================================================
// INTEGRATION TESTS: Jailer enabled regression guard
// ============================================================================

/// Box with jailer enabled starts and executes commands successfully.
#[tokio::test]
async fn jailer_enabled_box_starts_and_executes() {
    let jh = JailerHome::new();
    let t = BoxTestBase::with_home(jh.home, jailer_enabled_options()).await;
    t.bx.start().await.unwrap();

    let out = t.exec_stdout("echo", &["jailer-test"]).await;
    assert!(
        out.contains("jailer-test"),
        "Command should succeed with jailer enabled"
    );
}

/// Box with jailer explicitly disabled still works (development mode).
#[tokio::test]
async fn jailer_disabled_box_starts_and_executes() {
    let jh = JailerHome::new();
    let t = BoxTestBase::with_home(jh.home, jailer_disabled_options()).await;
    t.bx.start().await.unwrap();

    let out = t.exec_stdout("echo", &["no-jailer-test"]).await;
    assert!(
        out.contains("no-jailer-test"),
        "Command should succeed with jailer disabled"
    );
}

#[cfg(target_os = "macos")]
#[tokio::test]
async fn jailer_enabled_custom_profile_deny_boxes_subpath_blocks_start() {
    if !sandbox_exec_available() {
        eprintln!("Skipping: /usr/bin/sandbox-exec not available");
        return;
    }

    let jh = JailerHome::new();
    let profile_path = write_deny_boxes_profile(&jh.home.path);
    let t = BoxTestBase::with_home(
        jh.home,
        with_sandbox_profile(jailer_enabled_options(), profile_path),
    )
    .await;

    let box_id = t.bx.id().clone();
    let start_result =
        tokio::time::timeout(std::time::Duration::from_secs(600), t.bx.start()).await;

    let start_result = match start_result {
        Ok(result) => result,
        Err(_) => {
            panic!("start() timed out while waiting for sandbox denial");
        }
    };
    assert!(
        start_result.is_err(),
        "Expected start to fail with deny profile for boxes subpath"
    );

    let stderr_path = t
        .home_dir()
        .join("boxes")
        .join(box_id.as_str())
        .join("shim.stderr");
    assert!(
        stderr_path.exists(),
        "shim.stderr should exist after denied startup: {}",
        stderr_path.display()
    );

    let stderr = std::fs::read_to_string(&stderr_path).expect("Should read shim.stderr");
    let stderr_lower = stderr.to_lowercase();
    // "file exists" is valid deny evidence: when the sandbox blocks stat() on a
    // pre-created directory, Rust's create_dir_all can't verify the existing path
    // is a directory and surfaces the original EEXIST from mkdir instead of Ok(()).
    // Without the sandbox, create_dir_all handles existing directories gracefully.
    let has_deny_evidence = stderr_lower.contains("operation not permitted")
        || stderr_lower.contains("sandbox")
        || stderr_lower.contains("deny")
        || stderr_lower.contains("file exists");
    assert!(
        has_deny_evidence,
        "Expected sandbox deny evidence in shim.stderr, got:\n{}",
        stderr
    );
    // Drop: BoxTestBase -> RuntimeImpl::Drop stops non-detached boxes,
    //        PerTestBoxHome -> TempDir cleans up per-test dir.
}

#[cfg(target_os = "macos")]
#[tokio::test]
async fn jailer_disabled_with_same_profile_still_starts() {
    if !sandbox_exec_available() {
        eprintln!("Skipping: /usr/bin/sandbox-exec not available");
        return;
    }

    let jh = JailerHome::new();
    let profile_path = write_deny_boxes_profile(&jh.home.path);
    let t = BoxTestBase::with_home(
        jh.home,
        with_sandbox_profile(jailer_disabled_options(), profile_path),
    )
    .await;
    t.bx.start().await.unwrap();

    let out = t
        .exec_stdout("echo", &["profile-ignored-with-jailer-disabled"])
        .await;
    assert!(
        out.contains("profile-ignored-with-jailer-disabled"),
        "Control case should start and execute"
    );
}

// ============================================================================
// LINUX-ONLY: Namespace isolation enforcement
// ============================================================================

/// Find a descendant of `root` whose mount namespace differs from `host`.
///
/// `shim.pid` records the *outer* bwrap launcher, which stays in the host mount
/// namespace. bwrap runs with `--unshare-pid`, so it forks: the sandboxed
/// processes — the inner bwrap and the shim itself (which runs under libkrun,
/// so its `comm` shows as "libkrun VM", not "boxlite-shim") — live in a new
/// namespace below it. Walk `/proc` parent links from `root` and return the
/// first descendant that is actually isolated. Returns `None` only if no
/// descendant left the host namespace, i.e. isolation genuinely failed.
#[cfg(target_os = "linux")]
fn isolated_descendant(root: u32, host: &std::path::Path) -> Option<u32> {
    // A failure to read /proc is a broken test environment, not "no isolation";
    // fail fast with the real cause rather than reporting an isolation failure.
    let procs: Vec<(u32, u32)> = std::fs::read_dir("/proc")
        .expect("read /proc to walk the process tree")
        .flatten()
        .filter_map(|e| {
            let pid = e.file_name().to_str()?.parse::<u32>().ok()?;
            let status = std::fs::read_to_string(format!("/proc/{pid}/status")).ok()?;
            let ppid = status
                .lines()
                .find_map(|l| l.strip_prefix("PPid:")?.trim().parse::<u32>().ok())?;
            Some((pid, ppid))
        })
        .collect();

    let mut stack = vec![root];
    while let Some(cur) = stack.pop() {
        for (pid, ppid) in &procs {
            if *ppid == cur {
                let isolated = std::fs::read_link(format!("/proc/{pid}/ns/mnt"))
                    .is_ok_and(|ns| ns.as_path() != host);
                if isolated {
                    return Some(*pid);
                }
                stack.push(*pid);
            }
        }
    }
    None
}

/// On Linux, verify bwrap creates an isolated mount namespace for the shim.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn jailer_creates_isolated_mount_namespace() {
    let jh = JailerHome::new();
    let t = BoxTestBase::with_home(jh.home, jailer_enabled_options()).await;
    t.bx.start().await.unwrap();

    // Start a long-running command so the shim stays alive
    let _execution =
        t.bx.exec(boxlite::BoxCommand::new("sleep").arg("30"))
            .await
            .unwrap();

    // Read the shim's PID
    let pid_file = t
        .home_dir()
        .join("boxes")
        .join(t.bx.id().as_str())
        .join("shim.pid");
    let recorded_pid = boxlite::util::PidFileReader::at(&pid_file)
        .read()
        .map(|r| r.pid)
        .expect("Should read shim PID file");

    let self_mnt_ns =
        std::fs::read_link("/proc/self/ns/mnt").expect("Should read own mount namespace");

    // The recorded pid is the outer bwrap launcher, which shares the test's
    // (host) mount namespace; the sandboxed processes are its descendants in a
    // new namespace. Verify at least one descendant is actually isolated.
    let isolated = isolated_descendant(recorded_pid, &self_mnt_ns);

    assert!(
        isolated.is_some(),
        "bwrap should place the sandboxed process tree in a different mount \
         namespace than the test, but recorded pid {recorded_pid} and all of its \
         descendants share the test namespace {self_mnt_ns:?} (bwrap isolation inactive)"
    );
}