Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

perf(jailer): stage shim and libkrunfw in shared versioned cache (#3059)

lfld2875ea2756eb35c
diff --git a/Cargo.lock b/Cargo.lock
index f3f7a80d6..0dbc27fae 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -568,7 +568,6 @@ dependencies = [
"rand 0.9.4",
"rayon",
"rcgen",
- "reflink-copy",
"regex",
"reqwest",
"rusqlite",
@@ -5015,18 +5014,6 @@ dependencies = [
"syn 2.0.117",
]
-[[package]]
-name = "reflink-copy"
-version = "0.1.29"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "13362233b147e57674c37b802d216b7c5e3dcccbed8967c84f0d8d223868ae27"
-dependencies = [
- "cfg-if",
- "libc",
- "rustix 1.1.4",
- "windows 0.62.2",
-]
-
[[package]]
name = "regex"
version = "1.12.3"
diff --git a/apps/e2e/local.py b/apps/e2e/local.py
index 2ac20814e..a20c295e2 100755
--- a/apps/e2e/local.py
+++ b/apps/e2e/local.py
@@ -380,9 +380,13 @@ def save_pids(pids):
atomic_json(STATE / "pids.json", pids)
-def process_starttime(pid):
+def _proc_stat_fields(pid):
raw = Path(f"/proc/{pid}/stat").read_text()
- return raw[raw.rfind(")") + 2:].split()[19]
+ return raw[raw.rfind(")") + 2:].split()
+
+
+def process_starttime(pid):
+ return _proc_stat_fields(pid)[19]
def process_matches(pid, starttime):
@@ -436,7 +440,8 @@ def owned_process(argv, home=None):
home = RUNTIME_HOME if home is None else home
if not argv:
return False
- if f"{home}/boxes/" not in "\0".join(argv):
+ command_line = "\0".join(argv)
+ if not any(f"{home}/{directory}/" in command_line for directory in ("boxes", "shims")):
return False
return Path(argv[0]).name in ("bwrap", "boxlite-shim")
@@ -544,8 +549,7 @@ def adoptable_box(box):
if not 0 < pid < 2**31:
return False
os.kill(pid, 0)
- raw = Path(f"/proc/{pid}/stat").read_text()
- fields = raw[raw.rfind(")") + 2:].split()
+ fields = _proc_stat_fields(pid)
if fields[0] == "Z":
return False
expected = lines[1].strip().removeprefix("+") if len(lines) > 1 else ""
@@ -560,15 +564,41 @@ def adoptable_box(box):
return False
+def _box_names(argv):
+ prefix = f"{RUNTIME_HOME}/boxes/"
+ return {arg[len(prefix):].split("/", 1)[0] for arg in argv if arg.startswith(prefix)}
+
+
+def _shared_shim_box_names(pid):
+ try:
+ parent_argv = _argv(int(_proc_stat_fields(pid)[1]))
+ except (OSError, ValueError, IndexError):
+ parent_argv = []
+ if owned_process(parent_argv) and Path(parent_argv[0]).name == "bwrap":
+ return _box_names(parent_argv)
+
+ try:
+ environment = Path(f"/proc/{pid}/environ").read_bytes()
+ except OSError:
+ return set()
+ for entry in environment.split(b"\0"):
+ key, _, value = entry.partition(b"=")
+ if key == b"BOXLITE_BOX_ID":
+ return {os.fsdecode(value)}
+ return set()
+
+
def reap_unrecoverable_boxes():
"""Reap only owned trees that runtime recovery cannot identify as live."""
- prefix = str(RUNTIME_HOME / "boxes") + "/"
unrecoverable = []
for pid in box_processes():
- names = {arg[len(prefix):].split("/", 1)[0]
- for arg in _argv(pid) if arg.startswith(prefix)}
- if not names or any(name in ("", ".", "..") for name in names):
- continue # Ambiguous ownership is not permission to kill.
+ argv = _argv(pid)
+ names = _box_names(argv)
+ if (not names and argv and argv[0].startswith(f"{RUNTIME_HOME}/shims/")
+ and Path(argv[0]).name == "boxlite-shim"):
+ names = _shared_shim_box_names(pid)
+ if not names or any("/" in name or name in ("", ".", "..") for name in names):
+ continue # Reaping requires a valid Box ID.
if not any(adoptable_box(RUNTIME_HOME / "boxes" / name) for name in names):
unrecoverable.append(pid)
if unrecoverable:
diff --git a/docs/contributing/architecture/vmm/README.md b/docs/contributing/architecture/vmm/README.md
index 34c77c622..45f01f570 100644
--- a/docs/contributing/architecture/vmm/README.md
+++ b/docs/contributing/architecture/vmm/README.md
@@ -585,13 +585,28 @@ setup. Its empty disk registry makes `resize_disk()` return `InvalidInput`.
The host kernel enforces the shim's configured or inherited
[`RLIMIT_FSIZE` soft limit](../../../../src/boxlite/src/jailer/README.md#layer-3-resource-limits).
- **libkrun assumptions outside `krun/`.**
- - The jailer copies libkrunfw into every box
- (`src/boxlite/src/jailer/shim_copy.rs:103-105`).
+ - The jailer stages the shim and its adjacent libkrunfw files together under
+ `<home>/shims/<digest>/`. The sandbox receives read-only access to that
+ directory, and libkrun loads the firmware from beside the shim.
- The network socket name derives from libkrun's `-krun.sock` suffix
(`src/boxlite/src/net/socket_path.rs:51-59`).
- The Linux seccomp filter is written for libkrun's threads
(`src/boxlite/src/jailer/seccomp.rs:239-243`).
+### Shared shim cache
+
+```text
+Installed shim + libkrunfw → content digest → <home>/shims/<digest>/
+ ├─ read-only → Box A shim
+ └─ read-only → Box B shim
+```
+
+The cache hashes filenames, lengths, and contents in filename order. The
+runtime can reuse a digest in-process when source file metadata matches and the
+timestamps were stable before hashing. A cold start copies into a staging
+directory and renames it into place after writing the completion stamp. Boxes
+using the same shim and firmware share one published directory.
+
## Guest boot contract
The table compares what the guest gets from libkrun today with what it gets
diff --git a/docs/reference/file-formats.md b/docs/reference/file-formats.md
index 90e819a40..6e8d06024 100644
--- a/docs/reference/file-formats.md
+++ b/docs/reference/file-formats.md
@@ -14,7 +14,6 @@ BoxLite keeps boxes, images, and its database under its home directory, `~/.boxl
│ ├── sockets/ # Unix sockets: control, guest ready, network
│ ├── shared/ # Files shared with the guest over virtio-fs
│ ├── mounts/ # Host side of shared/ (isolate_mounts, Linux)
-│ ├── bin/ # Shim binary and libraries the jailer copies in
│ ├── boot/ # Custom kernel and initramfs
│ ├── ca/ # CA for secret injection, kept from the guest
│ ├── logs/ # Shim logs and console.log (kernel, init)
@@ -23,6 +22,11 @@ BoxLite keeps boxes, images, and its database under its home directory, `~/.boxl
│ ├── shim.stderr # Shim stderr, for crash diagnostics
│ ├── exit # Shim exit record: exit code and error details
│ └── exit.previous # Exit record from the previous run
+├── shims/ # Shared shim cache for jailed boxes
+│ └── {digest}/ # First 16 lowercase hex characters of SHA-256
+│ ├── boxlite-shim # Executable used by the jailer
+│ ├── libkrunfw.* # Bundled firmware loaded from beside the shim
+│ └── .complete # BoxLite version and build profile on separate lines
├── bases/ # Immutable clone bases and guest rootfs cache
├── images/ # OCI image cache
│ ├── layers/ # Layer blobs
@@ -58,6 +62,12 @@ directories are cleaned during runtime initialization and are not returned as vo
cleanup failure is logged and retried at the next initialization; it neither restores a logically
removed volume nor prevents the runtime from opening.
+The jailer refreshes the completion stamp on each cache use. Runtime startup
+and new publications prune entries older than one hour for debug builds and
+seven days for release or unknown builds. Unfinished `.staging.*` directories
+expire after one hour. Jailed box startup attempts to remove any legacy
+`boxes/{box-id}/bin/` directory.
+
The embedded runtime lives outside the home directory, in `boxlite/runtimes/` under the platform's
local data directory: `~/Library/Application Support` on macOS, `~/.local/share` on Linux.
diff --git a/src/boxlite/Cargo.toml b/src/boxlite/Cargo.toml
index c0f517503..7f49f713a 100644
--- a/src/boxlite/Cargo.toml
+++ b/src/boxlite/Cargo.toml
@@ -97,7 +97,6 @@ nix = { version = "0.30.1", features = ["fs", "mount"] }
rand = "0.9.3"
hex = "0.4.3"
signal-hook = "0.3"
-reflink-copy = "0.1"
nanoid = "0.4"
rcgen = "0.13"
time = "0.3"
diff --git a/src/boxlite/src/jailer/README.md b/src/boxlite/src/jailer/README.md
index 51d596f37..e8462c68d 100644
--- a/src/boxlite/src/jailer/README.md
+++ b/src/boxlite/src/jailer/README.md
@@ -135,6 +135,24 @@ others continue to provide protection.
**Note**: macOS provides weaker isolation than Linux. Production deployments
requiring maximum security should use Linux.
+#### Shared shim cache
+
+The jailer stages the shim and adjacent `libkrunfw.*` files in
+`<home>/shims/<digest>/`. Each jailed shim receives read-only access to its
+digest directory. The jailer also grants access to the original binary's
+library directory for dynamic linking. If staging fails, the jailer runs the
+installed shim inside the sandbox; when that fallback binary or adjacent
+`libkrunfw.*` entries are symlinks (such as `target/<profile>/runtime/`), the
+jailer grants single-file read-only access to each resolved target without
+exposing parent directories, and Bubblewrap mounts those resolved files into
+`/run/boxlite-shim` so relative symlinks do not dangle.
+Custom macOS `sandbox_profile` policies must grant read access to `<home>/shims/`.
+
+Boxes under the same `BOXLITE_HOME` share `boxlite-shim` and `libkrunfw.*`
+pages, which read-only binds on Linux and Seatbelt rules on macOS keep
+immutable to guests. Sharing eliminates per-box disk copies, avoids `ETXTBSY`
+during upgrades, and reduces macOS per-inode code-signature validation overhead.
+
### Layer 3: Resource Limits
**Mechanism**: cgroups (Linux), rlimits (both platforms)
diff --git a/src/boxlite/src/jailer/builder.rs b/src/boxlite/src/jailer/builder.rs
index 3c1999e30..c9a00569e 100644
--- a/src/boxlite/src/jailer/builder.rs
+++ b/src/boxlite/src/jailer/builder.rs
@@ -30,6 +30,7 @@ pub struct JailerBuilder {
mounts: Vec<MountSpec>,
box_id: Option<String>,
layout: Option<BoxFilesystemLayout>,
+ shim_cache_dir: Option<PathBuf>,
preserved_fds: Vec<(RawFd, i32)>,
detach: bool,
additional_path_access: Vec<PathAccess>,
@@ -51,6 +52,7 @@ impl JailerBuilder {
mounts: Vec::new(),
box_id: None,
layout: None,
+ shim_cache_dir: None,
preserved_fds: Vec::new(),
detach: false,
additional_path_access: Vec::new(),
@@ -70,6 +72,11 @@ impl JailerBuilder {
self
}
+ pub(crate) fn with_shim_cache_dir(mut self, dir: impl Into<PathBuf>) -> Self {
+ self.shim_cache_dir = Some(dir.into());
+ self
+ }
+
/// Set security options.
pub fn with_security(mut self, security: SecurityOptions) -> Self {
self.security = security;
@@ -355,6 +362,7 @@ impl JailerBuilder {
mounts: self.mounts,
box_id,
layout,
+ shim_cache_dir: self.shim_cache_dir,
preserved_fds: self.preserved_fds,
detach: self.detach,
additional_path_access: self.additional_path_access,
diff --git a/src/boxlite/src/jailer/command.rs b/src/boxlite/src/jailer/command.rs
index 361bfb89c..27756412b 100644
--- a/src/boxlite/src/jailer/command.rs
+++ b/src/boxlite/src/jailer/command.rs
@@ -7,14 +7,209 @@
mod tests {
use crate::jailer::Jail;
use crate::jailer::builder::JailerBuilder;
+ use crate::jailer::sandbox::{PathAccess, Sandbox, SandboxContext};
use crate::runtime::advanced_options::SecurityOptions;
use crate::runtime::layout::{BoxFilesystemLayout, FsLayoutConfig};
+ use std::fs;
use std::path::{Path, PathBuf};
+ use std::process::Command;
+ use std::sync::Mutex;
fn test_layout(box_dir: impl Into<PathBuf>) -> BoxFilesystemLayout {
BoxFilesystemLayout::new(box_dir.into(), FsLayoutConfig::without_bind_mount(), false)
}
+ #[derive(Default)]
+ struct RecordingSandbox(Mutex<Vec<PathAccess>>);
+
+ impl Sandbox for RecordingSandbox {
+ fn is_available(&self) -> bool {
+ true
+ }
+
+ fn apply(&self, ctx: &SandboxContext, _cmd: &mut Command) {
+ *self.0.lock().unwrap() = ctx.paths.clone();
+ }
+
+ fn name(&self) -> &'static str {
+ "recording"
+ }
+ }
+
+ fn staging_fixture() -> (
+ tempfile::TempDir,
+ PathBuf,
+ BoxFilesystemLayout,
+ JailerBuilder,
+ ) {
+ let home = tempfile::tempdir().unwrap();
+ let source = home.path().join("installed");
+ fs::create_dir(&source).unwrap();
+ let binary = source.join("boxlite-shim");
+ fs::write(&binary, b"shim").unwrap();
+ let layout = test_layout(home.path().join("boxes/test-box"));
+ let builder = JailerBuilder::new()
+ .with_box_id("test-box")
+ .with_layout(layout.clone())
+ .with_jailer_enabled(true);
+ (home, binary, layout, builder)
+ }
+
+ #[test]
+ fn command_stages_into_shared_cache_and_grants_ro_access() {
+ let (home, binary, layout, builder) = staging_fixture();
+ let jail = builder.build_with(RecordingSandbox::default()).unwrap();
+
+ let cmd = jail.command(&binary, &[]);
+ let staged = Path::new(cmd.get_program());
+ let generation = staged.parent().unwrap();
+ let cache = home.path().join("shims").canonicalize().unwrap();
+ assert_eq!(generation.parent(), Some(cache.as_path()));
+ assert_eq!(fs::read(staged).unwrap(), b"shim");
+ assert!(!layout.bin_dir().exists());
+ let grants = jail.sandbox.0.lock().unwrap();
+ for dir in [binary.parent().unwrap(), generation] {
+ let matching: Vec<_> = grants.iter().filter(|grant| grant.path == dir).collect();
+ assert_eq!(matching.len(), 1);
+ assert!(!matching[0].writable);
+ }
+ assert!(grants.iter().all(|grant| grant.path != cache));
+ }
+
+ #[test]
+ fn command_removes_legacy_box_bin_best_effort() {
+ let (_home, binary, layout, builder) = staging_fixture();
+ fs::create_dir_all(layout.bin_dir()).unwrap();
+ fs::write(layout.bin_dir().join("stale-shim"), b"old").unwrap();
+ let jail = builder.build_with(RecordingSandbox::default()).unwrap();
+
+ let cmd = jail.command(&binary, &[]);
+ assert!(Path::new(cmd.get_program()).is_file());
+ assert!(!layout.bin_dir().exists());
+
+ fs::write(layout.bin_dir(), b"not a directory").unwrap();
+ assert_eq!(jail.command(&binary, &[]).get_program(), cmd.get_program());
+ }
+
+ #[test]
+ fn command_falls_back_to_original_binary_on_stage_error() {
+ let (_home, binary, _layout, builder) = staging_fixture();
+ let jail = builder
+ .with_shim_cache_dir(&binary)
+ .build_with(RecordingSandbox::default())
+ .unwrap();
+
+ assert_eq!(jail.command(&binary, &[]).get_program(), binary);
+ let grants = jail.sandbox.0.lock().unwrap();
+ assert!(grants.iter().any(|grant| {
+ grant.path == binary.parent().unwrap().canonicalize().unwrap() && !grant.writable
+ }));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn command_fallback_symlinked_runtime_grants_only_resolved_targets() {
+ use std::os::unix::fs::symlink;
+
+ let home = tempfile::tempdir().unwrap();
+ let target_root = home.path().join("target-debug");
+ let build_out = target_root.join("build/boxlite-hash/out/runtime");
+ let runtime_dir = target_root.join("runtime");
+ fs::create_dir_all(&build_out).unwrap();
+ fs::create_dir_all(&runtime_dir).unwrap();
+
+ let real_shim = target_root.join("boxlite-shim");
+ let real_fw = build_out.join("libkrunfw.5.dylib");
+ let sibling_top = target_root.join("sibling.txt");
+ let sibling_fw = build_out.join("sibling-fw.txt");
+ fs::write(&real_shim, b"shim").unwrap();
+ fs::write(&real_fw, b"fw").unwrap();
+ fs::write(&sibling_top, b"secret").unwrap();
+ fs::write(&sibling_fw, b"secret-fw").unwrap();
+
+ let runtime_shim = runtime_dir.join("boxlite-shim");
+ let runtime_fw = runtime_dir.join("libkrunfw.5.dylib");
+ let runtime_fw_alias = runtime_dir.join("libkrunfw.dylib");
+ symlink("../boxlite-shim", &runtime_shim).unwrap();
+ symlink(
+ "../build/boxlite-hash/out/runtime/libkrunfw.5.dylib",
+ &runtime_fw,
+ )
+ .unwrap();
+ symlink("libkrunfw.5.dylib", &runtime_fw_alias).unwrap();
+
+ let layout = test_layout(home.path().join("boxes/test-box"));
+ let staging_err_jail = JailerBuilder::new()
+ .with_box_id("test-box")
+ .with_layout(layout)
+ .with_shim_cache_dir(&runtime_shim)
+ .with_jailer_enabled(true)
+ .build_with(RecordingSandbox::default())
+ .unwrap();
+ let no_cache_layout = test_layout(home.path().join("standalone-box"));
+ let no_cache_jail = JailerBuilder::new()
+ .with_box_id("test-box-no-cache")
+ .with_layout(no_cache_layout)
+ .with_jailer_enabled(true)
+ .build_with(RecordingSandbox::default())
+ .unwrap();
+
+ let canonical_shim = real_shim.canonicalize().unwrap();
+ let canonical_fw = real_fw.canonicalize().unwrap();
+ let canonical_root = target_root.canonicalize().unwrap();
+ let canonical_build_out = build_out.canonicalize().unwrap();
+
+ for jail in [&staging_err_jail, &no_cache_jail] {
+ let cmd = jail.command(&runtime_shim, &[]);
+ assert_eq!(cmd.get_program(), runtime_shim);
+
+ let grants = jail.sandbox.0.lock().unwrap();
+ for resolved in [&canonical_shim, &canonical_fw] {
+ let matches: Vec<_> = grants.iter().filter(|g| &g.path == resolved).collect();
+ assert_eq!(
+ matches.len(),
+ 1,
+ "resolved file {} must be granted exactly once (got {:?})",
+ resolved.display(),
+ grants
+ );
+ assert!(!matches[0].writable);
+ }
+
+ for forbidden in [
+ target_root.as_path(),
+ canonical_root.as_path(),
+ build_out.as_path(),
+ canonical_build_out.as_path(),
+ sibling_top.as_path(),
+ sibling_fw.as_path(),
+ ] {
+ assert!(
+ grants.iter().all(|g| g.path != forbidden),
+ "fallback must not expose {}",
+ forbidden.display()
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn command_jailer_disabled_skips_staging_and_leaves_legacy_untouched() {
+ let (home, binary, layout, builder) = staging_fixture();
+ fs::create_dir_all(layout.bin_dir()).unwrap();
+ let legacy = layout.bin_dir().join("stale-shim");
+ fs::write(&legacy, b"old").unwrap();
+ let jail = builder
+ .with_jailer_enabled(false)
+ .build_with(RecordingSandbox::default())
+ .unwrap();
+
+ assert_eq!(jail.command(&binary, &[]).get_program(), binary);
+ assert!(!home.path().join("shims").exists());
+ assert_eq!(fs::read(legacy).unwrap(), b"old");
+ assert!(jail.sandbox.0.lock().unwrap().is_empty());
+ }
+
/// When `jailer_enabled=false`, command() must return a direct command
/// using the binary as the program — no bwrap, no sandbox-exec.
#[test]
diff --git a/src/boxlite/src/jailer/common/fs.rs b/src/boxlite/src/jailer/common/fs.rs
deleted file mode 100644
index af6ebb5c5..000000000
--- a/src/boxlite/src/jailer/common/fs.rs
+++ /dev/null
@@ -1,208 +0,0 @@
-//! Filesystem utilities for the jailer module.
-//!
-//! Cross-platform file operations used by the jailer.
-
-use std::fs;
-use std::io;
-use std::path::Path;
-
-/// Copy a file if the source is newer or sizes differ.
-///
-/// This implements a simple "copy-if-newer" pattern to avoid unnecessary
-/// file copies when the destination already has an up-to-date version.
-///
-/// # Arguments
-///
-/// * `src` - Source file path
-/// * `dest` - Destination file path
-///
-/// # Returns
-///
-/// * `Ok(true)` - File was copied
-/// * `Ok(false)` - File was skipped (destination is up-to-date)
-/// * `Err(e)` - Copy failed
-///
-/// # Example
-///
-/// ```ignore
-/// use boxlite::jailer::common::fs::copy_if_newer;
-///
-/// let copied = copy_if_newer("/path/to/src", "/path/to/dest")?;
-/// if copied {
-/// println!("File was copied");
-/// } else {
-/// println!("File was already up-to-date");
-/// }
-/// ```
-#[allow(dead_code)] // Utility function for future DRY refactoring
-pub fn copy_if_newer(src: &Path, dest: &Path) -> io::Result<bool> {
- let should_copy = should_copy_file(src, dest);
-
- if should_copy {
- // Try reflink (CoW clone) first — instant on APFS/btrfs/xfs.
- // Reflink creates a new inode (unlike hardlink), so each box gets
- // independent page cache entries and .text sections in memory.
- match reflink_copy::reflink(src, dest) {
- Ok(()) => Ok(true),
- Err(_) => {
- // Fallback to regular copy (ext4, tmpfs, etc.)
- fs::copy(src, dest)?;
- Ok(true)
- }
- }
- } else {
- Ok(false)
- }
-}
-
-/// Check if a file should be copied based on modification time and size.
-///
-/// Returns `true` if:
-/// - Destination doesn't exist
-/// - Source is newer than destination
-/// - Source and destination have different sizes
-#[allow(dead_code)] // Used by copy_if_newer
-fn should_copy_file(src: &Path, dest: &Path) -> bool {
- if !dest.exists() {
- return true;
- }
-
- let src_meta = fs::metadata(src).ok();
- let dst_meta = fs::metadata(dest).ok();
-
- match (src_meta, dst_meta) {
- (Some(src), Some(dst)) => {
- // Copy if source is newer or sizes differ
- src.modified().ok() > dst.modified().ok() || src.len() != dst.len()
- }
- // If we can't read metadata, copy to be safe
- _ => true,
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use tempfile::tempdir;
-
- #[test]
- fn test_copy_if_newer_new_file() {
- let dir = tempdir().unwrap();
- let src = dir.path().join("src.txt");
- let dest = dir.path().join("dest.txt");
-
- fs::write(&src, "hello").unwrap();
-
- let copied = copy_if_newer(&src, &dest).unwrap();
- assert!(copied, "Should copy new file");
- assert!(dest.exists(), "Destination should exist");
- assert_eq!(fs::read_to_string(&dest).unwrap(), "hello");
- }
-
- #[test]
- fn test_copy_if_newer_same_content() {
- let dir = tempdir().unwrap();
- let src = dir.path().join("src.txt");
- let dest = dir.path().join("dest.txt");
-
- fs::write(&src, "hello").unwrap();
- fs::copy(&src, &dest).unwrap();
-
- // Small delay to ensure timestamps could differ if copied
- std::thread::sleep(std::time::Duration::from_millis(10));
-
- let copied = copy_if_newer(&src, &dest).unwrap();
- assert!(!copied, "Should not copy identical file");
- }
-
- #[test]
- fn test_copy_if_newer_different_size() {
- let dir = tempdir().unwrap();
- let src = dir.path().join("src.txt");
- let dest = dir.path().join("dest.txt");
-
- fs::write(&src, "hello world").unwrap();
- fs::write(&dest, "hi").unwrap();
-
- let copied = copy_if_newer(&src, &dest).unwrap();
- assert!(copied, "Should copy when sizes differ");
- assert_eq!(fs::read_to_string(&dest).unwrap(), "hello world");
- }
-
- #[test]
- fn test_copy_if_newer_source_newer() {
- let dir = tempdir().unwrap();
- let src = dir.path().join("src.txt");
- let dest = dir.path().join("dest.txt");
-
- // Create dest first
- fs::write(&dest, "old").unwrap();
-
- // Wait a bit, then create src
- std::thread::sleep(std::time::Duration::from_millis(100));
- fs::write(&src, "new").unwrap();
-
- let copied = copy_if_newer(&src, &dest).unwrap();
- assert!(copied, "Should copy newer source");
- assert_eq!(fs::read_to_string(&dest).unwrap(), "new");
- }
-
- #[test]
- fn test_should_copy_file_nonexistent_dest() {
- let dir = tempdir().unwrap();
- let src = dir.path().join("src.txt");
- let dest = dir.path().join("dest.txt");
-
- fs::write(&src, "hello").unwrap();
-
- assert!(
- should_copy_file(&src, &dest),
- "Should copy when dest doesn't exist"
- );
- }
-
- /// After copy_if_newer, source and dest must have different inodes.
- /// This guarantees memory isolation: each box gets independent page cache
- /// entries and .text sections (whether reflink or regular copy was used).
- #[test]
- fn test_copy_if_newer_creates_distinct_inode() {
- use std::os::unix::fs::MetadataExt;
-
- let dir = tempdir().unwrap();
- let src = dir.path().join("binary");
- let dest = dir.path().join("binary-copy");
-
- fs::write(&src, "ELF-fake-binary-data").unwrap();
-
- let copied = copy_if_newer(&src, &dest).unwrap();
- assert!(copied);
-
- let src_ino = fs::metadata(&src).unwrap().ino();
- let dest_ino = fs::metadata(&dest).unwrap().ino();
- assert_ne!(
- src_ino, dest_ino,
- "Source and dest must have different inodes for memory isolation"
- );
- }
-
- /// Verify copy_if_newer produces byte-identical output for larger files,
- /// regardless of whether reflink or regular copy is used.
- #[test]
- fn test_copy_if_newer_large_file_byte_identical() {
- let dir = tempdir().unwrap();
- let src = dir.path().join("large.bin");
- let dest = dir.path().join("large-copy.bin");
-
- // 4KB repeated pattern (simulates a small binary)
- let pattern: Vec<u8> = (0u8..=255).cycle().take(4096).collect();
- fs::write(&src, &pattern).unwrap();
-
- let copied = copy_if_newer(&src, &dest).unwrap();
- assert!(copied);
-
- let src_data = fs::read(&src).unwrap();
- let dest_data = fs::read(&dest).unwrap();
- assert_eq!(src_data.len(), dest_data.len(), "File sizes must match");
- assert_eq!(src_data, dest_data, "File contents must be byte-identical");
- }
-}
diff --git a/src/boxlite/src/jailer/common/mod.rs b/src/boxlite/src/jailer/common/mod.rs
index 88b4f6322..46e72b8ad 100644
--- a/src/boxlite/src/jailer/common/mod.rs
+++ b/src/boxlite/src/jailer/common/mod.rs
@@ -3,7 +3,6 @@
//! These modules provide:
//! - [`fd`]: File descriptor cleanup (async-signal-safe for pre_exec)
//! - [`rlimit`]: Resource limit management (async-signal-safe for pre_exec)
-//! - [`fs`]: Filesystem utilities (copy-if-newer, etc.)
//!
//! Note: PID file writing lives in [`crate::util::pid_file::PidFileWriter`]
//! (the format is owned by `PidRecord` / `PidFileReader` / `PidFileWriter`
@@ -11,7 +10,6 @@
//! bwrap/sandbox-exec at spawn time.
pub mod fd;
-pub mod fs;
pub mod rlimit;
/// Get errno in an async-signal-safe way.
diff --git a/src/boxlite/src/jailer/mod.rs b/src/boxlite/src/jailer/mod.rs
index 5b099e996..4bd9757ff 100644
--- a/src/boxlite/src/jailer/mod.rs
+++ b/src/boxlite/src/jailer/mod.rs
@@ -60,7 +60,7 @@ mod common;
mod error;
mod pre_exec;
pub(crate) mod sandbox;
-pub(crate) mod shim_copy;
+pub(crate) mod shim_cache;
// Linux-only modules
#[cfg(target_os = "linux")]
@@ -171,8 +171,9 @@ pub trait Jail: Send + Sync {
// ============================================================================
use crate::disk::read_backing_chain;
-use crate::runtime::layout::BoxFilesystemLayout;
+use crate::runtime::layout::{BoxFilesystemLayout, FilesystemLayout, dirs};
use crate::volumes::{VolumeShare, classify_volume_share};
+use std::ffi::OsStr;
use std::path::PathBuf;
// ============================================================================
@@ -188,7 +189,6 @@ use std::path::PathBuf;
///
/// ```text
/// {box_dir}/ # NOT granted wholesale
-/// ├── bin/ [RO] # copied shim binary + libkrunfw
/// ├── boot/ [RO] # staged custom kernel + initramfs
/// ├── shared/ [RW] # guest-visible virtio-fs share root
/// ├── sockets/ [RW] # libkrun vsock/unix sockets
@@ -281,14 +281,12 @@ fn build_path_access(
}
}
- // Read-only directories (copied shim/libraries and staged boot assets).
- for dir in [layout.bin_dir(), layout.boot_dir()] {
- if dir.exists() {
- paths.push(PathAccess {
- path: dir,
- writable: false,
- });
- }
+ let boot_dir = layout.boot_dir();
+ if boot_dir.exists() {
+ paths.push(PathAccess {
+ path: boot_dir,
+ writable: false,
+ });
}
// shared/ is exposed as a read-write virtio-fs share root on macOS.
@@ -424,6 +422,7 @@ pub struct Jailer<S: Sandbox> {
pub(crate) box_id: String,
/// Box filesystem layout (provides typed path accessors).
pub(crate) layout: BoxFilesystemLayout,
+ pub(crate) shim_cache_dir: Option<PathBuf>,
/// FDs to preserve through pre_exec: each (source_fd, target_fd) is dup2'd
/// before FD cleanup. Used for watchdog pipe inheritance across fork.
pub(crate) preserved_fds: Vec<(std::os::fd::RawFd, i32)>,
@@ -472,52 +471,69 @@ impl<S: Sandbox> Jail for Jailer<S> {
let mut ctx = self.context();
- // Grant read access to original binary's library directory so the
- // dynamic linker can load libraries from the original location.
- #[allow(clippy::collapsible_if)]
+ let mut effective_binary = binary.to_path_buf();
if self.security.jailer_enabled {
- if let Some(lib_dir) = binary.parent().filter(|d| d.exists()) {
- ctx.paths.push(PathAccess {
- path: lib_dir.to_path_buf(),
- writable: false,
- });
+ let bin_dir = self.layout.bin_dir();
+ if let Err(err) = std::fs::remove_dir_all(&bin_dir)
+ && err.kind() != std::io::ErrorKind::NotFound
+ {
+ tracing::warn!(path = %bin_dir.display(), error = %err, "Failed to remove legacy shim directory");
}
- }
-
- // Shim copy (Firecracker pattern) — shared for both platforms
- let effective_binary = if self.security.jailer_enabled {
- match shim_copy::copy_shim_to_box(binary, self.layout.root()) {
- Ok(copied) => {
- tracing::info!(
- original = %binary.display(),
- copied = %copied.display(),
- "Using copied shim binary (Firecracker pattern)"
- );
- copied
- }
- Err(e) => {
- tracing::warn!(error = %e, "Failed to copy shim, using original");
- binary.to_path_buf()
+ let mut staged_ok = false;
+ if let Some(cache_dir) = self.resolve_shim_cache_dir() {
+ match shim_cache::stage_shim(binary, &cache_dir) {
+ Ok(staged) => {
+ effective_binary = staged;
+ staged_ok = true;
+ }
+ Err(err) => {
+ tracing::warn!(error = %err, "Failed to stage shim, using original")
+ }
}
+ ctx.shim_cache_dir = Some(cache_dir);
+ } else {
+ tracing::debug!(box_id = %self.box_id, "No shim cache directory resolved, using original shim");
}
- } else {
- binary.to_path_buf()
- };
- // copy_shim_to_box() created box/bin and the copied shim above, but
- // context() computed the bind list *before* that — so box/bin (which
- // didn't exist yet) was skipped. Add it now, read-only, otherwise bwrap
- // can't see the shim binary it is about to exec (execvp ENOENT).
- #[allow(clippy::collapsible_if)]
- if self.security.jailer_enabled {
- if let Some(bin_dir) = effective_binary.parent().filter(|d| d.exists()) {
- if !ctx.paths.iter().any(|pa| pa.path == bin_dir) {
+ // Keep the original library directory visible to the dynamic linker.
+ let original_dir = binary.parent().filter(|p| !p.as_os_str().is_empty());
+ let effective_dir = effective_binary
+ .parent()
+ .filter(|p| p.exists())
+ .map(|p| p.canonicalize().unwrap_or_else(|_| p.to_path_buf()));
+ for dir in original_dir
+ .filter(|p| p.exists())
+ .into_iter()
+ .chain(effective_dir.as_deref())
+ {
+ if !ctx.paths.iter().any(|pa| pa.path == dir && !pa.writable) {
ctx.paths.push(PathAccess {
- path: bin_dir.to_path_buf(),
+ path: dir.to_path_buf(),
writable: false,
});
}
}
+
+ // On fallback (staging failed or no cache dir), a symlinked runtime/
+ // layout points outside effective_dir/original_dir; grant read-only
+ // single-file access to each resolved target without exposing sibling files.
+ if !staged_ok {
+ for file in shim_cache::resolve_runtime_files(&effective_binary).files {
+ let inside_granted_dir = original_dir
+ .is_some_and(|dir| file.canonical_source.starts_with(dir))
+ || effective_dir
+ .as_deref()
+ .is_some_and(|dir| file.canonical_source.starts_with(dir));
+ if !inside_granted_dir
+ && !ctx.paths.iter().any(|pa| pa.path == file.canonical_source)
+ {
+ ctx.paths.push(PathAccess {
+ path: file.canonical_source,
+ writable: false,
+ });
+ }
+ }
+ }
}
// Start with a bare command. Sandbox.apply() modifies it in-place.
@@ -551,6 +567,17 @@ impl<S: Sandbox> Jail for Jailer<S> {
}
impl<S: Sandbox> Jailer<S> {
+ pub(crate) fn resolve_shim_cache_dir(&self) -> Option<PathBuf> {
+ self.shim_cache_dir.clone().or_else(|| {
+ let boxes = self.layout.root().parent()?;
+ if boxes.file_name() == Some(OsStr::new(dirs::BOXES_DIR)) {
+ boxes.parent().map(FilesystemLayout::shims_dir_for)
+ } else {
+ None
+ }
+ })
+ }
+
/// Get the security options.
pub fn security(&self) -> &SecurityOptions {
&self.security
@@ -644,6 +671,7 @@ impl<S: Sandbox> Jailer<S> {
resource_limits: &self.security.resource_limits,
network_enabled: self.security.network_enabled,
sandbox_profile: self.security.sandbox_profile.as_deref(),
+ shim_cache_dir: None,
detached: self.detach,
}
}
@@ -788,16 +816,14 @@ mod tests {
let box_dir = dir.path().to_path_buf();
let layout = test_layout(box_dir.clone());
- // Create bin + boot + shared dirs
+ // A legacy bin directory may exist alongside boot and shared.
std::fs::create_dir_all(layout.bin_dir()).unwrap();
std::fs::create_dir_all(layout.boot_dir()).unwrap();
std::fs::create_dir_all(layout.shared_dir()).unwrap();
let paths = build_path_access(&layout, &[], &[]);
- let bin = paths.iter().find(|p| p.path == layout.bin_dir());
- assert!(bin.is_some(), "bin/ should be included");
- assert!(!bin.unwrap().writable, "bin/ should be read-only");
+ assert!(paths.iter().all(|p| p.path != layout.bin_dir()));
let boot = paths.iter().find(|p| p.path == layout.boot_dir());
assert!(boot.is_some(), "boot/ should be included");
@@ -967,6 +993,7 @@ mod tests {
resource_limits: &limits,
network_enabled: false,
sandbox_profile: None,
+ shim_cache_dir: None,
detached: true,
};
let mut cmd = std::process::Command::new("/usr/bin/cat");
@@ -1256,7 +1283,7 @@ mod tests {
std::fs::create_dir_all(layout.sockets_dir()).unwrap();
std::fs::create_dir_all(layout.mounts_dir()).unwrap();
std::fs::create_dir_all(layout.logs_dir()).unwrap();
- std::fs::create_dir_all(layout.bin_dir()).unwrap();
+ std::fs::create_dir_all(layout.boot_dir()).unwrap();
let paths = build_path_access(&layout, &[], &[]);
diff --git a/src/boxlite/src/jailer/sandbox/bwrap.rs b/src/boxlite/src/jailer/sandbox/bwrap.rs
index a54d1fd54..b96d7066d 100644
--- a/src/boxlite/src/jailer/sandbox/bwrap.rs
+++ b/src/boxlite/src/jailer/sandbox/bwrap.rs
@@ -65,6 +65,8 @@ impl Sandbox for BwrapSandbox {
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
+ let shim_plan =
+ crate::jailer::shim_cache::plan_bwrap_shim_mounts(std::path::Path::new(&binary));
let mut bwrap_cmd = bwrap::BwrapCommand::new();
@@ -123,6 +125,14 @@ impl Sandbox for BwrapSandbox {
bwrap_cmd.ro_bind(&pa.path, &pa.path);
tracing::debug!(path = %pa.path.display(), "bwrap: ro-bind");
}
+ for (src, dest) in &shim_plan.ro_binds {
+ bwrap_cmd.ro_bind(src, dest);
+ tracing::debug!(
+ src = %src.display(),
+ dest = %dest.display(),
+ "bwrap: ro-bind shim runtime"
+ );
+ }
// =====================================================================
// Environment sanitization
@@ -130,19 +140,15 @@ impl Sandbox for BwrapSandbox {
// The statically-linked shim dlopen's libkrunfw via LD_LIBRARY_PATH (its
// `$ORIGIN` rpath is ineffective), and `--clearenv` wipes it — without
// this the VM fails to start ("Couldn't find or load libkrunfw.so.5",
- // libkrun status=-2). Point it at the shim's own directory (`<box>/bin`),
- // which is bound into the sandbox and is exactly where `copy_libkrunfw`
- // placed the library the shim loads.
- let shim_dir = std::path::Path::new(&binary)
- .parent()
- .map(|dir| dir.to_string_lossy().into_owned())
- .unwrap_or_default();
-
+ // libkrun status=-2). The staged shim and libkrunfw share a read-only
+ // binding at `<home>/shims/<digest>`. When falling back to a symlinked
+ // `runtime/` layout, resolved targets are mounted into a synthetic
+ // read-only `/run/boxlite-shim` directory so symlinks do not dangle.
bwrap_cmd
.with_clearenv()
.setenv("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
.setenv("HOME", "/root")
- .setenv("LD_LIBRARY_PATH", shim_dir);
+ .setenv("LD_LIBRARY_PATH", shim_plan.ld_library_path.as_str());
// Preserve debugging environment variables
if let Ok(rust_log) = std::env::var("RUST_LOG") {
@@ -155,7 +161,7 @@ impl Sandbox for BwrapSandbox {
bwrap_cmd.chdir("/");
// Replace the command with bwrap-wrapped version.
- *cmd = bwrap_cmd.build(std::path::Path::new(&binary), &args);
+ *cmd = bwrap_cmd.build(&shim_plan.executable, &args);
// Add cgroup join as a pre_exec hook (async-signal-safe).
if let Some(cgroup_procs) = cgroup::build_cgroup_procs_path(ctx.id) {
@@ -201,10 +207,11 @@ mod tests {
resource_limits: limits,
network_enabled: false,
sandbox_profile: None,
+ shim_cache_dir: None,
detached: false,
};
- let shim = "/var/lib/boxlite/boxes/abc/bin/boxlite-shim";
+ let shim = "/var/lib/boxlite/shims/0123456789abcdef/boxlite-shim";
let mut cmd = Command::new(shim);
BwrapSandbox::new().apply(&ctx, &mut cmd);
@@ -219,8 +226,8 @@ mod tests {
.expect("bwrap must --setenv LD_LIBRARY_PATH so the static shim can dlopen libkrunfw");
assert_eq!(
args[pos + 2],
- "/var/lib/boxlite/boxes/abc/bin",
- "LD_LIBRARY_PATH must point at the shim's own directory (where libkrunfw is copied)"
+ "/var/lib/boxlite/shims/0123456789abcdef",
+ "LD_LIBRARY_PATH must point at the staged shim and firmware directory"
);
}
@@ -246,9 +253,10 @@ mod tests {
resource_limits: limits,
network_enabled: false,
sandbox_profile: None,
+ shim_cache_dir: None,
detached,
};
- let mut cmd = Command::new("/var/lib/boxlite/boxes/abc/bin/boxlite-shim");
+ let mut cmd = Command::new("/var/lib/boxlite/shims/0123456789abcdef/boxlite-shim");
BwrapSandbox::new().apply(&ctx, &mut cmd);
cmd.get_args().any(|a| a == "--die-with-parent")
}
@@ -262,4 +270,123 @@ mod tests {
"detached box must not get --die-with-parent or it is killed when run -d returns"
);
}
+
+ #[test]
+ fn apply_mounts_symlinked_runtime_into_synthetic_shim_dir() {
+ use crate::jailer::sandbox::PathAccess;
+ use crate::jailer::shim_cache::BWRAP_SANDBOX_SHIM_DIR;
+ use std::os::unix::fs::{PermissionsExt, symlink};
+
+ if !bwrap::is_available() {
+ eprintln!(
+ "skipping apply_mounts_symlinked_runtime_into_synthetic_shim_dir: bwrap not available"
+ );
+ return;
+ }
+
+ let root = tempfile::tempdir().unwrap();
+ let target_dir = root.path().join("target/debug");
+ let runtime_dir = target_dir.join("runtime");
+ let build_out = target_dir.join("build/boxlite-hash/out/runtime");
+ std::fs::create_dir_all(&runtime_dir).unwrap();
+ std::fs::create_dir_all(&build_out).unwrap();
+
+ let real_shim = target_dir.join("boxlite-shim");
+ std::fs::write(
+ &real_shim,
+ "#!/bin/sh\nif [ \"$#\" -gt 0 ]; then\n cat \"$1\"\nelse\n printf '%s:' \"$LD_LIBRARY_PATH\"\n cat /run/boxlite-shim/libkrunfw.so.5\nfi\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&real_shim, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let real_fw = build_out.join("libkrunfw.so.5.4.0");
+ std::fs::write(&real_fw, b"fw-ok").unwrap();
+ let sibling = target_dir.join("sibling.txt");
+ std::fs::write(&sibling, b"secret").unwrap();
+
+ let runtime_shim = runtime_dir.join("boxlite-shim");
+ let runtime_fw = runtime_dir.join("libkrunfw.so.5");
+ symlink("../boxlite-shim", &runtime_shim).unwrap();
+ symlink(
+ "../build/boxlite-hash/out/runtime/libkrunfw.so.5.4.0",
+ &runtime_fw,
+ )
+ .unwrap();
+
+ let canonical_shim = real_shim.canonicalize().unwrap();
+ let canonical_fw = real_fw.canonicalize().unwrap();
+ let limits = Box::leak(Box::new(ResourceLimits::default()));
+ let ctx = SandboxContext {
+ id: "test-box",
+ paths: vec![
+ PathAccess {
+ path: runtime_dir.clone(),
+ writable: false,
+ },
+ PathAccess {
+ path: canonical_shim.clone(),
+ writable: false,
+ },
+ PathAccess {
+ path: canonical_fw.clone(),
+ writable: false,
+ },
+ ],
+ unix_sockets: Default::default(),
+ resource_limits: limits,
+ network_enabled: false,
+ sandbox_profile: None,
+ shim_cache_dir: None,
+ detached: true,
+ };
+
+ let mut cmd = Command::new(&runtime_shim);
+ BwrapSandbox::new().apply(&ctx, &mut cmd);
+
+ let args: Vec<String> = cmd
+ .get_args()
+ .map(|a| a.to_string_lossy().into_owned())
+ .collect();
+ let expected_shim_dest = format!("{BWRAP_SANDBOX_SHIM_DIR}/boxlite-shim");
+ let expected_fw_dest = format!("{BWRAP_SANDBOX_SHIM_DIR}/libkrunfw.so.5");
+ let expected_ld = format!("{BWRAP_SANDBOX_SHIM_DIR}:{}", runtime_dir.display());
+ assert!(args.windows(3).any(|w| {
+ w[0] == "--ro-bind"
+ && w[1] == canonical_shim.to_string_lossy()
+ && w[2] == expected_shim_dest
+ }));
+ assert!(args.windows(3).any(|w| {
+ w[0] == "--ro-bind"
+ && w[1] == canonical_fw.to_string_lossy()
+ && w[2] == expected_fw_dest
+ }));
+ assert!(
+ args.windows(3)
+ .any(|w| w[0] == "--setenv" && w[1] == "LD_LIBRARY_PATH" && w[2] == expected_ld)
+ );
+ assert_eq!(
+ args.last().map(String::as_str),
+ Some(expected_shim_dest.as_str())
+ );
+
+ if bwrap::can_create_user_namespace().is_ok() {
+ let output = cmd.output().expect("execute bwrap symlinked runtime shim");
+ assert!(
+ output.status.success(),
+ "bwrap execution failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(
+ String::from_utf8_lossy(&output.stdout),
+ format!("{expected_ld}:fw-ok")
+ );
+
+ let mut sibling_cmd = Command::new(&runtime_shim);
+ sibling_cmd.arg(&sibling);
+ BwrapSandbox::new().apply(&ctx, &mut sibling_cmd);
+ let sibling_out = sibling_cmd.output().expect("execute sibling probe");
+ assert!(!sibling_out.status.success());
+ assert!(sibling_out.stdout.is_empty());
+ }
+ }
}
diff --git a/src/boxlite/src/jailer/sandbox/composite.rs b/src/boxlite/src/jailer/sandbox/composite.rs
index c9a195197..82bf25fc8 100644
--- a/src/boxlite/src/jailer/sandbox/composite.rs
+++ b/src/boxlite/src/jailer/sandbox/composite.rs
@@ -129,6 +129,7 @@ mod tests {
resource_limits: limits,
network_enabled: false,
sandbox_profile: None,
+ shim_cache_dir: None,
detached: false,
}
}
diff --git a/src/boxlite/src/jailer/sandbox/landlock.rs b/src/boxlite/src/jailer/sandbox/landlock.rs
index d2758f3d8..dc296ca42 100644
--- a/src/boxlite/src/jailer/sandbox/landlock.rs
+++ b/src/boxlite/src/jailer/sandbox/landlock.rs
@@ -92,6 +92,7 @@ mod tests {
resource_limits: limits,
network_enabled: false,
sandbox_profile: None,
+ shim_cache_dir: None,
detached: false,
}
}
diff --git a/src/boxlite/src/jailer/sandbox/mod.rs b/src/boxlite/src/jailer/sandbox/mod.rs
index 47baf35c8..d232f0fba 100644
--- a/src/boxlite/src/jailer/sandbox/mod.rs
+++ b/src/boxlite/src/jailer/sandbox/mod.rs
@@ -140,6 +140,8 @@ pub struct SandboxContext<'a> {
pub network_enabled: bool,
/// Custom sandbox profile path (macOS only).
pub sandbox_profile: Option<&'a Path>,
+ /// Shared shim cache root to protect from writes in the built-in macOS profile.
+ pub shim_cache_dir: Option<PathBuf>,
/// Whether the box is detached (`run -d`). Detached boxes must outlive the
/// launching process, so the sandbox must not tie their lifetime to it
/// (e.g. bwrap's `--die-with-parent`).
diff --git a/src/boxlite/src/jailer/sandbox/seatbelt.rs b/src/boxlite/src/jailer/sandbox/seatbelt.rs
index 8784dd388..10a3c472b 100644
--- a/src/boxlite/src/jailer/sandbox/seatbelt.rs
+++ b/src/boxlite/src/jailer/sandbox/seatbelt.rs
@@ -116,6 +116,7 @@ impl Sandbox for SeatbeltSandbox {
&ctx.paths,
&ctx.unix_sockets,
binary_path,
+ ctx.shim_cache_dir.as_deref(),
ctx.network_enabled,
ctx.sandbox_profile,
);
@@ -161,6 +162,7 @@ fn build_sandbox_exec_args(
paths: &[PathAccess],
unix_sockets: &UnixSocketAccess,
binary_path: &Path,
+ shim_cache_dir: Option<&Path>,
network_enabled: bool,
sandbox_profile: Option<&Path>,
) -> (String, Vec<String>) {
@@ -172,7 +174,13 @@ fn build_sandbox_exec_args(
args.push(profile_path.display().to_string());
} else {
// Build strict modular policy: base + file permissions + optional network
- let policy = build_sandbox_policy(paths, unix_sockets, binary_path, network_enabled);
+ let policy = build_sandbox_policy(
+ paths,
+ unix_sockets,
+ binary_path,
+ shim_cache_dir,
+ network_enabled,
+ );
if std::env::var_os("BOXLITE_DEBUG_PRINT_SEATBELT").is_some() {
eprintln!(
"BOXLITE_DEBUG seatbelt policy for {}:\n{}",
@@ -206,6 +214,7 @@ fn build_sandbox_policy(
paths: &[PathAccess],
unix_sockets: &UnixSocketAccess,
binary_path: &Path,
+ shim_cache_dir: Option<&Path>,
network_enabled: bool,
) -> String {
let mut policy = String::new();
@@ -255,14 +264,107 @@ fn build_sandbox_policy(
policy.push_str("; IP networking disabled\n");
}
+ // 8. Protect the shim and its firmware even under writable paths.
+ append_shim_write_denials(&mut policy, binary_path, shim_cache_dir);
+
policy
}
+fn append_shim_write_denials(
+ policy: &mut String,
+ binary_path: &Path,
+ shim_cache_dir: Option<&Path>,
+) {
+ let link_path = canonicalize_or_original(binary_path);
+ let target = binary_path.canonicalize().ok();
+ append_file_write_denials(policy, &link_path, target.as_deref());
+
+ if let Some(cache_dir) = shim_cache_dir {
+ let root = append_subtree_write_denial(policy, cache_dir);
+
+ // Staged files are already covered by the cache subtree denial.
+ if link_path.starts_with(&root) && target.is_some_and(|path| path.starts_with(&root)) {
+ return;
+ }
+ }
+
+ let bin_dir = binary_path
+ .parent()
+ .filter(|path| !path.as_os_str().is_empty())
+ .unwrap_or(Path::new("."));
+ let mut firmware = Vec::new();
+ let enumeration = match std::fs::read_dir(bin_dir) {
+ Ok(mut entries) => entries.try_for_each(|entry| {
+ let entry = entry?;
+ if entry
+ .file_name()
+ .as_encoded_bytes()
+ .starts_with(b"libkrunfw.")
+ {
+ let path = entry.path();
+ if path.is_file() {
+ firmware.push(path);
+ }
+ }
+ Ok(())
+ }),
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(err) => Err(err),
+ };
+ if let Err(err) = enumeration {
+ tracing::warn!(
+ path = %bin_dir.display(),
+ error = %err,
+ "Failed to enumerate shim firmware, denying writes to the shim directory"
+ );
+ append_subtree_write_denial(policy, bin_dir);
+ }
+
+ for path in firmware {
+ let link_path = canonicalize_or_original(&path);
+ let target = path.canonicalize().ok();
+ append_file_write_denials(policy, &link_path, target.as_deref());
+ }
+}
+
+fn append_subtree_write_denial(policy: &mut String, dir: &Path) -> PathBuf {
+ let link_path = canonicalize_or_original(dir);
+ let root = dir.canonicalize().unwrap_or_else(|_| link_path.clone());
+ if let Some(literal) = sbpl_path_literal(&root) {
+ policy.push_str(&format!(
+ "(deny file-write* (literal {literal}) (subpath {literal}))\n"
+ ));
+ } else {
+ tracing::warn!(path = ?root, "Skipping non-UTF-8 Seatbelt write denial");
+ }
+ if root != link_path {
+ append_literal_write_denial(policy, &link_path);
+ }
+ root
+}
+
+fn append_file_write_denials(policy: &mut String, link_path: &Path, target: Option<&Path>) {
+ append_literal_write_denial(policy, link_path);
+ if let Some(target) = target
+ && target != link_path
+ {
+ append_literal_write_denial(policy, target);
+ }
+}
+
+fn append_literal_write_denial(policy: &mut String, path: &Path) {
+ if let Some(literal) = sbpl_path_literal(path) {
+ policy.push_str(&format!("(deny file-write* (literal {literal}))\n"));
+ } else {
+ tracing::warn!(?path, "Skipping non-UTF-8 Seatbelt write denial");
+ }
+}
+
/// Generate dynamic file-read policy for binary path + all pre-computed paths.
fn build_dynamic_read_paths(binary_path: &Path, paths: &[PathAccess]) -> String {
let mut rules = String::new();
- // Add binary's parent directory (copied shim + libkrunfw)
+ // Grant access to the shim and the libkrunfw files staged beside it.
if let Some(bin_dir) = binary_path.parent() {
let bin_dir = canonicalize_or_original(bin_dir);
if let Some(literal) = sbpl_path_literal(&bin_dir) {
@@ -465,6 +567,33 @@ fn darwin_user_cache_dir() -> Option<PathBuf> {
#[cfg(test)]
mod tests {
use super::*;
+ use std::os::unix::fs::PermissionsExt;
+
+ struct UnreadableShimDir(tempfile::TempDir);
+
+ impl Drop for UnreadableShimDir {
+ fn drop(&mut self) {
+ let _ = std::fs::set_permissions(self.0.path(), std::fs::Permissions::from_mode(0o755));
+ }
+ }
+
+ fn unreadable_shim_dir() -> Option<UnreadableShimDir> {
+ let dir = UnreadableShimDir(tempfile::tempdir_in("/tmp").unwrap());
+ let path = dir.0.path();
+ for name in ["boxlite-shim", "libkrunfw.dylib"] {
+ std::fs::write(path.join(name), b"original").unwrap();
+ }
+ // Keep known paths searchable and writable while denying directory listing.
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o311)).unwrap();
+ match std::fs::read_dir(path) {
+ Ok(_) => {
+ eprintln!("Skipping: can still enumerate a directory with mode 0o311");
+ return None;
+ }
+ Err(err) => assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied),
+ }
+ Some(dir)
+ }
#[test]
fn test_seatbelt_policy_escapes_injected_file_path() {
@@ -477,6 +606,7 @@ mod tests {
}],
&UnixSocketAccess::default(),
Path::new("/bin/sh"),
+ None,
false,
);
@@ -511,6 +641,7 @@ mod tests {
}],
&UnixSocketAccess::default(),
Path::new("/bin/sh"),
+ None,
false,
);
let literal = format!("\"{}/{encoded}\"", parent.display());
@@ -539,6 +670,7 @@ mod tests {
}],
&UnixSocketAccess::default(),
&path.join("shim"),
+ None,
false,
);
for rule in [
@@ -566,6 +698,7 @@ mod tests {
}],
&UnixSocketAccess::default(),
Path::new("/bin/sh"),
+ None,
false,
);
let expected = dir.path().canonicalize().unwrap().join("link");
@@ -591,6 +724,7 @@ mod tests {
connect: vec![socket],
},
Path::new("/bin/sh"),
+ None,
false,
);
let literal = format!(
@@ -619,6 +753,7 @@ mod tests {
connect: vec![path.clone()],
},
&binary,
+ None,
false,
);
assert!(!policy.contains("invalid-"));
@@ -720,6 +855,7 @@ mod tests {
&paths,
&UnixSocketAccess::default(),
&binary_path,
+ None,
true,
None,
);
@@ -794,7 +930,13 @@ mod tests {
}];
let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");
- let policy = build_sandbox_policy(&paths, &UnixSocketAccess::default(), &binary_path, true);
+ let policy = build_sandbox_policy(
+ &paths,
+ &UnixSocketAccess::default(),
+ &binary_path,
+ None,
+ true,
+ );
assert!(policy.contains("(allow network-outbound)"));
}
@@ -807,8 +949,13 @@ mod tests {
}];
let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");
- let policy =
- build_sandbox_policy(&paths, &UnixSocketAccess::default(), &binary_path, false);
+ let policy = build_sandbox_policy(
+ &paths,
+ &UnixSocketAccess::default(),
+ &binary_path,
+ None,
+ false,
+ );
// Unfiltered grants are the IP-networking ones; they must be absent.
for grant in [
@@ -850,7 +997,8 @@ mod tests {
let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");
for network_enabled in [true, false] {
- let policy = build_sandbox_policy(&paths, &unix_sockets, &binary_path, network_enabled);
+ let policy =
+ build_sandbox_policy(&paths, &unix_sockets, &binary_path, None, network_enabled);
let socket_grants = policy
.split("(allow ")
.filter(|section| {
@@ -900,6 +1048,7 @@ mod tests {
connect: vec![],
},
&PathBuf::from("/usr/local/bin/boxlite-shim"),
+ None,
false,
);
let socket_grant_sections = policy
@@ -942,6 +1091,137 @@ mod tests {
assert!(SEATBELT_FILE_WRITE_POLICY.contains("(subpath \"/private/var/tmp\")"));
}
+ #[test]
+ fn test_shared_shim_write_denials_follow_write_grants() {
+ let home = tempfile::tempdir_in("/tmp").unwrap();
+ let shims = home.path().join("shims");
+ let generation = shims.join("0123456789abcdef");
+ std::fs::create_dir_all(&generation).unwrap();
+ let paths = [PathAccess {
+ path: home.path().to_path_buf(),
+ writable: true,
+ }];
+ let policy = build_sandbox_policy(
+ &paths,
+ &UnixSocketAccess::default(),
+ &generation.join("boxlite-shim"),
+ Some(&shims),
+ true,
+ );
+
+ let tmp_grant = policy.find("(subpath \"/private/tmp\")").unwrap();
+ let (grants, denials) = policy.rsplit_once("(allow file-write*").unwrap();
+ assert!(tmp_grant < grants.len());
+ assert!(grants.contains("; Dynamic write paths"));
+ let path = shims.canonicalize().unwrap();
+ let literal = sbpl_path_literal(&path).unwrap();
+ assert!(
+ denials.contains(&format!(
+ "(deny file-write* (literal {literal}) (subpath {literal}))"
+ )),
+ "missing write denial for {} after the write grants",
+ path.display()
+ );
+ }
+
+ #[test]
+ fn test_seatbelt_policy_denies_writes_to_symlinked_cache() {
+ let home = tempfile::tempdir_in("/tmp").unwrap();
+ let target = tempfile::tempdir_in("/tmp").unwrap();
+ let cache = home.path().join("shims");
+ std::os::unix::fs::symlink(target.path(), &cache).unwrap();
+ let generation = target.path().join("0123456789abcdef");
+ std::fs::create_dir(&generation).unwrap();
+ let shim = generation.join("boxlite-shim");
+ std::fs::write(&shim, b"shim").unwrap();
+
+ let policy = build_sandbox_policy(
+ &[],
+ &UnixSocketAccess::default(),
+ &shim,
+ Some(&cache),
+ false,
+ );
+ let target = target.path().canonicalize().unwrap();
+ let link = home.path().canonicalize().unwrap().join("shims");
+ let target = sbpl_path_literal(&target).unwrap();
+ let link = sbpl_path_literal(&link).unwrap();
+ assert!(
+ policy.contains(&format!(
+ "(deny file-write* (literal {target}) (subpath {target}))"
+ )),
+ "missing write denial for the cache target {target}"
+ );
+ assert!(
+ policy.contains(&format!("(deny file-write* (literal {link}))")),
+ "missing write denial for the cache symlink {link}"
+ );
+ }
+
+ #[test]
+ fn test_seatbelt_policy_denies_only_fallback_shim_and_firmware() {
+ let home = tempfile::tempdir_in("/tmp").unwrap();
+ let parent = home.path().canonicalize().unwrap();
+ let shim = home.path().join("boxlite-shim");
+ let firmware = home.path().join("libkrunfw.dylib");
+ for (link, name) in [(&shim, "installed-shim"), (&firmware, "installed-firmware")] {
+ let target = parent.join(name);
+ std::fs::write(&target, b"original").unwrap();
+ std::os::unix::fs::symlink(target, link).unwrap();
+ }
+ let paths = [PathAccess {
+ path: home.path().to_path_buf(),
+ writable: true,
+ }];
+
+ let policy = build_sandbox_policy(&paths, &UnixSocketAccess::default(), &shim, None, false);
+ let parent = sbpl_path_literal(&parent).unwrap();
+ assert!(
+ !policy.contains(&format!(
+ "(deny file-write* (literal {parent}) (subpath {parent}))"
+ )),
+ "fallback shim parent must remain writable"
+ );
+ for link in [&shim, &firmware] {
+ for path in [canonicalize_or_original(link), link.canonicalize().unwrap()] {
+ let literal = sbpl_path_literal(&path).unwrap();
+ assert!(
+ policy.contains(&format!("(deny file-write* (literal {literal}))")),
+ "missing file write denial for {literal}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn test_seatbelt_policy_denies_writes_to_unreadable_shim_directory() {
+ let Some(dir) = unreadable_shim_dir() else {
+ return;
+ };
+ let target_dir = tempfile::tempdir_in("/tmp").unwrap();
+ let shim = dir.0.path().join("boxlite-shim");
+ let target = target_dir.path().join("boxlite-shim");
+ std::fs::rename(&shim, &target).unwrap();
+ std::os::unix::fs::symlink(&target, &shim).unwrap();
+
+ let policy = build_sandbox_policy(&[], &UnixSocketAccess::default(), &shim, None, false);
+ let root = dir.0.path().canonicalize().unwrap();
+ let literal = sbpl_path_literal(&root).unwrap();
+ assert!(
+ policy.contains(&format!(
+ "(deny file-write* (literal {literal}) (subpath {literal}))"
+ )),
+ "missing subtree write denial for {literal}"
+ );
+ for path in [root.join("boxlite-shim"), target.canonicalize().unwrap()] {
+ let literal = sbpl_path_literal(&path).unwrap();
+ assert!(
+ policy.contains(&format!("(deny file-write* (literal {literal}))")),
+ "missing shim write denial for {literal}"
+ );
+ }
+ }
+
/// The static write policy must NOT grant the whole per-user temp/cache
/// tree (`/private/var/folders`, a.k.a. `$TMPDIR` / `DARWIN_USER_*_DIR`).
/// The shim's TMPDIR is redirected to a box-scoped path by
@@ -968,11 +1248,12 @@ mod tests {
#[test]
fn test_dynamic_read_paths_empty() {
- let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");
+ let generation = "/var/lib/boxlite/shims/0123456789abcdef";
+ let binary_path = Path::new(generation).join("boxlite-shim");
let policy = build_dynamic_read_paths(&binary_path, &[]);
assert!(policy.contains("(allow file-read*"));
- assert!(policy.contains("/usr/local/bin"));
+ assert!(policy.contains(generation));
}
#[test]
@@ -1031,8 +1312,13 @@ mod tests {
}];
let binary_path = PathBuf::from("/tmp/test/boxlite-shim");
- let policy =
- build_sandbox_policy(&paths, &UnixSocketAccess::default(), &binary_path, false);
+ let policy = build_sandbox_policy(
+ &paths,
+ &UnixSocketAccess::default(),
+ &binary_path,
+ None,
+ false,
+ );
assert!(
!policy.contains("(subpath \"/usr\")"),
@@ -1216,7 +1502,8 @@ mod tests {
let paths = crate::jailer::build_path_access(&layout, &[], &[]);
let binary = PathBuf::from("/usr/local/bin/boxlite-shim");
- let policy = build_sandbox_policy(&paths, &UnixSocketAccess::default(), &binary, false);
+ let policy =
+ build_sandbox_policy(&paths, &UnixSocketAccess::default(), &binary, None, false);
let mounts_str = mounts_base.to_string_lossy().to_string();
assert!(
@@ -1297,6 +1584,7 @@ mod tests {
paths,
&UnixSocketAccess::default(),
std::path::Path::new("/bin/sh"),
+ None,
false,
None,
);
@@ -1480,6 +1768,7 @@ mod tests {
&paths,
&UnixSocketAccess::default(),
std::path::Path::new("/bin/sh"),
+ None,
false,
None,
);
@@ -1497,6 +1786,175 @@ mod tests {
assert_eq!(String::from_utf8_lossy(&output.stdout), "tmp-exec-ok\n");
}
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn test_seatbelt_runtime_denies_writes_to_shared_shims_in_tmp() {
+ let home = tempfile::tempdir_in("/tmp").unwrap();
+ let shims = home.path().join("shims");
+ let generation = shims.join("0123456789abcdef");
+ std::fs::create_dir_all(&generation).unwrap();
+ let shim = generation.join("boxlite-shim");
+ std::fs::write(&shim, b"shim").unwrap();
+ let paths = [PathAccess {
+ path: PathBuf::from("/bin"),
+ writable: false,
+ }];
+ let (sandbox_cmd, sandbox_args) = build_sandbox_exec_args(
+ &paths,
+ &UnixSocketAccess::default(),
+ &shim,
+ Some(&shims),
+ false,
+ None,
+ );
+ let allowed = home.path().join("allowed");
+ let run = |path: &Path| {
+ Command::new(&sandbox_cmd)
+ .args(&sandbox_args)
+ .args(["/bin/sh", "-c", "echo written > \"$1\"", "sh"])
+ .arg(path)
+ .output()
+ .unwrap()
+ };
+
+ let output = run(&allowed);
+ assert!(output.status.success(), "{:?}", output);
+ for blocked in [&shim, &shims.join("another-shim")] {
+ let output = run(blocked);
+ assert!(!output.status.success(), "write succeeded for {blocked:?}");
+ assert!(
+ String::from_utf8_lossy(&output.stderr).contains("Operation not permitted"),
+ "{output:?}"
+ );
+ }
+ assert_eq!(std::fs::read(&shim).unwrap(), b"shim");
+ assert!(!shims.join("another-shim").exists());
+ }
+
+ fn run_shim_write_probe(
+ shim: &Path,
+ cache: Option<&Path>,
+ script: &str,
+ path: &Path,
+ ) -> std::process::Output {
+ let paths = [
+ PathAccess {
+ path: PathBuf::from("/bin"),
+ writable: false,
+ },
+ PathAccess {
+ path: path.to_path_buf(),
+ writable: false,
+ },
+ ];
+ let (sandbox_cmd, sandbox_args) = build_sandbox_exec_args(
+ &paths,
+ &UnixSocketAccess::default(),
+ shim,
+ cache,
+ false,
+ None,
+ );
+ Command::new(sandbox_cmd)
+ .args(sandbox_args)
+ .args(["/bin/sh", "-c", script, "sh"])
+ .arg(path)
+ .output()
+ .unwrap()
+ }
+
+ fn assert_shim_write_denied(output: std::process::Output) {
+ assert!(!output.status.success(), "write succeeded: {output:?}");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Operation not permitted") && !stderr.contains("sandbox_apply"),
+ "expected a kernel file denial: {stderr}"
+ );
+ }
+
+ #[test]
+ fn test_seatbelt_runtime_denies_writes_to_symlinked_cache() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let home = tempfile::tempdir_in("/tmp").unwrap();
+ let target = tempfile::tempdir_in("/tmp").unwrap();
+ let cache = home.path().join("shims");
+ std::os::unix::fs::symlink(target.path(), &cache).unwrap();
+ let generation = target.path().join("0123456789abcdef");
+ std::fs::create_dir(&generation).unwrap();
+ let shim = generation.join("boxlite-shim");
+ std::fs::write(&shim, b"shim").unwrap();
+ let new_file = target.path().join("new-file");
+ assert_shim_write_denied(run_shim_write_probe(
+ &shim,
+ Some(&cache),
+ "printf changed > \"$1\"",
+ &new_file,
+ ));
+ std::fs::set_permissions(target.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
+ assert_shim_write_denied(run_shim_write_probe(
+ &shim,
+ Some(&cache),
+ "/bin/chmod 700 \"$1\"",
+ target.path(),
+ ));
+ let permissions = std::fs::metadata(target.path()).unwrap().permissions();
+ assert_eq!(permissions.mode() & 0o7777, 0o755);
+ assert_shim_write_denied(run_shim_write_probe(
+ &shim,
+ Some(&cache),
+ "/bin/rm \"$1\"",
+ &cache,
+ ));
+ assert!(
+ std::fs::symlink_metadata(&cache)
+ .unwrap()
+ .file_type()
+ .is_symlink()
+ );
+ assert!(!new_file.exists());
+ }
+
+ #[test]
+ fn test_seatbelt_runtime_fallback_shim_allows_sibling_writes() {
+ let home = tempfile::tempdir_in("/tmp").unwrap();
+ let shim = home.path().join("boxlite-shim");
+ let firmware = home.path().join("libkrunfw.dylib");
+ for path in [&shim, &firmware] {
+ std::fs::write(path, b"original").unwrap();
+ }
+ let sibling = home.path().join("writable");
+ let script = "printf changed > \"$1\"";
+
+ let output = run_shim_write_probe(&shim, None, script, &sibling);
+ assert!(output.status.success(), "sibling write failed: {output:?}");
+ assert_eq!(std::fs::read(sibling).unwrap(), b"changed");
+ for path in [&shim, &firmware] {
+ assert_shim_write_denied(run_shim_write_probe(&shim, None, script, path));
+ assert_eq!(std::fs::read(path).unwrap(), b"original");
+ }
+ }
+
+ #[test]
+ fn test_seatbelt_runtime_denies_firmware_overwrite_in_unreadable_shim_directory() {
+ if !is_sandbox_available() {
+ eprintln!("Skipping: sandbox-exec not available");
+ return;
+ }
+ let Some(dir) = unreadable_shim_dir() else {
+ return;
+ };
+ let shim = dir.0.path().join("boxlite-shim");
+ let firmware = dir.0.path().join("libkrunfw.dylib");
+ assert_shim_write_denied(run_shim_write_probe(
+ &shim,
+ None,
+ "printf changed > \"$1\"",
+ &firmware,
+ ));
+ assert_eq!(std::fs::read(&firmware).unwrap(), b"original");
+ }
+
#[cfg(target_os = "macos")]
#[test]
fn test_seatbelt_runtime_denies_write_outside_writable_path() {
@@ -1601,6 +2059,7 @@ mod tests {
paths,
unix_sockets,
Path::new(PROBE_BIN),
+ None,
network_enabled,
None,
);
@@ -1768,4 +2227,89 @@ mod tests {
}
}
}
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn test_seatbelt_runtime_fallback_symlinked_runtime_execs_and_denies_sibling() {
+ use crate::jailer::Jail;
+ use crate::jailer::builder::JailerBuilder;
+ use crate::runtime::layout::{BoxFilesystemLayout, FsLayoutConfig};
+ use std::os::unix::fs::{PermissionsExt, symlink};
+
+ if !is_sandbox_available() {
+ eprintln!("Skipping: sandbox-exec not available");
+ return;
+ }
+
+ let root = tempfile::tempdir_in("/tmp").expect("tempdir in /tmp");
+ let target_dir = root.path().join("target/debug");
+ let runtime_dir = target_dir.join("runtime");
+ let build_out = target_dir.join("build/boxlite-hash/out/runtime");
+ std::fs::create_dir_all(&runtime_dir).unwrap();
+ std::fs::create_dir_all(&build_out).unwrap();
+
+ let real_shim = target_dir.join("boxlite-shim");
+ std::fs::write(
+ &real_shim,
+ "#!/bin/sh\nif [ \"$#\" -gt 0 ]; then\n /bin/cat \"$1\"\nelse\n /bin/cat \"${0%/*}/libkrunfw.5.dylib\"\nfi\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&real_shim, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let real_fw = build_out.join("libkrunfw.5.dylib");
+ std::fs::write(&real_fw, b"libkrunfw-fallback-ok\n").unwrap();
+
+ let sibling = target_dir.join("sibling.txt");
+ std::fs::write(&sibling, b"forbidden-sibling\n").unwrap();
+
+ let runtime_shim = runtime_dir.join("boxlite-shim");
+ let runtime_fw = runtime_dir.join("libkrunfw.5.dylib");
+ symlink("../boxlite-shim", &runtime_shim).unwrap();
+ symlink(
+ "../build/boxlite-hash/out/runtime/libkrunfw.5.dylib",
+ &runtime_fw,
+ )
+ .unwrap();
+
+ let layout = BoxFilesystemLayout::new(
+ root.path().join("boxes/test-box"),
+ FsLayoutConfig::without_bind_mount(),
+ false,
+ );
+ let jail = JailerBuilder::new()
+ .with_box_id("seatbelt-fallback-symlink")
+ .with_layout(layout)
+ .with_shim_cache_dir(&runtime_shim)
+ .with_additional_path_access(vec![PathAccess {
+ path: PathBuf::from("/bin"),
+ writable: false,
+ }])
+ .with_jailer_enabled(true)
+ .build_with(SeatbeltSandbox::new())
+ .unwrap();
+
+ let mut ok_cmd = jail.command(&runtime_shim, &[]);
+ let ok_out = ok_cmd.output().expect("run sandboxed symlinked shim");
+ assert!(
+ ok_out.status.success(),
+ "fallback symlinked runtime/ shim + libkrunfw.5.dylib must execute/read in Seatbelt: stderr={}",
+ String::from_utf8_lossy(&ok_out.stderr)
+ );
+ assert_eq!(ok_out.stdout, b"libkrunfw-fallback-ok\n");
+
+ let mut deny_cmd = jail.command(&runtime_shim, &[sibling.to_string_lossy().into_owned()]);
+ let deny_out = deny_cmd
+ .output()
+ .expect("run sandboxed shim against sibling");
+ assert!(
+ !deny_out.status.success(),
+ "reading ../sibling.txt must be denied by Seatbelt"
+ );
+ assert!(
+ String::from_utf8_lossy(&deny_out.stderr).contains("Operation not permitted"),
+ "expected Seatbelt denial for ../sibling.txt, got: {}",
+ String::from_utf8_lossy(&deny_out.stderr)
+ );
+ assert!(deny_out.stdout.is_empty());
+ }
}
diff --git a/src/boxlite/src/jailer/shim_cache.rs b/src/boxlite/src/jailer/shim_cache.rs
new file mode 100644
index 000000000..ebfe54ee0
--- /dev/null
+++ b/src/boxlite/src/jailer/shim_cache.rs
@@ -0,0 +1,933 @@
+//! Content-addressed shim and firmware shared by jailed boxes in one runtime home.
+
+use boxlite_shared::errors::{BoxliteError, BoxliteResult};
+use filetime::FileTime;
+use parking_lot::Mutex;
+use sha2::{Digest, Sha256};
+use std::collections::HashMap;
+use std::ffi::{OsStr, OsString};
+use std::fs::{self, Metadata};
+use std::io::{self, Read};
+#[cfg(unix)]
+use std::os::unix::fs::{MetadataExt, PermissionsExt};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, OnceLock};
+use std::time::{Duration, SystemTime};
+
+/// Hidden completion marker written after all generation files are copied.
+const STAMP: &str = ".complete";
+/// Hidden namespace for temporary directories outside the published digest names.
+const STAGING_PREFIX: &str = ".staging.";
+/// Give in-progress staging an hour before treating its directory as abandoned.
+const STAGING_ORPHAN_TTL: Duration = Duration::from_secs(60 * 60);
+/// Retire idle debug generations after an hour to limit buildup from rebuilds.
+const STALE_TTL_DEBUG: Duration = Duration::from_secs(60 * 60);
+/// Keep idle release generations for a week so intermittent runs can reuse them.
+const STALE_TTL_RELEASE: Duration = Duration::from_secs(7 * 24 * 60 * 60);
+/// Skip memoization within two seconds of a source change to account for coarse timestamps.
+const RACY_STAT_WINDOW: Duration = Duration::from_secs(2);
+/// Record whether debug assertions are enabled so cleanup can pick the retention period.
+const BUILD_PROFILE: &str = if cfg!(debug_assertions) {
+ "debug"
+} else {
+ "release"
+};
+/// Use a 64-bit SHA-256 prefix to keep generation directory names short.
+const DIGEST_BYTES: usize = 8;
+/// A generation name has two hexadecimal digits per digest byte.
+const DIGEST_HEX_LEN: usize = DIGEST_BYTES * 2;
+/// Hash file contents in 64 KiB chunks to amortize reads.
+const HASH_BUFFER_BYTES: usize = 64 * 1024;
+/// Let everyone traverse staged directories and execute shims, with writes limited to the owner.
+#[cfg(unix)]
+const EXECUTABLE_MODE: u32 = 0o755;
+/// Let everyone read firmware, with writes limited to the owner and no execute bits.
+#[cfg(unix)]
+const FIRMWARE_MODE: u32 = 0o644;
+/// Synthetic read-only directory inside Bubblewrap for symlinked runtime layouts.
+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
+pub(crate) const BWRAP_SANDBOX_SHIM_DIR: &str = "/run/boxlite-shim";
+
+static SEQUENCE: AtomicU64 = AtomicU64::new(0);
+static MEMO: OnceLock<Mutex<HashMap<PathBuf, Arc<MemoEntry>>>> = OnceLock::new();
+static LIFECYCLE_LOCK: Mutex<()> = Mutex::new(());
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct ResolvedRuntimeFile {
+ pub(crate) canonical_source: PathBuf,
+ pub(crate) logical_name: OsString,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub(crate) struct ResolvedRuntimeFiles {
+ pub(crate) files: Vec<ResolvedRuntimeFile>,
+ #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
+ pub(crate) has_symlink: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
+pub(crate) struct BwrapShimMountPlan {
+ pub(crate) ro_binds: Vec<(PathBuf, PathBuf)>,
+ pub(crate) executable: PathBuf,
+ pub(crate) ld_library_path: String,
+}
+
+fn shim_parent_dir(shim: &Path) -> &Path {
+ shim.parent()
+ .filter(|p| !p.as_os_str().is_empty())
+ .unwrap_or(Path::new("."))
+}
+
+fn is_firmware_filename(filename: &OsStr, binary_name: &OsStr) -> bool {
+ filename != binary_name && filename.as_encoded_bytes().starts_with(b"libkrunfw.")
+}
+
+/// Resolve `binary` and adjacent `libkrunfw.*` files in its directory.
+///
+/// Tracks each entry's canonical file path alongside its logical filename in
+/// `binary`'s directory, plus whether `binary` or any `libkrunfw.*` entry is a
+/// symlink. Non-existent or non-file binaries return an empty result.
+pub(crate) fn resolve_runtime_files(binary: &Path) -> ResolvedRuntimeFiles {
+ let Some(binary_name) = binary.file_name().filter(|name| !name.is_empty()) else {
+ return ResolvedRuntimeFiles::default();
+ };
+ let dir = shim_parent_dir(binary);
+
+ let Ok(link_meta) = fs::symlink_metadata(binary) else {
+ return ResolvedRuntimeFiles::default();
+ };
+ let Ok(meta) = fs::metadata(binary) else {
+ return ResolvedRuntimeFiles::default();
+ };
+ if !meta.is_file() {
+ return ResolvedRuntimeFiles::default();
+ }
+
+ let mut has_symlink = link_meta.file_type().is_symlink();
+ let canonical_binary = binary
+ .canonicalize()
+ .unwrap_or_else(|_| binary.to_path_buf());
+ let mut files = vec![ResolvedRuntimeFile {
+ canonical_source: canonical_binary,
+ logical_name: binary_name.to_os_string(),
+ }];
+
+ if let Ok(entries) = fs::read_dir(dir) {
+ for entry in entries.flatten() {
+ let filename = entry.file_name();
+ if !is_firmware_filename(&filename, binary_name) {
+ continue;
+ }
+ let entry_path = entry.path();
+ if fs::metadata(&entry_path).is_ok_and(|m| m.is_file()) {
+ if fs::symlink_metadata(&entry_path).is_ok_and(|lm| lm.file_type().is_symlink()) {
+ has_symlink = true;
+ }
+ let canonical = entry_path.canonicalize().unwrap_or(entry_path);
+ files.push(ResolvedRuntimeFile {
+ canonical_source: canonical,
+ logical_name: filename,
+ });
+ }
+ }
+ }
+
+ files.sort_unstable_by(|a, b| a.logical_name.cmp(&b.logical_name));
+ ResolvedRuntimeFiles { files, has_symlink }
+}
+
+/// Plan Bubblewrap read-only mounts, executable path, and `LD_LIBRARY_PATH` for `binary`.
+///
+/// When `binary` or any adjacent `libkrunfw.*` entry is a symlink (e.g., an
+/// unstaged `target/<profile>/runtime/` fallback), resolved targets are mapped
+/// into [`BWRAP_SANDBOX_SHIM_DIR`] so relative symlinks do not dangle or
+/// collide with directory mounts inside the mount namespace. Normal staged
+/// directories keep their direct paths with no extra mounts.
+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
+pub(crate) fn plan_bwrap_shim_mounts(binary: &Path) -> BwrapShimMountPlan {
+ let shim_dir = binary
+ .parent()
+ .filter(|p| !p.as_os_str().is_empty())
+ .map(|dir| dir.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ let resolved = resolve_runtime_files(binary);
+ if resolved.has_symlink
+ && let Some(binary_name) = binary.file_name().filter(|name| !name.is_empty())
+ {
+ let sandbox_dir = Path::new(BWRAP_SANDBOX_SHIM_DIR);
+ let ro_binds = resolved
+ .files
+ .into_iter()
+ .map(|file| (file.canonical_source, sandbox_dir.join(file.logical_name)))
+ .collect();
+ let ld_library_path = if shim_dir.is_empty() {
+ BWRAP_SANDBOX_SHIM_DIR.to_string()
+ } else {
+ format!("{BWRAP_SANDBOX_SHIM_DIR}:{shim_dir}")
+ };
+ return BwrapShimMountPlan {
+ ro_binds,
+ executable: sandbox_dir.join(binary_name),
+ ld_library_path,
+ };
+ }
+
+ BwrapShimMountPlan {
+ ro_binds: Vec::new(),
+ executable: binary.to_path_buf(),
+ ld_library_path: shim_dir,
+ }
+}
+
+#[derive(Clone, PartialEq, Eq)]
+struct FileFingerprint {
+ name: OsString,
+ len: u64,
+ mtime: FileTime,
+ #[cfg(unix)]
+ inode: (u64, u64),
+ #[cfg(unix)]
+ ctime: FileTime,
+}
+
+impl FileFingerprint {
+ fn new(name: OsString, metadata: &Metadata) -> Self {
+ Self {
+ name,
+ len: metadata.len(),
+ mtime: FileTime::from_last_modification_time(metadata),
+ #[cfg(unix)]
+ inode: (metadata.dev(), metadata.ino()),
+ #[cfg(unix)]
+ ctime: FileTime::from_unix_time(metadata.ctime(), metadata.ctime_nsec() as u32),
+ }
+ }
+
+ fn older_than(&self, cutoff: FileTime) -> bool {
+ #[cfg(unix)]
+ if self.ctime >= cutoff {
+ return false;
+ }
+ self.mtime < cutoff
+ }
+
+ fn check_metadata(&self, path: &Path, metadata: &Metadata) -> io::Result<()> {
+ if *self == Self::new(self.name.clone(), metadata) {
+ return Ok(());
+ }
+ Err(io::Error::other(format!(
+ "source changed: {}",
+ path.display()
+ )))
+ }
+}
+
+struct MemoEntry {
+ fingerprints: Vec<FileFingerprint>,
+ digest: String,
+}
+
+fn collect_sources(shim: &Path, dir: &Path, name: &OsStr) -> io::Result<Vec<FileFingerprint>> {
+ let metadata = fs::metadata(shim)?;
+ if !metadata.is_file() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "shim must be a file",
+ ));
+ }
+ let mut files = vec![FileFingerprint::new(name.to_os_string(), &metadata)];
+ for entry in fs::read_dir(dir)? {
+ let entry = entry?;
+ let filename = entry.file_name();
+ if !is_firmware_filename(&filename, name) {
+ continue;
+ }
+ match fs::metadata(entry.path()) {
+ Ok(metadata) if metadata.is_file() => {
+ files.push(FileFingerprint::new(filename, &metadata));
+ }
+ Ok(_) => {}
+ Err(err) if err.kind() == io::ErrorKind::NotFound => {}
+ Err(err) => return Err(err),
+ }
+ }
+ files.sort_unstable_by(|a, b| a.name.cmp(&b.name));
+ Ok(files)
+}
+
+fn digest_at(
+ shim: &Path,
+ dir: &Path,
+ files: &[FileFingerprint],
+ now: SystemTime,
+) -> io::Result<String> {
+ let key = shim.canonicalize().unwrap_or_else(|_| shim.to_path_buf());
+ let memo = MEMO.get_or_init(|| Mutex::new(HashMap::new()));
+ let cached = memo.lock().get(&key).cloned();
+ if let Some(entry) = cached
+ && entry.fingerprints == files
+ {
+ return Ok(entry.digest.clone());
+ }
+
+ let mut hash = Sha256::new();
+ let mut buffer = [0; HASH_BUFFER_BYTES];
+ for source in files {
+ let name = source.name.as_encoded_bytes();
+ hash.update((name.len() as u64).to_le_bytes());
+ hash.update(name);
+ hash.update(source.len.to_le_bytes());
+ let path = dir.join(&source.name);
+ let mut file = fs::File::open(&path)?;
+ loop {
+ let len = file.read(&mut buffer)?;
+ if len == 0 {
+ break;
+ }
+ hash.update(&buffer[..len]);
+ }
+ source.check_metadata(&path, &file.metadata()?)?;
+ }
+ let digest = hex::encode(&hash.finalize()[..DIGEST_BYTES]);
+ // Coarse file timestamps can alias writes made close to the hash read.
+ let cutoff = FileTime::from_system_time(now - RACY_STAT_WINDOW);
+ if files.iter().all(|f| f.older_than(cutoff)) {
+ let entry = Arc::new(MemoEntry {
+ fingerprints: files.to_vec(),
+ digest: digest.clone(),
+ });
+ let _previous = memo.lock().insert(key, entry);
+ }
+ Ok(digest)
+}
+
+fn is_complete(target: &Path, files: &[FileFingerprint]) -> bool {
+ target.join(STAMP).is_file()
+ && files.iter().all(|file| {
+ fs::metadata(target.join(&file.name))
+ .is_ok_and(|metadata| metadata.is_file() && metadata.len() == file.len)
+ })
+}
+
+struct StagingGuard {
+ path: PathBuf,
+ published: bool,
+}
+
+impl StagingGuard {
+ fn publish(mut self, target: &Path, files: &[FileFingerprint]) -> io::Result<bool> {
+ let result = fs::rename(&self.path, target);
+ let _lock = LIFECYCLE_LOCK.lock();
+ match result {
+ Ok(()) => self.published = true,
+ Err(_) if is_complete(target, files) => {}
+ Err(err) => return Err(err),
+ }
+ let _ = filetime::set_file_mtime(target.join(STAMP), FileTime::now());
+ Ok(self.published)
+ }
+}
+
+impl Drop for StagingGuard {
+ fn drop(&mut self) {
+ if !self.published {
+ let _ = fs::remove_dir_all(&self.path);
+ }
+ }
+}
+
+pub(crate) fn stage_shim(shim_path: &Path, cache_dir: &Path) -> BoxliteResult<PathBuf> {
+ stage(shim_path, cache_dir).map_err(|err| {
+ BoxliteError::Storage(format!(
+ "failed to stage shim {} in {}: {err}",
+ shim_path.display(),
+ cache_dir.display(),
+ ))
+ })
+}
+
+fn stage(shim_path: &Path, cache_dir: &Path) -> io::Result<PathBuf> {
+ let name = shim_path
+ .file_name()
+ .filter(|name| !name.is_empty() && *name != STAMP)
+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid shim filename"))?;
+ let dir = shim_parent_dir(shim_path);
+ let files = collect_sources(shim_path, dir, name)?;
+ let digest = digest_at(shim_path, dir, &files, SystemTime::now())?;
+ let target = cache_dir.join(&digest);
+
+ let hit = {
+ let _lock = LIFECYCLE_LOCK.lock();
+ let complete = is_complete(&target, &files);
+ if complete {
+ let _ = filetime::set_file_mtime(target.join(STAMP), FileTime::now());
+ }
+ complete
+ };
+ if !hit {
+ fs::create_dir_all(cache_dir)?;
+ let seq = SEQUENCE.fetch_add(1, Ordering::Relaxed);
+ let path = cache_dir.join(format!(
+ "{STAGING_PREFIX}{digest}.{}.{seq}",
+ std::process::id()
+ ));
+ fs::create_dir(&path)?;
+ let staging = StagingGuard {
+ path,
+ published: false,
+ };
+ #[cfg(unix)]
+ fs::set_permissions(&staging.path, fs::Permissions::from_mode(EXECUTABLE_MODE))?;
+
+ for source in &files {
+ let path = dir.join(&source.name);
+ let destination = staging.path.join(&source.name);
+ fs::copy(&path, &destination)?;
+ let metadata = fs::metadata(&path)?;
+ source.check_metadata(&path, &metadata)?;
+ #[cfg(unix)]
+ {
+ let mode = if source.name == name {
+ EXECUTABLE_MODE
+ } else {
+ FIRMWARE_MODE
+ };
+ fs::set_permissions(&destination, fs::Permissions::from_mode(mode))?;
+ }
+ }
+ fs::write(
+ staging.path.join(STAMP),
+ format!("{}\n{BUILD_PROFILE}\n", crate::VERSION),
+ )?;
+ if staging.publish(&target, &files)? {
+ tracing::info!(path = %target.display(), "Published shared shim");
+ cleanup_stale(cache_dir, Some(&target));
+ }
+ }
+ Ok(target.canonicalize().unwrap_or(target).join(name))
+}
+
+fn published_metadata(path: &Path) -> io::Result<Metadata> {
+ fs::metadata(path.join(STAMP)).or_else(|_| fs::metadata(path))
+}
+
+fn is_expired(metadata: io::Result<Metadata>, now: SystemTime, ttl: Duration) -> bool {
+ metadata
+ .and_then(|metadata| metadata.modified())
+ .is_ok_and(|time| now.duration_since(time).is_ok_and(|age| age > ttl))
+}
+
+fn retire_if_stale(
+ path: &Path,
+ reap_dir: &Path,
+ now: SystemTime,
+ ttl: Duration,
+) -> io::Result<bool> {
+ let _lock = LIFECYCLE_LOCK.lock();
+ if !is_expired(published_metadata(path), now, ttl) {
+ return Ok(false);
+ }
+ fs::rename(path, reap_dir)?;
+ Ok(true)
+}
+
+pub(crate) fn cleanup_stale(cache_dir: &Path, active_dir: Option<&Path>) {
+ let Ok(entries) = fs::read_dir(cache_dir) else {
+ return;
+ };
+ let active_canonical = active_dir.and_then(|path| path.canonicalize().ok());
+ let now = SystemTime::now();
+ for entry in entries
+ .flatten()
+ .filter(|entry| entry.file_type().is_ok_and(|ty| ty.is_dir()))
+ {
+ let path = entry.path();
+ let name = entry.file_name();
+ let name = name.as_encoded_bytes();
+ if name.starts_with(STAGING_PREFIX.as_bytes()) {
+ if is_expired(entry.metadata(), now, STAGING_ORPHAN_TTL) {
+ let _ = fs::remove_dir_all(&path);
+ }
+ continue;
+ }
+ if name.len() != DIGEST_HEX_LEN
+ || !name.iter().all(|&b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
+ {
+ continue;
+ }
+ if active_dir == Some(path.as_path())
+ || active_canonical
+ .as_ref()
+ .is_some_and(|active| path.canonicalize().is_ok_and(|p| p == *active))
+ {
+ continue;
+ }
+ let profile = fs::read_to_string(path.join(STAMP)).unwrap_or_default();
+ let ttl = match profile.lines().nth(1) {
+ Some("debug") => STALE_TTL_DEBUG,
+ _ => STALE_TTL_RELEASE,
+ };
+ if !is_expired(published_metadata(&path), now, ttl) {
+ continue;
+ }
+
+ // Move the digest out of the cache namespace before deleting its contents.
+ let seq = SEQUENCE.fetch_add(1, Ordering::Relaxed);
+ let reap_dir = cache_dir.join(format!("{STAGING_PREFIX}reap.{}.{seq}", std::process::id()));
+ match retire_if_stale(&path, &reap_dir, now, ttl) {
+ Ok(true) => {
+ let _ = fs::remove_dir_all(&reap_dir);
+ }
+ Ok(false) => {}
+ Err(err) if err.kind() == io::ErrorKind::NotFound => {}
+ Err(err) => {
+ tracing::warn!(path = %path.display(), error = %err, "Failed to retire shared shim directory")
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use filetime::set_file_mtime;
+ use tempfile::{TempDir, tempdir};
+
+ fn fixture() -> (TempDir, PathBuf, PathBuf) {
+ let root = tempdir().unwrap();
+ let source = root.path().join("source");
+ fs::create_dir(&source).unwrap();
+ let shim = source.join("boxlite-shim");
+ fs::write(&shim, b"shim").unwrap();
+ let cache = root.path().join("shims");
+ (root, shim, cache)
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn stage_shim_copies_shim_and_libkrunfw_with_permissions() {
+ let (_root, shim, cache) = fixture();
+ let firmware = shim.with_file_name("libkrunfw.so.5");
+ fs::write(&firmware, b"firmware").unwrap();
+ fs::set_permissions(&shim, fs::Permissions::from_mode(0o600)).unwrap();
+ fs::set_permissions(&firmware, fs::Permissions::from_mode(0o600)).unwrap();
+ fs::create_dir(shim.with_file_name("libkrunfw.directory")).unwrap();
+ fs::write(shim.with_file_name("libkrun.so"), b"other").unwrap();
+
+ let staged = stage_shim(&shim, &cache).unwrap();
+ let dir = staged.parent().unwrap();
+ assert_eq!(dir.file_name().unwrap(), "25003b18fa290e6b");
+ let library = dir.join(firmware.file_name().unwrap());
+ assert_eq!(fs::read(&staged).unwrap(), b"shim");
+ assert_eq!(fs::read(&library).unwrap(), b"firmware");
+ assert_eq!(fs::metadata(dir).unwrap().mode() & 0o777, 0o755);
+ assert_eq!(fs::metadata(&staged).unwrap().mode() & 0o777, 0o755);
+ assert_eq!(fs::metadata(library).unwrap().mode() & 0o777, 0o644);
+ assert_eq!(fs::read_dir(dir).unwrap().count(), 3);
+ let stamp = fs::read_to_string(dir.join(STAMP)).unwrap();
+ assert_eq!(stamp, format!("{}\n{BUILD_PROFILE}\n", crate::VERSION));
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn stage_shim_normalizes_writable_source_permissions() {
+ let (_root, shim, cache) = fixture();
+ let firmware = shim.with_file_name("libkrunfw.so.5");
+ fs::write(&firmware, b"firmware").unwrap();
+ for path in [&shim, &firmware] {
+ fs::set_permissions(path, fs::Permissions::from_mode(0o777)).unwrap();
+ }
+ let staged = stage_shim(&shim, &cache).unwrap();
+ assert_eq!(fs::metadata(&staged).unwrap().mode() & 0o777, 0o755);
+ let library = staged.with_file_name(firmware.file_name().unwrap());
+ assert_eq!(fs::metadata(library).unwrap().mode() & 0o777, 0o644);
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn stage_shim_reuses_same_inode_without_recopy() {
+ let (_root, shim, cache) = fixture();
+ let staged = stage_shim(&shim, &cache).unwrap();
+ let inode = fs::metadata(&staged).unwrap().ino();
+ let stamp = staged.with_file_name(STAMP);
+ let old = FileTime::from_unix_time(1, 0);
+ set_file_mtime(&stamp, old).unwrap();
+
+ assert_eq!(stage_shim(&shim, &cache).unwrap(), staged);
+ assert_eq!(fs::metadata(staged).unwrap().ino(), inode);
+ assert!(FileTime::from_last_modification_time(&fs::metadata(stamp).unwrap()) > old);
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn stage_shim_follows_symlinked_sources() {
+ use std::os::unix::fs::symlink;
+
+ let (root, shim, cache) = fixture();
+ let real_shim = root.path().join("installed-shim");
+ fs::rename(&shim, &real_shim).unwrap();
+ symlink(real_shim, &shim).unwrap();
+ let firmware = root.path().join("installed-firmware");
+ fs::write(&firmware, b"firmware").unwrap();
+ symlink(firmware, shim.with_file_name("libkrunfw.dylib")).unwrap();
+ symlink("missing", shim.with_file_name("libkrunfw.broken")).unwrap();
+
+ let staged = stage_shim(&shim, &cache).unwrap();
+ let library = staged.with_file_name("libkrunfw.dylib");
+ for (path, contents) in [(&staged, &b"shim"[..]), (&library, &b"firmware"[..])] {
+ assert!(fs::symlink_metadata(path).unwrap().is_file());
+ assert_eq!(fs::read(path).unwrap(), contents);
+ }
+ assert!(!staged.with_file_name("libkrunfw.broken").exists());
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn stage_shim_rejects_firmware_symlink_loop() {
+ let (_root, shim, cache) = fixture();
+ let firmware = shim.with_file_name("libkrunfw.loop");
+ std::os::unix::fs::symlink("libkrunfw.loop", &firmware).unwrap();
+ let expected = io::Error::from_raw_os_error(libc::ELOOP).to_string();
+
+ let err = stage_shim(&shim, &cache).expect_err("firmware metadata error must fail staging");
+ assert!(err.to_string().contains(&expected), "{err}");
+ }
+
+ #[test]
+ fn stage_shim_content_change_creates_new_digest_dir() {
+ let (_root, shim, cache) = fixture();
+ let firmware = shim.with_file_name("libkrunfw.so.5");
+ fs::write(&firmware, b"firmware v1").unwrap();
+ let first = stage_shim(&shim, &cache).unwrap();
+ let mtime = FileTime::from_last_modification_time(&fs::metadata(&firmware).unwrap());
+ fs::write(&firmware, b"firmware v2").unwrap();
+ set_file_mtime(&firmware, mtime).unwrap();
+ let second = stage_shim(&shim, &cache).unwrap();
+ fs::write(&shim, b"shim v2").unwrap();
+ let third = stage_shim(&shim, &cache).unwrap();
+
+ assert_ne!(first.parent(), second.parent());
+ assert_ne!(second.parent(), third.parent());
+ assert_eq!(
+ fs::read(first.with_file_name("libkrunfw.so.5")).unwrap(),
+ b"firmware v1"
+ );
+ assert_eq!(
+ fs::read(second.with_file_name("libkrunfw.so.5")).unwrap(),
+ b"firmware v2"
+ );
+ assert_eq!(fs::read(third).unwrap(), b"shim v2");
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn digest_memo_reuses_entry_until_source_changes() {
+ let (_root, shim, _cache) = fixture();
+ let dir = shim.parent().unwrap();
+ let name = shim.file_name().unwrap();
+ let key = shim.canonicalize().unwrap();
+ let files = collect_sources(&shim, dir, name).unwrap();
+ let now = SystemTime::now() + 2 * RACY_STAT_WINDOW;
+ let first = digest_at(&shim, dir, &files, now).unwrap();
+ let memo = MEMO.get().unwrap();
+ let entry = || memo.lock().get(&key).cloned().unwrap();
+ let first_entry = entry();
+ assert_eq!(first_entry.digest, first);
+
+ assert_eq!(digest_at(&shim, dir, &files, now).unwrap(), first);
+ assert!(Arc::ptr_eq(&first_entry, &entry()));
+
+ let mtime = files[0].mtime;
+ let prev_inode = files[0].inode;
+ // Replace atomically via rename so the inode changes deterministically even
+ // when coarse ctime ticks would otherwise leave the metadata fingerprint equal.
+ let replacement = dir.join("boxlite-shim.new");
+ fs::write(&replacement, b"edit").unwrap();
+ set_file_mtime(&replacement, mtime).unwrap();
+ fs::rename(&replacement, &shim).unwrap();
+ let files = collect_sources(&shim, dir, name).unwrap();
+ assert_eq!(files[0].mtime, mtime);
+ assert_ne!(files[0].inode, prev_inode);
+ let now = SystemTime::now() + 2 * RACY_STAT_WINDOW;
+ let updated = digest_at(&shim, dir, &files, now).unwrap();
+ assert_ne!(updated, first);
+ assert_eq!(entry().digest, updated);
+ }
+
+ #[test]
+ fn digest_memo_skips_sources_inside_racy_window() {
+ let (_root, shim, _cache) = fixture();
+ let dir = shim.parent().unwrap();
+ let name = shim.file_name().unwrap();
+ let key = shim.canonicalize().unwrap();
+ let now = SystemTime::now();
+ set_file_mtime(&shim, FileTime::from_system_time(now)).unwrap();
+ let files = collect_sources(&shim, dir, name).unwrap();
+ digest_at(&shim, dir, &files, now + RACY_STAT_WINDOW / 2).unwrap();
+ assert!(!MEMO.get().unwrap().lock().contains_key(&key));
+ }
+
+ #[test]
+ fn stage_shim_concurrent_threads_atomic_publish() {
+ let (_root, shim, cache) = fixture();
+ let barrier = std::sync::Barrier::new(8);
+ std::thread::scope(|scope| {
+ let threads: Vec<_> = (0..8)
+ .map(|_| {
+ scope.spawn(|| {
+ barrier.wait();
+ let staged = stage_shim(&shim, &cache).unwrap();
+ assert_eq!(fs::read(&staged).unwrap(), b"shim");
+ assert!(staged.with_file_name(STAMP).is_file());
+ staged
+ })
+ })
+ .collect();
+ let paths: Vec<_> = threads
+ .into_iter()
+ .map(|thread| thread.join().unwrap())
+ .collect();
+ assert!(paths.iter().all(|path| path == &paths[0]));
+ });
+ assert_eq!(fs::read_dir(cache).unwrap().count(), 1);
+ }
+
+ #[test]
+ fn stage_shim_race_loser_cleans_up_staging_dir() {
+ let (_root, shim, cache) = fixture();
+ let winner = stage_shim(&shim, &cache).unwrap();
+ let staging = cache.join(".staging.loser");
+ fs::create_dir(&staging).unwrap();
+ fs::write(staging.join("unused"), b"race loser").unwrap();
+
+ let guard = StagingGuard {
+ path: staging.clone(),
+ published: false,
+ };
+ let files =
+ collect_sources(&shim, shim.parent().unwrap(), shim.file_name().unwrap()).unwrap();
+ assert!(!guard.publish(winner.parent().unwrap(), &files).unwrap());
+ assert!(!staging.exists());
+ assert_eq!(fs::read(winner).unwrap(), b"shim");
+ }
+
+ #[test]
+ fn cleanup_stale_respects_ttl_and_protects_active_dir() {
+ let (root, shim, cache) = fixture();
+ let active = stage_shim(&shim, &cache).unwrap();
+ let active_dir = active.parent().unwrap();
+ let now = SystemTime::now();
+ let ago = |duration| FileTime::from_system_time(now - duration);
+ let past_debug = STALE_TTL_DEBUG + Duration::from_secs(60);
+ let past_release = STALE_TTL_RELEASE + Duration::from_secs(60);
+ set_file_mtime(active.with_file_name(STAMP), ago(past_release)).unwrap();
+ for (name, profile, age) in [
+ ("0000000000000001", Some("debug"), past_debug),
+ ("0000000000000002", Some("debug"), Duration::ZERO),
+ ("0000000000000003", Some("release"), past_release),
+ ("0000000000000004", Some("release"), past_debug),
+ ("0000000000000005", None, past_release),
+ ("0000000000000006", None, past_debug),
+ ("local", None, past_release),
+ (
+ ".staging.expired",
+ None,
+ STAGING_ORPHAN_TTL + Duration::from_secs(60),
+ ),
+ (".staging.fresh", None, Duration::ZERO),
+ ] {
+ let path = cache.join(name);
+ fs::create_dir(&path).unwrap();
+ let clock_path = if let Some(profile) = profile {
+ let stamp = path.join(STAMP);
+ fs::write(&stamp, format!("version\n{profile}\n")).unwrap();
+ stamp
+ } else {
+ path
+ };
+ set_file_mtime(clock_path, ago(age)).unwrap();
+ }
+
+ let cache_alias = root.path().join("source/../shims");
+ cleanup_stale(&cache_alias, Some(active_dir));
+ assert!(active.is_file());
+ for (name, kept) in [
+ ("0000000000000001", false),
+ ("0000000000000002", true),
+ ("0000000000000003", false),
+ ("0000000000000004", true),
+ ("0000000000000005", false),
+ ("0000000000000006", true),
+ ("local", true),
+ (".staging.expired", false),
+ (".staging.fresh", true),
+ ] {
+ assert_eq!(cache.join(name).exists(), kept, "{name}");
+ }
+ cleanup_stale(&cache, None);
+ assert!(!active_dir.exists());
+ }
+
+ #[test]
+ fn cleanup_stale_keeps_shim_renewed_after_expiry_check() {
+ let (_root, shim, cache) = fixture();
+ let staged = stage_shim(&shim, &cache).unwrap();
+ let generation = staged.parent().unwrap();
+ set_file_mtime(staged.with_file_name(STAMP), FileTime::from_unix_time(1, 0)).unwrap();
+ let now = SystemTime::now();
+ assert!(is_expired(
+ published_metadata(generation),
+ now,
+ STALE_TTL_RELEASE
+ ));
+
+ let hit = stage_shim(&shim, &cache).unwrap();
+ assert_eq!(hit, staged);
+ let reap_dir = cache.join(".staging.reap");
+ assert!(!retire_if_stale(generation, &reap_dir, now, STALE_TTL_RELEASE).unwrap());
+ assert_eq!(fs::read(hit).unwrap(), b"shim");
+ }
+
+ #[test]
+ fn stage_shim_missing_source_returns_storage_error() {
+ let (_root, shim, cache) = fixture();
+ assert!(matches!(
+ stage_shim(&shim.with_file_name("missing"), &cache),
+ Err(BoxliteError::Storage(_))
+ ));
+ assert!(!cache.exists());
+ }
+
+ #[test]
+ fn stage_shim_directory_source_returns_storage_error() {
+ let (_root, shim, cache) = fixture();
+ assert!(matches!(
+ stage_shim(shim.parent().unwrap(), &cache),
+ Err(BoxliteError::Storage(_))
+ ));
+ assert!(!cache.exists());
+ }
+
+ #[test]
+ fn stage_shim_incomplete_target_returns_error_without_refreshing_stamp() {
+ let (_root, shim, cache) = fixture();
+ let staged = stage_shim(&shim, &cache).unwrap();
+ fs::remove_file(&staged).unwrap();
+ let stamp = staged.with_file_name(STAMP);
+ let old = FileTime::from_unix_time(1, 0);
+ set_file_mtime(&stamp, old).unwrap();
+
+ let result = stage_shim(&shim, &cache);
+
+ assert!(
+ matches!(result, Err(BoxliteError::Storage(_))),
+ "{result:?}"
+ );
+ assert_eq!(
+ FileTime::from_last_modification_time(&fs::metadata(stamp).unwrap()),
+ old
+ );
+ assert!(!staged.exists());
+ assert_eq!(fs::read_dir(cache).unwrap().count(), 1);
+ }
+
+ #[test]
+ fn stage_shim_rejects_missing_or_truncated_firmware_without_refreshing_stamp() {
+ for truncated in [true, false] {
+ let (_root, shim, cache) = fixture();
+ let library = "libkrunfw.so.5";
+ fs::write(shim.with_file_name(library), b"firmware").unwrap();
+ let staged = stage_shim(&shim, &cache).unwrap();
+ let cached_library = staged.with_file_name(library);
+ if truncated {
+ fs::write(&cached_library, b"short").unwrap();
+ } else {
+ fs::remove_file(&cached_library).unwrap();
+ }
+ let stamp = staged.with_file_name(STAMP);
+ let old = FileTime::from_unix_time(1, 0);
+ set_file_mtime(&stamp, old).unwrap();
+
+ let result = stage_shim(&shim, &cache);
+
+ assert!(
+ matches!(result, Err(BoxliteError::Storage(_))),
+ "{result:?}"
+ );
+ assert_eq!(
+ FileTime::from_last_modification_time(&fs::metadata(stamp).unwrap()),
+ old
+ );
+ assert!(staged.is_file());
+ assert_eq!(fs::read_dir(cache).unwrap().count(), 1);
+ }
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn plan_bwrap_shim_mounts_remaps_symlinked_runtime_layout() {
+ use std::os::unix::fs::symlink;
+
+ let root = tempdir().unwrap();
+ let target_dir = root.path().join("target/debug");
+ let runtime_dir = target_dir.join("runtime");
+ let real_out = target_dir.join("real-out");
+ let out_link = target_dir.join("build/boxlite-hash/out");
+ std::fs::create_dir_all(&runtime_dir).unwrap();
+ std::fs::create_dir_all(&real_out).unwrap();
+ std::fs::create_dir_all(out_link.parent().unwrap()).unwrap();
+ symlink(&real_out, &out_link).unwrap();
+
+ let real_shim = target_dir.join("boxlite-shim");
+ let real_fw = real_out.join("libkrunfw.so.5.4.0");
+ fs::write(&real_shim, b"shim").unwrap();
+ fs::write(&real_fw, b"fw").unwrap();
+
+ let runtime_shim = runtime_dir.join("boxlite-shim");
+ let fw_hop1 = runtime_dir.join(".libkrunfw-hop");
+ let runtime_fw = runtime_dir.join("libkrunfw.so.5");
+ symlink("../boxlite-shim", &runtime_shim).unwrap();
+ symlink("../build/boxlite-hash/out/libkrunfw.so.5.4.0", &fw_hop1).unwrap();
+ symlink(".libkrunfw-hop", &runtime_fw).unwrap();
+
+ let plan = plan_bwrap_shim_mounts(&runtime_shim);
+ assert_eq!(
+ plan.executable,
+ Path::new(BWRAP_SANDBOX_SHIM_DIR).join("boxlite-shim")
+ );
+ assert_eq!(
+ plan.ld_library_path,
+ format!("{BWRAP_SANDBOX_SHIM_DIR}:{}", runtime_dir.display())
+ );
+ assert_eq!(
+ plan.ro_binds,
+ vec![
+ (
+ real_shim.canonicalize().unwrap(),
+ Path::new(BWRAP_SANDBOX_SHIM_DIR).join("boxlite-shim")
+ ),
+ (
+ real_fw.canonicalize().unwrap(),
+ Path::new(BWRAP_SANDBOX_SHIM_DIR).join("libkrunfw.so.5")
+ ),
+ ]
+ );
+ }
+
+ #[test]
+ fn plan_bwrap_shim_mounts_keeps_staged_non_symlink_paths_direct() {
+ let (_root, shim, cache) = fixture();
+ fs::write(shim.with_file_name("libkrunfw.so.5"), b"fw").unwrap();
+ let staged = stage_shim(&shim, &cache).unwrap();
+
+ let plan = plan_bwrap_shim_mounts(&staged);
+ assert!(plan.ro_binds.is_empty());
+ assert_eq!(plan.executable, staged);
+ assert_eq!(
+ plan.ld_library_path,
+ staged.parent().unwrap().to_string_lossy()
+ );
+ }
+}
diff --git a/src/boxlite/src/jailer/shim_copy.rs b/src/boxlite/src/jailer/shim_copy.rs
deleted file mode 100644
index e3e4993b5..000000000
--- a/src/boxlite/src/jailer/shim_copy.rs
+++ /dev/null
@@ -1,159 +0,0 @@
-//! Shim binary and libkrunfw copy utility (Firecracker pattern).
-//!
-//! This module implements Firecracker's security isolation pattern:
-//! copy (not hard-link) the shim binary into the jail directory to ensure
-//! complete memory isolation between boxes.
-//!
-//! `libkrunfw` is also copied because libkrun loads it via `dlopen` at
-//! runtime, and the shim's rpath resolves to `bin/`. Other bundled
-//! libraries (libkrun, libgvproxy) are **not** copied — libkrun is
-//! statically linked on macOS, and libgvproxy is a separate process.
-//!
-//! # Why Copy Instead of Hard-Link?
-//!
-//! 1. **Memory Isolation**: Hard-linked binaries share the same inode,
-//! which means they share the same `.text` section in memory.
-//! A vulnerability in one box could potentially exploit shared code.
-//!
-//! 2. **Independent Updates**: Each box has its own copy, so updates
-//! to the shim don't affect running boxes.
-//!
-//! # Usage
-//!
-//! ```ignore
-//! use boxlite::jailer::shim_copy::copy_shim_to_box;
-//!
-//! let copied_shim = copy_shim_to_box(&shim_path, &box_dir)?;
-//! // copied_shim is now at box_dir/bin/boxlite-shim
-//! ```
-
-use crate::jailer::common::fs::copy_if_newer;
-use boxlite_shared::errors::{BoxliteError, BoxliteResult};
-use std::path::{Path, PathBuf};
-
-/// Library file name prefixes to copy alongside the shim binary.
-///
-/// Only `libkrunfw` is needed: libkrun `dlopen`s it at runtime and the
-/// shim's rpath resolves to `bin/`. On Linux, `libkrunfw` is also
-/// dynamically loaded via `dlopen`.
-#[cfg(any(target_os = "linux", target_os = "macos"))]
-const LIBKRUNFW_PREFIX: &str = "libkrunfw.";
-
-/// Copy shim binary and libkrunfw to box directory for jail isolation.
-///
-/// This follows Firecracker's approach: copy (not hard-link) the shim binary
-/// into the jail directory to ensure complete memory isolation between boxes.
-/// `libkrunfw` is also copied so that libkrun's `dlopen` can find it via
-/// the shim's rpath.
-///
-/// # Arguments
-///
-/// * `shim_path` - Path to the original shim binary
-/// * `box_dir` - Path to the box directory (e.g., `~/.boxlite/boxes/{box_id}`)
-///
-/// # Returns
-///
-/// Path to the copied shim binary (inside `box_dir/bin/`).
-///
-/// # Errors
-///
-/// Returns [`BoxliteError::Storage`] if:
-/// - Failed to create the `bin/` directory
-/// - Failed to copy the shim binary
-/// - Failed to copy libkrunfw
-///
-/// # Example
-///
-/// ```ignore
-/// let copied_shim = copy_shim_to_box(&shim_path, &box_dir)?;
-/// // Use copied_shim instead of original shim_path
-/// ```
-pub fn copy_shim_to_box(shim_path: &Path, box_dir: &Path) -> BoxliteResult<PathBuf> {
- let bin_dir = box_dir.join("bin");
- std::fs::create_dir_all(&bin_dir).map_err(|e| {
- BoxliteError::Storage(format!(
- "Failed to create bin directory {}: {}",
- bin_dir.display(),
- e
- ))
- })?;
-
- // Copy shim binary
- let shim_name = shim_path.file_name().unwrap_or_default();
- let dest_shim = bin_dir.join(shim_name);
-
- let copied = copy_if_newer(shim_path, &dest_shim).map_err(|e| {
- BoxliteError::Storage(format!(
- "Failed to copy shim {} to {}: {}",
- shim_path.display(),
- dest_shim.display(),
- e
- ))
- })?;
-
- if copied {
- tracing::debug!(
- src = %shim_path.display(),
- dst = %dest_shim.display(),
- "Copied shim binary to box directory"
- );
- }
-
- // Copy libkrunfw so dlopen can find it via the shim's rpath.
- if let Some(shim_dir) = shim_path.parent() {
- copy_libkrunfw(shim_dir, &bin_dir)?;
- }
-
- Ok(dest_shim)
-}
-
-/// Copy libkrunfw from the shim's directory to `dest_dir`.
-///
-/// libkrun loads libkrunfw via `dlopen` at runtime. On macOS the shim's
-/// rpath resolves to its own directory (`bin/`), and `DYLD_*` env vars are
-/// stripped by SIP when going through `sandbox-exec`. Copying the library
-/// into `bin/` ensures `dlopen` can always find it.
-///
-/// Uses copy-if-newer to avoid unnecessary copies on subsequent starts.
-fn copy_libkrunfw(src_dir: &Path, dest_dir: &Path) -> BoxliteResult<()> {
- let entries = match std::fs::read_dir(src_dir) {
- Ok(entries) => entries,
- Err(e) => {
- tracing::warn!(
- src_dir = %src_dir.display(),
- error = %e,
- "Could not read source directory for libkrunfw"
- );
- return Ok(());
- }
- };
-
- for entry in entries.filter_map(|e| e.ok()) {
- let name = entry.file_name();
- let name_str = name.to_string_lossy();
-
- if name_str.starts_with(LIBKRUNFW_PREFIX) {
- let src_path = entry.path();
- let dest_path = dest_dir.join(&name);
-
- let copied = copy_if_newer(&src_path, &dest_path).map_err(|e| {
- BoxliteError::Storage(format!(
- "Failed to copy libkrunfw {} to {}: {}",
- src_path.display(),
- dest_path.display(),
- e
- ))
- })?;
-
- if copied {
- tracing::debug!(
- lib = %name_str,
- dst = %dest_path.display(),
- "Copied libkrunfw to box directory"
- );
- }
- }
- }
-
- Ok(())
-}
diff --git a/src/boxlite/src/runtime/layout.rs b/src/boxlite/src/runtime/layout.rs
index 383146f0c..c6a342d3a 100644
--- a/src/boxlite/src/runtime/layout.rs
+++ b/src/boxlite/src/runtime/layout.rs
@@ -22,6 +22,9 @@ pub mod dirs {
/// Subdirectory for running boxes
pub const BOXES_DIR: &str = "boxes";
+ /// Subdirectory for the shared shim and firmware cache
+ pub(crate) const SHIMS_DIR: &str = "shims";
+
/// Subdirectory for managed local volumes
pub const VOLUMES_DIR: &str = "volumes";
@@ -108,6 +111,7 @@ impl FsLayoutConfig {
/// │ └── {path_hash}-{manifest_short}/
/// ├── boxes/ # Per-box directories (BoxFilesystemLayout)
/// │ └── {box_id}/ # See BoxFilesystemLayout
+/// ├── shims/ # Shim and firmware cache by digest
/// ├── bases/ # Flat backing files (nanoid-named)
/// │ ├── {nanoid}.qcow2 # Snapshot / clone base container disk
/// │ └── {nanoid}.ext4 # Guest rootfs cache
@@ -170,6 +174,14 @@ impl FilesystemLayout {
self.home_dir.join(dirs::BOXES_DIR)
}
+ pub(crate) fn shims_dir(&self) -> PathBuf {
+ Self::shims_dir_for(&self.home_dir)
+ }
+
+ pub(crate) fn shims_dir_for(home_dir: &Path) -> PathBuf {
+ home_dir.join(dirs::SHIMS_DIR)
+ }
+
/// Root directory for managed local volumes: ~/.boxlite/volumes
pub fn volumes_dir(&self) -> PathBuf {
self.home_dir.join(dirs::VOLUMES_DIR)
@@ -488,10 +500,7 @@ impl BoxFilesystemLayout {
// BIN AND LOGS (jailer isolation)
// ========================================================================
- /// Bin directory: ~/.boxlite/boxes/{box_id}/bin
- ///
- /// Contains the shim binary and bundled libraries, copied (or reflinked)
- /// by the jailer for memory isolation between boxes.
+ /// Legacy per-box bin path, retained for API compatibility and cleanup.
pub fn bin_dir(&self) -> PathBuf {
self.box_dir.join("bin")
}
@@ -768,6 +777,23 @@ impl ImageFilesystemLayout {
mod tests {
use super::*;
+ #[test]
+ fn test_shims_dir() {
+ let home = Path::new("/boxlite-home");
+ let layout = FilesystemLayout::new(home.to_path_buf(), FsLayoutConfig::default());
+ assert_eq!(layout.shims_dir(), home.join("shims"));
+ assert_eq!(FilesystemLayout::shims_dir_for(home), layout.shims_dir());
+ }
+
+ #[test]
+ fn test_prepare_accepts_regular_file_at_shims_path() {
+ let home = tempfile::tempdir().unwrap();
+ let layout = FilesystemLayout::new(home.path().to_path_buf(), FsLayoutConfig::default());
+ std::fs::write(layout.shims_dir(), b"legacy file").unwrap();
+ layout.prepare().unwrap();
+ assert_eq!(std::fs::read(layout.shims_dir()).unwrap(), b"legacy file");
+ }
+
#[test]
fn test_local_bundle_cache_dir_format() {
let layout = ImageFilesystemLayout::new(PathBuf::from("/images"));
diff --git a/src/boxlite/src/runtime/rt_impl.rs b/src/boxlite/src/runtime/rt_impl.rs
index 8073b8239..07c7996ec 100644
--- a/src/boxlite/src/runtime/rt_impl.rs
+++ b/src/boxlite/src/runtime/rt_impl.rs
@@ -293,6 +293,8 @@ impl RuntimeImpl {
))
})?;
+ crate::jailer::shim_cache::cleanup_stale(&layout.shims_dir(), None);
+
// Clean temp dir contents to avoid stale files from previous runs
if let Ok(entries) = std::fs::read_dir(layout.temp_dir()) {
for entry in entries.flatten() {
diff --git a/src/boxlite/src/vmm/controller/shim.rs b/src/boxlite/src/vmm/controller/shim.rs
index 16481e2dd..73e263b95 100644
--- a/src/boxlite/src/vmm/controller/shim.rs
+++ b/src/boxlite/src/vmm/controller/shim.rs
@@ -4,7 +4,7 @@ use std::{path::PathBuf, process::Child, sync::Mutex, time::Instant};
use crate::{
BoxID,
- runtime::layout::BoxFilesystemLayout,
+ runtime::layout::{BoxFilesystemLayout, FilesystemLayout},
vmm::{InstanceSpec, VmmKind},
};
@@ -375,6 +375,7 @@ impl VmmController for ShimController {
self.box_id.as_str(),
&self.options,
)
+ .with_shim_cache_dir(FilesystemLayout::shims_dir_for(&config.home_dir))
.with_nested_virtualization(config.nested_virtualization)
.with_volume_access(config.volume_access.clone());
let spawned = spawner.spawn(&config_json, config.detach)?;
diff --git a/src/boxlite/src/vmm/controller/spawn.rs b/src/boxlite/src/vmm/controller/spawn.rs
index ba720c4cd..972f6003d 100644
--- a/src/boxlite/src/vmm/controller/spawn.rs
+++ b/src/boxlite/src/vmm/controller/spawn.rs
@@ -43,6 +43,7 @@ pub struct SpawnedShim {
pub struct ShimSpawner<'a> {
binary_path: &'a Path,
layout: &'a BoxFilesystemLayout,
+ shim_cache_dir: Option<PathBuf>,
box_id: &'a str,
options: &'a BoxOptions,
nested_virtualization: bool,
@@ -59,6 +60,7 @@ impl<'a> ShimSpawner<'a> {
Self {
binary_path,
layout,
+ shim_cache_dir: None,
box_id,
options,
nested_virtualization: false,
@@ -98,6 +100,11 @@ impl<'a> ShimSpawner<'a> {
self
}
+ pub(crate) fn with_shim_cache_dir(mut self, dir: impl Into<PathBuf>) -> Self {
+ self.shim_cache_dir = Some(dir.into());
+ self
+ }
+
pub fn with_volume_access(mut self, paths: Vec<PathAccess>) -> Self {
self.volume_access = paths;
self
@@ -128,6 +135,26 @@ impl<'a> ShimSpawner<'a> {
.collect()
}
+ fn jailer_builder(&self, detach: bool) -> JailerBuilder {
+ let mut builder = JailerBuilder::new()
+ .with_box_id(self.box_id)
+ .with_layout(self.layout.clone())
+ .with_security(self.options.advanced.security.clone())
+ .with_volumes(self.options.volumes.clone())
+ .with_mounts(self.options.mounts.clone())
+ .with_additional_path_access(self.additional_path_access())
+ .with_network_backend_enabled(matches!(
+ &self.options.network,
+ NetworkSpec::Enabled { .. }
+ ))
+ .with_detach(detach);
+
+ if let Some(dir) = &self.shim_cache_dir {
+ builder = builder.with_shim_cache_dir(dir);
+ }
+ builder
+ }
+
/// Spawn the shim subprocess with jailer isolation and optional watchdog.
///
/// When `detach` is false, creates a watchdog pipe so the shim detects
@@ -147,19 +174,7 @@ impl<'a> ShimSpawner<'a> {
// 2. Build jailer with optional FD preservation for watchdog pipe.
// `with_detach(detach)` threads the lifecycle choice into the
// jailer's pre_exec chain (setsid vs. process_group).
- let mut builder = JailerBuilder::new()
- .with_box_id(self.box_id)
- .with_layout(self.layout.clone())
- .with_security(self.options.advanced.security.clone())
- .with_volumes(self.options.volumes.clone())
- .with_mounts(self.options.mounts.clone())
- .with_additional_path_access(self.additional_path_access())
- .with_network_backend_enabled(matches!(
- &self.options.network,
- NetworkSpec::Enabled { .. }
- ))
- .with_detach(detach);
-
+ let mut builder = self.jailer_builder(detach);
if let Some(ref setup) = child_setup {
builder = builder.with_preserved_fd(setup.raw_fd(), watchdog::PIPE_FD);
}
@@ -327,6 +342,19 @@ mod tests {
assert_eq!(spawner.box_id, "test-box");
}
+ #[test]
+ fn spawn_forwards_explicit_shim_cache_dir_to_jailer() {
+ let layout = test_layout();
+ let options = BoxOptions::default();
+ let cache_dir = PathBuf::from("/tmp/custom-shim-cache");
+ let spawner = ShimSpawner::new(Path::new("/bin/true"), &layout, "test-box", &options)
+ .with_shim_cache_dir(&cache_dir);
+
+ let jailer = spawner.jailer_builder(false).build().unwrap();
+
+ assert_eq!(jailer.resolve_shim_cache_dir(), Some(cache_dir));
+ }
+
/// The probe grant widens the shim's sandbox, so only a box that asked for
/// nesting may request it.
///
diff --git a/src/boxlite/src/vmm/controller/tests/fractional_cpus_membership.rs b/src/boxlite/src/vmm/controller/tests/fractional_cpus_membership.rs
index 7a1d51e12..61ef828d4 100644
--- a/src/boxlite/src/vmm/controller/tests/fractional_cpus_membership.rs
+++ b/src/boxlite/src/vmm/controller/tests/fractional_cpus_membership.rs
@@ -47,18 +47,19 @@ fn assert_spawn_survives_cgroup_failure(membership_target: Option<&Path>, quota_
let home = tempfile::tempdir().unwrap();
let layout = BoxFilesystemLayout::new(
- home.path().to_path_buf(),
+ home.path().join("boxes/membership-test"),
FsLayoutConfig::without_bind_mount(),
false,
);
layout.prepare().unwrap();
- // The jailer copies this helper into <box>/bin. Its marker is in the
- // writable logs binding, since bubblewrap replaces /tmp with a tmpfs.
+ // The staged helper writes its marker through the writable logs binding.
let helpers = tempfile::tempdir().unwrap();
let binary = helpers.path().join("membership-helper");
+ let marker = layout.logs_dir().join("executed");
+ let quoted_marker = marker.to_str().unwrap().replace('\'', "'\\''");
fs::write(
&binary,
- "#!/bin/sh\nexec cat > \"${0%/*}/../logs/executed\"\n",
+ format!("#!/bin/sh\nexec cat > '{quoted_marker}'\n"),
)
.unwrap();
fs::set_permissions(&binary, fs::Permissions::from_mode(0o755)).unwrap();
@@ -78,10 +79,7 @@ fn assert_spawn_survives_cgroup_failure(membership_target: Option<&Path>, quota_
}
let mut spawned = result.expect("cgroup failure must not prevent child exec");
assert!(spawned.child.wait().unwrap().success());
- assert_eq!(
- fs::read_to_string(layout.logs_dir().join("executed")).unwrap(),
- config
- );
+ assert_eq!(fs::read_to_string(marker).unwrap(), config);
layout.cleanup().unwrap();
}
diff --git a/src/boxlite/tests/jailer.rs b/src/boxlite/tests/jailer.rs
index 85542d3c5..0b28155e7 100644
--- a/src/boxlite/tests/jailer.rs
+++ b/src/boxlite/tests/jailer.rs
@@ -11,6 +11,8 @@ mod common;
use boxlite::runtime::advanced_options::{AdvancedBoxOptions, SecurityOptions};
use boxlite::runtime::options::{BoxOptions, NetworkSpec};
use common::box_test::BoxTestBase;
+use std::fs;
+use std::os::unix::fs::MetadataExt;
use std::path::PathBuf;
// ============================================================================
@@ -220,6 +222,64 @@ async fn jailer_enabled_box_starts_and_executes() {
);
}
+#[tokio::test]
+async fn jailer_shares_single_staged_shim_across_boxes() {
+ let t = BoxTestBase::with_home(JailerHome::new().home, jailer_enabled_options()).await;
+ let second = t
+ .runtime
+ .create(jailer_enabled_options(), None)
+ .await
+ .unwrap();
+ let box_bin = |bx: &boxlite::LiteBox| {
+ t.home_dir()
+ .join("boxes")
+ .join(bx.id().as_str())
+ .join("bin")
+ };
+ let cache = t.home_dir().join("shims");
+
+ t.bx.start().await.unwrap();
+ let generation = fs::read_dir(&cache)
+ .unwrap()
+ .next()
+ .unwrap()
+ .unwrap()
+ .path();
+ let digest = generation.file_name().unwrap().to_str().unwrap();
+ assert_eq!(digest.len(), 16);
+ assert!(
+ digest
+ .bytes()
+ .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
+ );
+ let stamp = generation.join(".complete");
+ let old = filetime::FileTime::from_unix_time(1, 0);
+ filetime::set_file_mtime(&stamp, old).unwrap();
+ let shim = generation.join("boxlite-shim");
+ let inode = fs::metadata(&shim).unwrap().ino();
+
+ second.start().await.unwrap();
+ assert!(filetime::FileTime::from_last_modification_time(&fs::metadata(stamp).unwrap()) > old);
+ assert_eq!(fs::read_dir(&cache).unwrap().count(), 1);
+ assert_eq!(fs::metadata(&shim).unwrap().ino(), inode);
+ let legacy_bin = box_bin(&t.bx);
+ assert!(!legacy_bin.exists());
+ assert!(!box_bin(&second).exists());
+
+ t.bx.stop().await.unwrap();
+ fs::create_dir(&legacy_bin).unwrap();
+ fs::write(legacy_bin.join("stale-shim"), b"legacy shim").unwrap();
+ let restarted = t.runtime.get(t.bx.id().as_str()).await.unwrap().unwrap();
+ restarted.start().await.unwrap();
+ assert!(!legacy_bin.exists());
+ assert_eq!(fs::read_dir(cache).unwrap().count(), 1);
+ assert_eq!(fs::metadata(shim).unwrap().ino(), inode);
+
+ restarted.stop().await.unwrap();
+ second.stop().await.unwrap();
+ t.runtime.remove(second.id().as_str(), true).await.unwrap();
+}
+
/// #1072: dropping the jailer's own network grants must not take the shim's
/// AF_UNIX control plane with it.
///
diff --git a/tests/scripts/test_e2e_local.py b/tests/scripts/test_e2e_local.py
index 1fb95041f..156dc1ab5 100644
--- a/tests/scripts/test_e2e_local.py
+++ b/tests/scripts/test_e2e_local.py
@@ -279,6 +279,50 @@ class LocalE2ETest(unittest.TestCase):
os.killpg(process.pid, signal.SIGKILL)
process.wait()
+ def check_shared_shim_reaping(self, *, use_bwrap_parent):
+ home = self.state / "runtime"
+ shim = str(home / "shims/0123456789abcdef/boxlite-shim")
+ recoverable = home / "boxes/recoverable"
+ recoverable.mkdir(parents=True)
+ (recoverable / "shim.pid").write_text("101\n42\n")
+ argv = {101: [shim], 102: [shim]}
+ if use_bwrap_parent:
+ argv[201] = ["/usr/bin/bwrap", str(recoverable / "tmp"), shim]
+ argv[202] = ["/usr/bin/bwrap", str(home / "boxes/lost/tmp"), shim]
+ environments = {101: b"BOXLITE_BOX_ID=lost", 102: b"BOXLITE_BOX_ID=recoverable"}
+ else:
+ argv[201] = ["/usr/bin/bwrap", str(self.state / "other/boxes/lost/tmp")]
+ environments = {101: b"BOXLITE_BOX_ID=recoverable", 102: b"BOXLITE_BOX_ID=lost"}
+ real_read_text = Path.read_text
+
+ def read_text(path):
+ if path.name == "stat" and path.parent.parent == Path("/proc"):
+ pid = int(path.parent.name)
+ return f"{pid} (shim ) name) S {pid + 100} " + "0 " * 17 + "42"
+ return real_read_text(path)
+
+ def read_bytes(path):
+ self.assertEqual(path.name, "environ")
+ return b"OTHER=ignored\0" + environments[int(path.parent.name)] + b"\0"
+
+ with patch.object(local, "RUNTIME_HOME", home), \
+ patch.object(local, "box_processes", return_value=[101, 102]), \
+ patch.object(local, "_argv", side_effect=lambda pid: argv.get(pid, [])), \
+ patch.object(Path, "read_text", read_text), \
+ patch.object(Path, "read_bytes", read_bytes), \
+ patch.object(local.os, "kill") as check_pid, \
+ patch.object(local, "stop_orphaned_boxes", return_value=[]) as reap:
+ local.reap_unrecoverable_boxes()
+
+ check_pid.assert_called_once_with(101, 0)
+ reap.assert_called_once_with(pids=[102])
+
+ def test_reap_shared_shims_attributed_by_bwrap_parent(self):
+ self.check_shared_shim_reaping(use_bwrap_parent=True)
+
+ def test_reap_shared_shims_attributed_by_box_id_environment(self):
+ self.check_shared_shim_reaping(use_bwrap_parent=False)
+
def test_compose_declares_all_dependency_services(self):
compose = (local.E2E / "compose.yaml").read_text()
for service in ("postgres", "redis", "registry", "rauthy", "rustfs"):
@@ -487,6 +531,12 @@ class LocalE2ETest(unittest.TestCase):
self.assertFalse(local.owned_process([f"{home}/boxes/abc/bin/python3"]))
self.assertFalse(local.owned_process([]))
+ def test_owned_process_matches_shared_shims_in_this_checkout(self):
+ home = str(local.RUNTIME_HOME)
+ self.assertTrue(local.owned_process([f"{home}/shims/0123456789abcdef/boxlite-shim"]))
+ self.assertFalse(local.owned_process(["/tmp/elsewhere/shims/0123456789abcdef/boxlite-shim"]))
+ self.assertFalse(local.owned_process([f"{home}/shims/abc/python3"]))
+
def test_prune_box_dirs_removes_only_box_directories(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)