Skip to content

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

feat(volumes): LocalVolumeStore core and cli (#2707)

Lhfcws049d1ab7217a
diff --git a/docs/concepts/storage.md b/docs/concepts/storage.md
index 57afb4fca..66ca5da64 100644
--- a/docs/concepts/storage.md
+++ b/docs/concepts/storage.md
@@ -27,8 +27,14 @@ Image Layers Rootfs Builder Box Rootfs
| Type | Description | Use Case |
|----------------|--------------------------|--------------------------------------|
-| **virtiofs** | Host directory mount | Sharing files with Box |
-| **QCOW2 disk** | Copy-on-write disk image | Box files, kept while the Box exists |
+| **virtiofs bind** | Caller-selected host directory or file | Sharing a specific host path with a box |
+| **Named local volume** | BoxLite-managed directory shared over virtio-fs | Persistent data shared independently of box lifecycle |
+| **QCOW2 disk** | Copy-on-write disk image | Box-private root filesystem, kept while the box exists |
+
+Named volume identity and payload are separate: `{volume-id}/.metadata.json` stores id, name, and
+creation time, while only `{volume-id}/_data/` is exposed to the guest. Box configuration stores the
+canonical id rather than the host path. Volume removal is blocked while any persisted box
+configuration references that id. See [Mounting volumes](../guides/volumes.md).
**QCOW2 features:**
diff --git a/docs/contributing/README.md b/docs/contributing/README.md
index 990030584..92e745900 100644
--- a/docs/contributing/README.md
+++ b/docs/contributing/README.md
@@ -29,6 +29,7 @@ How to build, test, and change the code.
- [CLI development](development/cli.md): building, testing, and extending the `boxlite` CLI.
- [E2E local CI runbook](development/e2e-local.md): the self-hosted runner behind `e2e-local.yml`.
- [REST API testing](development/rest-api-testing.md): API-key and OIDC coverage across the SDK, CLI, API, runner, and VM.
+- [Local volume testing](development/local-volume-testing.md): unit, guest, real-VM, and Python compatibility checks for local managed volumes.
- [macOS sandbox debugging](development/macos-sandbox-debugging.md): find and fix Seatbelt denials.
## Investigations
diff --git a/docs/contributing/development/local-volume-testing.md b/docs/contributing/development/local-volume-testing.md
new file mode 100644
index 000000000..dc5a169db
--- /dev/null
+++ b/docs/contributing/development/local-volume-testing.md
@@ -0,0 +1,224 @@
+# Local volume test runbook
+
+Use this runbook for changes to local managed volumes: the store, box holder lifecycle, archive
+round trips, CLI mounts, guest resolved mounts, or the existing Python `volumes` dictionary API.
+It tests the local runtime only; cloud, REST, and runner behavior are out of scope.
+
+Run every command from the repository root unless the command changes directory itself. Execute the
+steps in order and keep the output needed to identify which tests actually ran.
+
+## Evidence rules
+
+- Use the Make targets below so builds retain the required features, runtime artifacts, and ordering.
+- A passing command must exit zero **and run the intended tests**. A filter that matches zero tests,
+ a platform skip, or a successful build alone is not test coverage.
+- Fix failures caused by the change before continuing. Record unrelated or pre-existing failures
+ separately, with evidence; never turn a red suite into a reported pass.
+- When fixing a defect, also perform the defect proof in
+ [`AGENTS.md`](../../../AGENTS.md#defect-proof). A passing test without the failing pre-fix run does
+ not prove the fix.
+- Do not commit or create a PR unless the user asked for it.
+
+## 1. Prepare and record the environment
+
+Inspect the working tree before testing so existing changes are preserved:
+
+```bash
+git status --short --branch
+uname -s -m
+```
+
+For a checkout that has not been set up, initialize submodules and install the platform dependencies:
+
+```bash
+git submodule update --init --recursive
+make setup
+```
+
+The M3 matrix requires cargo-nextest. If `cargo nextest --version` fails on an existing checkout, run
+`make setup` to install the missing test tool before invoking the matrix.
+
+The VM tests require a supported local hypervisor: macOS ARM64 with Hypervisor.framework, or Linux
+with KVM. On Linux, verify that KVM is usable before starting the VM suites:
+
+```bash
+test -r /dev/kvm -a -w /dev/kvm
+```
+
+Step 1 is complete when the required tools are present, the platform is recorded, and any unavailable
+hypervisor is reported as a blocker rather than replaced with compile-only checks.
+
+## 2. Run the fast Rust loop
+
+Format and lint first, then run the volume-focused unit tests:
+
+```bash
+make fmt:rust
+make clippy
+make test:unit:rust FILTER=volume
+```
+
+The focused filter is a development loop, not the final Rust gate. Before finishing any code change,
+run the complete unit suite so archive, import, VMM grants, and lifecycle tests without `volume` in
+their names are included:
+
+```bash
+make test:unit:rust
+```
+
+Step 2 is complete when Clippy and the full unit suite pass. If only a focused run has completed,
+report the remaining full-suite run explicitly.
+
+## 3. Run guest tests on Linux
+
+On Linux, run the guest suite. It includes the resolved-mount cleanup, read-only, path-replacement,
+and unsupported-`openat2` tests:
+
+```bash
+make test:unit:guest
+```
+
+On macOS, record these tests as **not run; Linux required**. The Make target's successful skip is not
+a guest test pass. A change to `src/guest/src/storage/resolved_mount.rs` is not fully verified until
+this suite has run on Linux.
+
+## 4. Exercise real VM paths
+
+Run the local-volume CLI scenarios:
+
+```bash
+make test:integration:cli FILTER=local_volume
+```
+
+Confirm that the output contains all three test names:
+
+- `local_volume_complete_lifecycle`
+- `local_volume_rejects_duplicate_mounts`
+- `local_volume_remove_waits_for_last_holder`
+
+The lifecycle case creates a volume, writes and reads through separate real VMs using `--rm`,
+verifies that no boxes remain, removes the volume, and confirms that a subsequent get fails.
+
+When the mount protocol or guest bind dispatch changes, also verify the pre-existing single-file
+host-bind contract:
+
+```bash
+make test:integration:cli FILTER=test_run_with_single_file_volume
+```
+
+Confirm that `test_run_with_single_file_volume` ran and read the staged file through a real VM.
+
+Run an archive round trip:
+
+```bash
+make test:integration:rust FILTER=test_export_import_roundtrip
+```
+
+Confirm that `test_export_import_roundtrip` ran. These CLI and archive tests build and boot real VMs;
+allow the Make targets to finish instead of substituting `cargo check` or importing a library.
+
+On Linux, also run the existing host-directory compatibility cases through the explicit-engine M3
+matrix. The ordinary integration target lists these cases as ignored, so a zero-exit filtered run is
+not evidence that they executed:
+
+```bash
+make test:integration:vmm:m3 ENGINE=krun FILTER=directory_volumes
+```
+
+Confirm that the two-, three-, eight-, and thirty-two-directory cases all ran and passed. If the
+matrix reports a missing `VMM_KERNEL`, run `make vmm:boot` and then rerun the matrix. Use
+`ENGINE=native` instead when the change affects the native VMM path. On macOS, record the M3 matrix
+as **not run; Linux KVM required**.
+
+Step 4 is complete when the three CLI scenarios and archive round trip pass, plus all four M3
+directory cases on Linux. On a host without a usable hypervisor, skip the remaining VM steps and
+continue to the final report with that coverage marked as blocked.
+
+## 5. Verify the Python compatibility path
+
+Run the standard target first:
+
+```bash
+make test:integration:python FILTER=local_volume
+```
+
+Confirm that `test_local_volume_shared_by_boxes_clone_and_import` ran. It verifies that clone and
+import still read the original volume data and that removing a volume remains blocked while any box
+references it.
+
+### Python 3.9 fallback
+
+The standard target uses the repository's `.venv`. If it fails **before test collection** because
+that interpreter is Python 3.9 while the SDK requires Python 3.10 or later, use this isolated Python
+3.12 fallback. Do not use the fallback to bypass a test assertion or another build failure.
+
+```bash
+set -euo pipefail
+venv="$(mktemp -d /tmp/boxlite-py312-XXXXXX)"
+trap 'rm -rf "$venv"' EXIT
+python3.12 -m venv "$venv"
+"$venv/bin/pip" install -q uv maturin pytest
+export VIRTUAL_ENV="$venv"
+export PATH="$venv/bin:$PATH"
+(
+ cd sdks/python
+ "$venv/bin/maturin" develop --uv
+ "$venv/bin/python" -m pytest tests/test_local_volume.py -v
+)
+```
+
+This fallback intentionally builds through Maturin outside the hardcoded `.venv`; the normal Make
+target remains the required path on a supported interpreter. The trap removes the temporary
+environment when the shell exits. If Python 3.12 is unavailable, report the SDK test as blocked.
+
+After Python source or test changes, run:
+
+```bash
+make lint:python
+make fmt:check:python
+```
+
+Step 5 is complete when the named integration test has run under a supported interpreter and the
+Python checks pass. Disclose whether the standard target or fallback produced the evidence.
+
+## 6. Run broader core regression suites
+
+Before merging a runtime or lifecycle change, run:
+
+```bash
+make test:unit:core
+make test:integration:core
+```
+
+These suites are broader and slower than the focused checks. A timeout is not a pass: identify the
+unexecuted tests and rerun them with specific Make-target filters, or report the incomplete suite.
+
+On macOS, `TestMitmProxy_HTTP2_MultiplexedStreams` in the gvproxy bridge has been observed failing
+independently of local-volume work. Do not classify it as unrelated from its name alone: confirm
+that the change does not affect gvproxy and, when attribution is needed, rerun the same test on the
+base revision. Include the failure in the final report even when the local-volume evidence passes.
+
+## 7. Check the final diff and report
+
+Remove only temporary files created by the current test run. Leave pre-existing files and build
+caches alone, then run:
+
+```bash
+git diff --check
+git status --short --branch
+```
+
+Report each command with its platform and outcome. Include the number or names of tests executed,
+not just the command's exit status. Use this compact format:
+
+| Area | Command | Result | Evidence or limitation |
+| --- | --- | --- | --- |
+| Rust units | `make test:unit:rust` | Pass/fail | Test totals or failing test |
+| Guest | `make test:unit:guest` | Pass/fail/not run | Linux result or platform blocker |
+| CLI VM | `make test:integration:cli FILTER=local_volume` | Pass/fail/not run | Three named tests |
+| CLI single-file VM | `make test:integration:cli FILTER=test_run_with_single_file_volume` | Pass/fail/not run | Required for mount protocol or guest bind dispatch changes |
+| Python VM | Standard target or fallback | Pass/fail/not run | Interpreter and named test |
+
+The runbook is complete when every applicable step has run, all intended tests are accounted for,
+changed-code failures are fixed, and every skip, unrelated failure, or unrun platform check is
+explicit in the report.
diff --git a/docs/guides/volumes.md b/docs/guides/volumes.md
index 2e423fc52..e45f7d6d3 100644
--- a/docs/guides/volumes.md
+++ b/docs/guides/volumes.md
@@ -1,117 +1,127 @@
# Mounting volumes
-Mount host directories into boxes for data input/output.
+BoxLite supports host bind mounts and named local volumes. Both use virtio-fs to share a host
+directory with the guest.
-## Mount types
+## Host bind mounts
-**virtiofs (Default):**
-- High-performance file sharing
-- Low overhead
-- Real-time host-guest synchronization
+A bind mount exposes a host directory or file at a path inside the box. Use a tuple for host paths:
-**QCOW2 (container disk):**
-- Block device
-- Survives stop only when the box is kept (`auto_delete=0`)
-- Copy-on-write
+```python
+import os
+import boxlite
+
+async with boxlite.SimpleBox(
+ image="python:slim",
+ volumes=[
+ (os.path.expanduser("~/.config/myapp"), "/etc/myapp", True),
+ (os.path.join(os.getcwd(), "output"), "/output", False),
+ ],
+ working_dir="/output",
+) as box:
+ result = await box.exec("python", "process.py", "--input", "/etc/myapp/config")
+ print(result.stdout)
+```
-## Read-only vs read-write
+The third tuple element is `read_only`: `True` makes the mount read-only, `False` makes it
+read-write. Bind mounts are appropriate when the caller chooses the host path directly.
-**Read-Only Mount (Data Input):**
+## Named local volumes
-```python
-volumes=[
- ("/host/config", "/etc/app/config", True),
- ("/host/datasets", "/mnt/data", True),
-]
+A named local volume is managed by BoxLite rather than by a host path in box configuration. Its
+payload survives box deletion and can be mounted by multiple boxes.
+
+Create and inspect volumes with the CLI:
+
+```bash
+boxlite volume create --name workspace
+boxlite volume ls
+boxlite volume get <volume-id>
```
-**Read-Write Mount (Data Output):**
+The create command prints a UUID. The name is optional and defaults to that UUID. A user-supplied
+name cannot itself be a canonical UUID, which keeps mount selectors unambiguous. Get and remove
+accept only the canonical id; mount accepts either the id or the name.
-```python
-volumes=[
- ("/host/output", "/mnt/output", False),
- ("/host/logs", "/var/log/app", False),
-]
+Mount by name with the existing shorthand:
+
+```bash
+boxlite run --rm -v workspace:/workspace alpine:latest \
+ sh -c 'echo hello > /workspace/result.txt'
+boxlite run --rm -v workspace:/workspace:ro alpine:latest \
+ sh -c 'cat /workspace/result.txt; echo change > /workspace/result.txt'
```
-## Common use cases
+The second box can read the file written by the first. Its read-only mount rejects the attempted
+write. Multiple boxes may mount the same volume read-write, but BoxLite does not provide
+application-level transactions, write-conflict resolution, or locking for their workloads.
-### 1. Configuration files
+### Typed volume mounts and subdirectories
-```python
-import os
-import boxlite
+`--mount` provides the typed form, including `readonly` and `sub_path`:
-# Mount config directory
-async with boxlite.SimpleBox(
- image="python:slim",
- volumes=[
- (os.path.expanduser("~/.config/myapp"), "/etc/myapp", True)
- ]
-) as box:
- result = await box.exec("cat", "/etc/myapp/config.yaml")
- print(result.stdout)
+```bash
+boxlite run --rm \
+ --mount type=volume,source=workspace,target=/workspace,readonly,sub_path=team/backend \
+ alpine:latest
```
-### 2. Data processing
+`sub_path` must name an existing directory inside the volume. It cannot be absolute, contain `.` or
+`..`, or contain a symlink. Only that subdirectory is visible at the mount target; sibling
+directories are not mounted. A missing directory returns `NotFound` and is not created implicitly.
-```python
-# Input data (read-only), output results (read-write)
-async with boxlite.SimpleBox(
- image="python:slim",
- volumes=[
- ("/data/input", "/mnt/input", True),
- ("/data/output", "/mnt/output", False),
- ]
-) as box:
- await box.exec("python", "process.py", "--input", "/mnt/input", "--output", "/mnt/output")
-```
+The legacy `-v` syntax supports read-only mounts but not `sub_path`. CLI typed mounts support only
+`type=volume`; host binds continue to use `-v`.
-### 3. Source code development
+A single box cannot mount the same canonical volume id more than once, even under different names,
+targets, or read-only modes. This is rejected with `InvalidArgument`. Different boxes may still
+mount the same id independently.
-```python
-# Mount source code for live development
-async with boxlite.SimpleBox(
- image="python:slim",
- volumes=[
- (os.getcwd(), "/workspace", False)
- ],
- working_dir="/workspace"
-) as box:
- # Run tests in isolated environment
- await box.exec("pytest", "tests/")
+### Lifecycle, clone, and import
+
+Every persisted box configuration that references a volume prevents its deletion, including
+configured, failed, stopped, and running boxes. `boxlite volume rm --force` ignores a missing volume
+but does not bypass this protection.
+
+After the last referencing box is removed:
+
+```bash
+boxlite volume rm <volume-id>
```
-### 4. Persistent storage with QCOW2
+Deleting a box does not delete volume data. Cloning a box or importing a box archive on the same
+machine retains the canonical volume id and shares the same payload; it does not copy the data. An
+import fails with `NotFound` if the target machine has no volume with that id. Archives do not
+create empty replacement volumes or migrate payload automatically.
+
+The CLI's existing anonymous bind directories under `volumes/anonymous/` are unchanged and are not
+listed as named volumes.
+
+`size_bytes` is currently unset because BoxLite does not recursively scan volume payload during
+CRUD operations.
+
+## QCOW2 container disks
+
+The container rootfs uses a separate QCOW2 disk, not a named volume. It is private to the box and
+uses copy-on-write layers shared with image and clone bases. It survives stop only when the box is
+kept (`auto_delete=0`).
```python
-# Create a box that keeps its disk after stop
box = await runtime.create(boxlite.BoxOptions(
image="postgres:latest",
- disk_size_gb=20, # 20 GB disk
- env=[("POSTGRES_PASSWORD", "secret")],
- auto_delete=0, # keep the box after stop
+ disk_size_gb=10,
+ auto_delete=0,
))
-
-# Data survives stop/restart
await box.stop()
-# ... later ...
-box = await runtime.get(box.id) # Disk still intact
+box = await runtime.get(box.id)
```
-## Performance considerations
+Use named local volumes for independent, shared data resources; use the QCOW2 rootfs for the box's
+private container filesystem.
-**virtiofs Performance:**
-- Fast for small files
-- Slight overhead for large files
-- Real-time synchronization
-
-**QCOW2 Performance:**
-- Block-level access (faster for large files)
-- Copy-on-write overhead
-- No real-time sync with host
+## Performance considerations
-**Best Practices:**
-- Use read-only mounts when possible (lower overhead)
-- Mount specific directories, not entire filesystem
-- For large datasets, consider QCOW2 disk
+- virtio-fs shares host files directly and reflects host/guest changes in real time.
+- Metadata-heavy workloads may perform differently from the QCOW2 block-device rootfs.
+- Use read-only mounts when possible.
+- Mount only the required host directory or volume `sub_path`.
diff --git a/docs/reference/cli/README.md b/docs/reference/cli/README.md
index 62632aadd..36913226b 100644
--- a/docs/reference/cli/README.md
+++ b/docs/reference/cli/README.md
@@ -1190,9 +1190,8 @@ BOXLITE_SERVE_API_KEY="$KEY" boxlite serve --host 0.0.0.0
**Synopsis:** `boxlite volume <create|ls|get|rm>`
-Manage managed persistent volumes. Volumes are a REST-runtime capability — the
-local runtime has no volume backend, so every subcommand returns
-`named volumes are not supported yet` against it. See
+Manage persistent volumes. LocalRuntime stores them under its home directory;
+REST runtimes use the selected server's volume API. See
[Connecting to the cloud](#connecting-to-the-cloud).
| Subcommand | Synopsis | Notes |
@@ -1206,9 +1205,9 @@ local runtime has no volume backend, so every subcommand returns
wants without knowing the id:
```bash
-boxlite volume create --name my-data # prints e.g. vol_01K2EXAMPLE
+boxlite volume create --name my-data # prints a canonical UUID
boxlite run -v my-data:/data alpine # by name
-boxlite run -v vol_01K2EXAMPLE:/data alpine # or by id
+boxlite run -v <volume-uuid>:/data alpine # or by id
```
Names must be at least two characters of `[a-zA-Z0-9][a-zA-Z0-9_.-]` — Docker's
@@ -1349,6 +1348,11 @@ Used by `run` and `create` (defined in `src/cli/src/cli.rs`).
| Flag | Short | Description |
|------|-------|-------------|
| `--volume VOLUME` | `-v` | Mount a volume; repeatable (see [Volume Mount Syntax](#volume-mount-syntax)) |
+| `--mount type=volume,source=NAME,target=PATH[,readonly][,sub_path=DIR]` | — | Typed managed-volume mount; mutually exclusive with `-v` |
+
+`sub_path` selects an existing directory inside the volume and rejects absolute paths, `..`, and
+symlinks. Reusing the same canonical volume id twice in one box is rejected; use a different box or
+volume for each mount declaration.
### `NetworkFlags`
diff --git a/docs/reference/file-formats.md b/docs/reference/file-formats.md
index 75ad52ffc..90e819a40 100644
--- a/docs/reference/file-formats.md
+++ b/docs/reference/file-formats.md
@@ -31,8 +31,14 @@ BoxLite keeps boxes, images, and its database under its home directory, `~/.boxl
│ ├── extracted/ # Extracted layers
│ ├── disk-images/ # Ext4 disk images that box disks overlay
│ └── local/ # Caches for images loaded from local OCI bundles
-├── volumes/
-│ └── anonymous/ # Anonymous volumes the CLI creates
+├── volumes/ # Named local volumes and legacy anonymous binds
+│ ├── .registry.lock # Local volume metadata/payload lock
+│ ├── .staging/ # Unpublished volume creations (hidden from CRUD)
+│ ├── .trash/ # Logically removed payload awaiting cleanup
+│ ├── anonymous/ # Anonymous bind directories the CLI creates
+│ └── {volume-id}/ # Canonical UUID directory
+│ ├── .metadata.json # id, name, and UTC creation time
+│ └── _data/ # Payload exposed to boxes over virtio-fs
├── db/
│ └── boxlite.db # SQLite: boxes, images, base disks, snapshots
├── locks/ # Per-box lifecycle lock files
@@ -45,6 +51,13 @@ BoxLite keeps boxes, images, and its database under its home directory, `~/.boxl
└── .lock # Runtime lock file (prevents multiple instances)
```
+Named volumes keep resource identity outside `_data`, so guest writes cannot alter their own id or
+creation metadata. Box configuration stores only the canonical volume id and mount declaration, not
+the resolved host path. The path is resolved again on each start. Temporary and deleted operation
+directories are cleaned during runtime initialization and are not returned as volumes. A physical
+cleanup failure is logged and retried at the next initialization; it neither restores a logically
+removed volume nor prevents the runtime from opening.
+
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/sdks/c/include/boxlite.h b/sdks/c/include/boxlite.h
index 158f2366d..1c58ec145 100644
--- a/sdks/c/include/boxlite.h
+++ b/sdks/c/include/boxlite.h
@@ -1783,8 +1783,8 @@ void boxlite_options_add_bind_mount(CBoxliteOptions *opts,
// name — the server resolves either.
//
// `managed_volume` is the volume's id or name (`"my-data"`, `"vol_01K2…"`).
-// Managed volumes need a REST runtime; the local runtime has no volume backend
-// and rejects one at create.
+// LocalRuntime resolves managed volumes through `LocalVolumeStore`; REST
+// runtimes resolve them on the server.
//
// A NULL `opts`, `managed_volume`, or `guest_path` is ignored, matching
// [`boxlite_options_add_bind_mount`].
diff --git a/sdks/c/src/options.rs b/sdks/c/src/options.rs
index b18ab8665..a535ab423 100644
--- a/sdks/c/src/options.rs
+++ b/sdks/c/src/options.rs
@@ -211,8 +211,8 @@ pub unsafe extern "C" fn boxlite_options_add_bind_mount(
/// name — the server resolves either.
///
/// `managed_volume` is the volume's id or name (`"my-data"`, `"vol_01K2…"`).
-/// Managed volumes need a REST runtime; the local runtime has no volume backend
-/// and rejects one at create.
+/// LocalRuntime resolves managed volumes through `LocalVolumeStore`; REST
+/// runtimes resolve them on the server.
///
/// A NULL `opts`, `managed_volume`, or `guest_path` is ignored, matching
/// [`boxlite_options_add_bind_mount`].
diff --git a/sdks/go/options.go b/sdks/go/options.go
index 6f217e782..b9eb0ddce 100644
--- a/sdks/go/options.go
+++ b/sdks/go/options.go
@@ -364,8 +364,8 @@ func WithBindMountReadOnly(hostPath, guestPath string) BoxOption {
// managedVolume is the volume's server-assigned id or its name — the server
// resolves either.
//
-// Managed volumes need a REST runtime; the local runtime has no volume backend
-// and rejects one at create.
+// LocalRuntime resolves managed volumes through `LocalVolumeStore`; REST
+// runtimes resolve them on the server.
func WithManagedVolume(managedVolume, guestPath string) BoxOption {
return func(c *boxConfig) {
c.checkpointOverride = true
diff --git a/sdks/python/tests/test_local_volume.py b/sdks/python/tests/test_local_volume.py
new file mode 100644
index 000000000..1e0a3a133
--- /dev/null
+++ b/sdks/python/tests/test_local_volume.py
@@ -0,0 +1,83 @@
+from __future__ import annotations
+
+import os
+import uuid
+from contextlib import suppress
+
+import pytest
+
+import boxlite
+
+pytestmark = [pytest.mark.integration, pytest.mark.asyncio]
+
+
+async def test_local_volume_shared_by_boxes_clone_and_import(shared_runtime):
+ volume = await shared_runtime.volumes.create(name=f"sdk-{uuid.uuid4()}")
+ box = None
+ clone = None
+ imported = None
+ archive_path = os.path.join(os.sep, "tmp", f"{volume.id}.boxlite")
+ try:
+ box = await shared_runtime.create(
+ boxlite.BoxOptions(
+ image="alpine:latest",
+ volumes=[
+ {
+ "managed_volume": volume.name,
+ "guest_path": "/workspace",
+ "read_only": False,
+ }
+ ],
+ auto_delete=0,
+ detach=False,
+ )
+ )
+ execution = await box.exec(
+ "sh",
+ [
+ "-c",
+ "mkdir -p /workspace/team/backend; echo sdk-data > /workspace/team/backend/result.txt",
+ ],
+ )
+ result = await execution.wait()
+ assert result.exit_code == 0, result.stderr
+ archive = await box.export(dest=archive_path)
+ clone = await box.clone_box()
+ execution = await clone.exec("cat", ["/workspace/team/backend/result.txt"])
+ stdout = "".join([chunk async for chunk in execution.stdout()])
+ result = await execution.wait()
+ assert result.exit_code == 0, result.stderr
+ assert "sdk-data" in stdout
+ with pytest.raises(Exception, match="referenced"):
+ await shared_runtime.volumes.remove(volume.id)
+ await shared_runtime.remove(box.id, force=True)
+ box = None
+ with pytest.raises(Exception, match="referenced"):
+ await shared_runtime.volumes.remove(volume.id)
+ await shared_runtime.remove(clone.id, force=True)
+ clone = None
+ imported = await shared_runtime.import_box(archive)
+ execution = await imported.exec("cat", ["/workspace/team/backend/result.txt"])
+ stdout = "".join([chunk async for chunk in execution.stdout()])
+ result = await execution.wait()
+ assert result.exit_code == 0, result.stderr
+ assert "sdk-data" in stdout
+ with pytest.raises(Exception, match="referenced"):
+ await shared_runtime.volumes.remove(volume.id)
+ await shared_runtime.remove(imported.id, force=True)
+ imported = None
+ await shared_runtime.volumes.remove(volume.id)
+ finally:
+ for handle in (box, clone, imported):
+ if handle is not None:
+ with suppress(Exception):
+ await shared_runtime.remove(handle.id, force=True)
+ with suppress(Exception):
+ await shared_runtime.volumes.remove(volume.id)
+ try:
+ os.remove(archive_path)
+ except FileNotFoundError:
+ pass
+
+ with pytest.raises(boxlite.NotFoundError):
+ await shared_runtime.volumes.get(volume.id)
diff --git a/src/boxlite/src/db/boxes.rs b/src/boxlite/src/db/boxes.rs
index 3ebea1860..64ca1c3b2 100644
--- a/src/boxlite/src/db/boxes.rs
+++ b/src/boxlite/src/db/boxes.rs
@@ -14,6 +14,7 @@ use std::sync::{
atomic::{AtomicUsize, Ordering},
};
+use crate::BaseDiskID;
use crate::litebox::config::BoxConfig;
use crate::runtime::id::BoxID;
use crate::runtime::types::BoxState;
@@ -189,6 +190,24 @@ impl BoxStore {
/// Uses a transaction to ensure both inserts succeed or neither does.
/// Follows Podman pattern of explicit transactions for multi-statement operations.
pub fn save(&self, config: &BoxConfig, state: &BoxState) -> BoxliteResult<()> {
+ self.save_impl(config, state, None)
+ }
+
+ pub(crate) fn save_clone(
+ &self,
+ config: &BoxConfig,
+ state: &BoxState,
+ base_disk_id: &BaseDiskID,
+ ) -> BoxliteResult<()> {
+ self.save_impl(config, state, Some(base_disk_id))
+ }
+
+ fn save_impl(
+ &self,
+ config: &BoxConfig,
+ state: &BoxState,
+ base_disk_id: Option<&BaseDiskID>,
+ ) -> BoxliteResult<()> {
let mut conn = self.db.conn();
let tx = db_err!(conn.transaction())?;
@@ -217,6 +236,14 @@ impl BoxStore {
params![config.id, state.status.as_str(), state.pid, state_json],
))?;
+ // A clone and its backing-disk dependency become visible together.
+ if let Some(base_disk_id) = base_disk_id {
+ db_err!(tx.execute(
+ "INSERT INTO base_disk_ref (base_disk_id, box_id) VALUES (?1, ?2)",
+ params![base_disk_id, config.id],
+ ))?;
+ }
+
// Commit transaction
db_err!(tx.commit())?;
@@ -235,6 +262,22 @@ impl BoxStore {
}
}
+ /// List every persisted box configuration without requiring a state row.
+ pub fn list_configs(&self) -> BoxliteResult<Vec<BoxConfig>> {
+ let conn = self.db.conn();
+ let mut stmt = db_err!(conn.prepare("SELECT json FROM box_config"))?;
+ let rows = db_err!(stmt.query_map([], |row| row.get::<_, String>(0)))?;
+ let mut configs = Vec::new();
+ for row in rows {
+ let json = db_err!(row)?;
+ let config = serde_json::from_str(&json).map_err(|error| {
+ BoxliteError::Database(format!("Failed to deserialize config: {error}"))
+ })?;
+ configs.push(config);
+ }
+ Ok(configs)
+ }
+
/// List all boxes as (config, state) pairs.
///
/// Returns boxes sorted by creation time (newest first).
diff --git a/src/boxlite/src/litebox/archive.rs b/src/boxlite/src/litebox/archive.rs
index 49d8e85e2..c00cc6995 100644
--- a/src/boxlite/src/litebox/archive.rs
+++ b/src/boxlite/src/litebox/archive.rs
@@ -37,16 +37,27 @@ pub(crate) const PUBLISHED_PORTS_ARCHIVE_VERSION: u32 = 5;
/// Older importers must refuse fractional CPUs they cannot enforce.
pub(crate) const FRACTIONAL_CPUS_ARCHIVE_VERSION: u32 = 6;
+/// Managed and typed mounts require a local volume-capable importer.
+pub(crate) const MANAGED_MOUNTS_ARCHIVE_VERSION: u32 = 7;
+
/// Maximum archive version this build can import.
-pub(crate) const MAX_SUPPORTED_VERSION: u32 = FRACTIONAL_CPUS_ARCHIVE_VERSION;
+pub(crate) const MAX_SUPPORTED_VERSION: u32 = MANAGED_MOUNTS_ARCHIVE_VERSION;
/// Pick the archive format an exported box needs.
///
/// Use the oldest format that can represent all configured policies.
/// An explicitly empty capability policy still requires v4; ports require v5,
-/// and fractional CPUs require v6 so older readers cannot silently discard them.
+/// fractional CPUs require v6, and managed/typed mounts require v7 so older
+/// readers cannot silently discard or defer them until boot fails.
pub(crate) fn archive_version_for_options(options: &crate::runtime::options::BoxOptions) -> u32 {
- if options
+ if !options.mounts.is_empty()
+ || options
+ .volumes
+ .iter()
+ .any(|mount| mount.managed_volume.is_some())
+ {
+ MANAGED_MOUNTS_ARCHIVE_VERSION
+ } else if options
.cpu_count()
.is_ok_and(|cpu| cpu.is_some_and(|cpu| cpu.is_fractional()))
{
@@ -68,9 +79,10 @@ pub(crate) fn archive_version_for_options(options: &crate::runtime::options::Box
/// v4: `box_options.advanced` carries a custom capability policy
/// v5: `ports` carry publication semantics (automatic host port, bind IP)
/// v6: fractional `box_options.cpus` requires host CPU bandwidth enforcement
+/// v7: managed/typed mounts require local volume-capable resolution
#[derive(Debug, Serialize, Deserialize)]
pub struct ArchiveManifest {
- /// Archive format version (1 through 6).
+ /// Archive format version (1 through 7).
pub version: u32,
/// Original box name (optional, may be renamed on import).
pub box_name: Option<String>,
@@ -409,6 +421,28 @@ mod tests {
}
}
+ #[test]
+ fn managed_mounts_require_archive_v7() {
+ use crate::runtime::options::{MountSpec, VolumeSpec};
+
+ let legacy = crate::runtime::options::BoxOptions {
+ volumes: vec![VolumeSpec::managed_volume("workspace", "/workspace")],
+ ..Default::default()
+ };
+ assert_eq!(archive_version_for_options(&legacy), 7);
+
+ for mount in [
+ MountSpec::volume_mount("workspace", "/workspace"),
+ MountSpec::bind_mount("/srv/data", "/data"),
+ ] {
+ let options = crate::runtime::options::BoxOptions {
+ mounts: vec![mount],
+ ..Default::default()
+ };
+ assert_eq!(archive_version_for_options(&options), 7);
+ }
+ }
+
/// Regression: the export stamp and the importer's canonicalization window
/// have to agree. When they drift, a box exported by this build re-imports
/// through `normalize_legacy_ports`, which clears `host_ip` — turning a
diff --git a/src/boxlite/src/litebox/clone_export.rs b/src/boxlite/src/litebox/clone_export.rs
index f6b3e5d39..266d7cb1e 100644
--- a/src/boxlite/src/litebox/clone_export.rs
+++ b/src/boxlite/src/litebox/clone_export.rs
@@ -48,7 +48,7 @@ impl BoxImpl {
/// Three-phase flow (snapshot-as-base):
/// A. Inside quiesce bracket (VM paused): create disk layer (rename + COW child).
/// B. Outside quiesce bracket (VM resumed): create N thin overlay headers.
- /// C. Provision each clone and increment layer ref count.
+ /// C. Provision each clone atomically with its layer dependency.
pub(crate) async fn clone_boxes(
&self,
_options: crate::runtime::options::CloneOptions,
@@ -68,7 +68,10 @@ impl BoxImpl {
}
let t0 = Instant::now();
- self.with_disk_admission(async {
+ let source_admission =
+ Arc::new(crate::lock::OwnedLockGuard::new_async(self.disk_locker()?).await);
+ self.ensure_box_exists()?;
+ (async {
let rt = Arc::clone(&self.runtime);
let src_disks = self.config.box_home.join("disks");
let src_container = src_disks.join(disk_filenames::CONTAINER_DISK);
@@ -132,7 +135,7 @@ impl BoxImpl {
// Phase C: Provision each clone and record base disk refs.
// Each clone's disk is a copy of this one, so it runs the same build.
- // Read before the loop: the guard must not be held across an await.
+ // Read before the loop: the state lock must not be held across an await.
let resolved_image = self.state.read().resolved_image.clone();
let copy_options = self.options_for_copy()?;
let mut clones = Vec::with_capacity(count);
@@ -146,23 +149,13 @@ impl BoxImpl {
copy_options.clone(),
BoxStatus::Stopped,
resolved_image.clone(),
+ Some(crate::runtime::rt_impl::CloneDependency {
+ base_disk_id: layer.id.clone(),
+ source_admission: Arc::clone(&source_admission),
+ }),
)
.await?;
- // Record that this clone depends on the shared base disk.
- if let Err(e) = rt
- .base_disk_mgr
- .store()
- .add_ref(&layer.id, litebox.id().as_ref())
- {
- tracing::warn!(
- clone_id = %litebox.id(),
- base_disk_id = %layer.id,
- error = %e,
- "Failed to record base disk ref for clone"
- );
- }
-
clones.push(litebox);
}
diff --git a/src/boxlite/src/litebox/init/tasks/guest_init.rs b/src/boxlite/src/litebox/init/tasks/guest_init.rs
index 5469f3b46..c54831205 100644
--- a/src/boxlite/src/litebox/init/tasks/guest_init.rs
+++ b/src/boxlite/src/litebox/init/tasks/guest_init.rs
@@ -140,6 +140,15 @@ impl PipelineTask<InitCtx> for GuestInitTask {
}
}
+fn requires_safe_volume_sub_path(mounts: &[crate::volumes::ContainerMount]) -> bool {
+ mounts.iter().any(|mount| {
+ matches!(
+ mount.payload,
+ crate::volumes::ContainerMountPayload::ManagedSubDirectory { .. }
+ )
+ })
+}
+
/// Initialize the guest and create the container (init is *not* run here).
async fn run_guest_init(
guest_session: GuestSession,
@@ -169,6 +178,9 @@ async fn run_guest_init(
.require_min_version(MIN_DEVICE_GUEST_VERSION)
.await?;
}
+ if requires_safe_volume_sub_path(&bootstrap.container.mounts) {
+ guest_interface.require_safe_volume_sub_path().await?;
+ }
guest_interface.init(bootstrap.guest).await?;
tracing::info!("Guest initialized successfully");
@@ -218,6 +230,7 @@ fn kvm_device() -> ContainerDevice {
#[cfg(test)]
mod tests {
use super::*;
+ use std::sync::Arc;
fn limits_for(cpus: Option<f64>, memory_mib: Option<u32>, cap: Option<u64>) -> (i64, u64, i64) {
let mut options = BoxOptions {
@@ -264,4 +277,198 @@ mod tests {
"privileged floor {MIN_PRIVILEGED_CONTAINER_GUEST_VERSION:?} is newer than the capability floor {MIN_CAPABILITY_GUEST_VERSION:?}"
);
}
+
+ #[test]
+ fn managed_sub_directories_require_a_safe_guest_before_init() {
+ let mount = |payload| crate::volumes::ContainerMount {
+ volume_name: "uservol0".to_string(),
+ destination: "/data".to_string(),
+ read_only: true,
+ owner_uid: 0,
+ owner_gid: 0,
+ payload,
+ };
+ let managed = mount(crate::volumes::ContainerMountPayload::ManagedSubDirectory {
+ sub_path: "team/backend".to_string(),
+ });
+ assert!(requires_safe_volume_sub_path(&[managed]));
+ assert!(!requires_safe_volume_sub_path(&[
+ mount(crate::volumes::ContainerMountPayload::WholeDirectory),
+ mount(crate::volumes::ContainerMountPayload::SingleFile {
+ file_name: "app.conf".to_string(),
+ }),
+ ]));
+ }
+
+ #[derive(Clone)]
+ struct VersionedGuest {
+ version: &'static str,
+ safe_managed_volume_sub_path: bool,
+ guest_init_calls: Arc<std::sync::Mutex<usize>>,
+ container_init_calls: Arc<std::sync::Mutex<usize>>,
+ }
+
+ #[tonic::async_trait]
+ impl boxlite_shared::Guest for VersionedGuest {
+ async fn init(
+ &self,
+ _: tonic::Request<boxlite_shared::GuestInitRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::GuestInitResponse>, tonic::Status> {
+ *self.guest_init_calls.lock().unwrap() += 1;
+ Ok(tonic::Response::new(boxlite_shared::GuestInitResponse {
+ result: Some(boxlite_shared::guest_init_response::Result::Success(
+ boxlite_shared::GuestInitSuccess {},
+ )),
+ }))
+ }
+
+ async fn ping(
+ &self,
+ _: tonic::Request<boxlite_shared::PingRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::PingResponse>, tonic::Status> {
+ Ok(tonic::Response::new(boxlite_shared::PingResponse {
+ version: self.version.to_string(),
+ safe_managed_volume_sub_path: self.safe_managed_volume_sub_path,
+ }))
+ }
+
+ async fn shutdown(
+ &self,
+ _: tonic::Request<boxlite_shared::ShutdownRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::ShutdownResponse>, tonic::Status> {
+ Ok(tonic::Response::new(boxlite_shared::ShutdownResponse {}))
+ }
+
+ async fn quiesce(
+ &self,
+ _: tonic::Request<boxlite_shared::QuiesceRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::QuiesceResponse>, tonic::Status> {
+ Ok(tonic::Response::new(boxlite_shared::QuiesceResponse {
+ frozen_count: 0,
+ }))
+ }
+
+ async fn thaw(
+ &self,
+ _: tonic::Request<boxlite_shared::ThawRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::ThawResponse>, tonic::Status> {
+ Ok(tonic::Response::new(boxlite_shared::ThawResponse {
+ thawed_count: 0,
+ }))
+ }
+ }
+
+ #[tonic::async_trait]
+ impl boxlite_shared::Container for VersionedGuest {
+ async fn init(
+ &self,
+ request: tonic::Request<boxlite_shared::ContainerInitRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::ContainerInitResponse>, tonic::Status> {
+ *self.container_init_calls.lock().unwrap() += 1;
+ let container_id = request.into_inner().container_id;
+ Ok(tonic::Response::new(
+ boxlite_shared::ContainerInitResponse {
+ result: Some(boxlite_shared::container_init_response::Result::Success(
+ boxlite_shared::ContainerInitSuccess { container_id },
+ )),
+ },
+ ))
+ }
+
+ async fn start(
+ &self,
+ _: tonic::Request<boxlite_shared::ContainerStartRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::ContainerStartResponse>, tonic::Status>
+ {
+ Err(tonic::Status::unimplemented("not used by these tests"))
+ }
+
+ async fn mount(
+ &self,
+ _: tonic::Request<boxlite_shared::ContainerMountRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::ContainerMountResponse>, tonic::Status>
+ {
+ Err(tonic::Status::unimplemented("not used by these tests"))
+ }
+ }
+
+ fn bootstrap_for_version_gate() -> GuestBootstrapConfig {
+ GuestBootstrapConfig {
+ guest: GuestInitConfig {
+ volumes: vec![],
+ network: None,
+ },
+ container: crate::portal::interfaces::ContainerInitConfig {
+ container_id: "container-1".to_string(),
+ image: crate::images::ContainerImageConfig::default(),
+ rootfs: crate::portal::interfaces::ContainerRootfsInitConfig::Merged,
+ mounts: vec![crate::volumes::ContainerMount {
+ volume_name: "uservol0".to_string(),
+ destination: "/data".to_string(),
+ read_only: true,
+ owner_uid: 0,
+ owner_gid: 0,
+ payload: crate::volumes::ContainerMountPayload::ManagedSubDirectory {
+ sub_path: "team/backend".to_string(),
+ },
+ }],
+ ca_certs: vec![],
+ tty: false,
+ devices: vec![],
+ resources: ContainerResources::default(),
+ advanced: Default::default(),
+ },
+ }
+ }
+
+ async fn run_with_guest_version(
+ version: &'static str,
+ safe_managed_volume_sub_path: bool,
+ ) -> (BoxliteResult<()>, usize, usize) {
+ let guest_init_calls = Arc::new(std::sync::Mutex::new(0));
+ let container_init_calls = Arc::new(std::sync::Mutex::new(0));
+ let guest = VersionedGuest {
+ version,
+ safe_managed_volume_sub_path,
+ guest_init_calls: Arc::clone(&guest_init_calls),
+ container_init_calls: Arc::clone(&container_init_calls),
+ };
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ drop(listener);
+ tokio::spawn(async move {
+ tonic::transport::Server::builder()
+ .add_service(boxlite_shared::GuestServer::new(guest.clone()))
+ .add_service(boxlite_shared::ContainerServer::new(guest))
+ .serve(addr)
+ .await
+ .unwrap();
+ });
+ for _ in 0..100 {
+ if tokio::net::TcpStream::connect(addr).await.is_ok() {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+
+ let result = run_guest_init(
+ crate::portal::GuestSession::new(boxlite_shared::BoxTransport::tcp(addr.port())),
+ bootstrap_for_version_gate(),
+ )
+ .await;
+ let guest_calls = *guest_init_calls.lock().unwrap();
+ let container_calls = *container_init_calls.lock().unwrap();
+ (result, guest_calls, container_calls)
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn run_guest_init_requires_safe_subpath_capability_before_any_init() {
+ let (result, guest_calls, container_calls) = run_with_guest_version("0.14.0", false).await;
+ assert!(matches!(result, Err(BoxliteError::Unsupported(_))));
+ assert_eq!((guest_calls, container_calls), (0, 0));
+
+ let (result, guest_calls, container_calls) = run_with_guest_version("0.14.0", true).await;
+ result.unwrap();
+ assert_eq!((guest_calls, container_calls), (1, 1));
+ }
}
diff --git a/src/boxlite/src/litebox/init/tasks/vmm_spawn.rs b/src/boxlite/src/litebox/init/tasks/vmm_spawn.rs
index 183a3ada1..645580f5a 100644
--- a/src/boxlite/src/litebox/init/tasks/vmm_spawn.rs
+++ b/src/boxlite/src/litebox/init/tasks/vmm_spawn.rs
@@ -152,7 +152,19 @@ async fn build_config(
let transport = BoxTransport::unix(layout.socket_path());
let ready_transport = BoxTransport::unix(layout.ready_socket_path());
- let user_volumes = resolve_user_volumes(&options.volumes)?;
+ let local_volume_store = runtime.local_volume_store.clone();
+ let volume_options = options.clone();
+ // Volume resolution does file IO and takes filesystem locks, so keep it
+ // off Tokio's async worker threads.
+ let user_volumes = tokio::task::spawn_blocking(move || {
+ resolve_user_volumes(
+ &volume_options.volumes,
+ &volume_options.mounts,
+ &local_volume_store,
+ )
+ })
+ .await
+ .map_err(|error| BoxliteError::Internal(format!("volume resolution task failed: {error}")))??;
// Prepare container directories (image/, rw/, rootfs/)
let container_layout = layout.shared_layout().container(container_id.as_str());
@@ -192,16 +204,34 @@ async fn build_config(
// Add user volumes via ContainerVolumeManager
let mut container_mgr = ContainerVolumeManager::new(&mut volume_mgr);
for vol in &user_volumes {
- // Single-file volume: stage the file into a dedicated dir under the box's
- // shared tree (already granted to the VMM sandbox) and share that dir, so
- // virtio-fs never exposes the file's host siblings. Directories share as-is.
- let share_dir = match &vol.subpath {
- None => vol.host_path.clone(),
- Some(file_name) => {
+ // The share directory and payload describe one resolved mount kind.
+ // Single files get an isolated staged directory; managed subdirectories
+ // stay inside the volume payload and are pinned by the guest.
+ let (share_dir, payload) = match &vol.kind {
+ crate::litebox::init::types::ResolvedShareKind::Directory => (
+ vol.host_path.clone(),
+ crate::volumes::ContainerMountPayload::WholeDirectory,
+ ),
+ crate::litebox::init::types::ResolvedShareKind::SingleFile { file_name } => {
let staging_dir = layout.shared_dir().join("user-volumes").join(&vol.tag);
stage_single_file(&staging_dir, &vol.host_path, file_name, vol.read_only)?;
- staging_dir
+ (
+ staging_dir,
+ crate::volumes::ContainerMountPayload::SingleFile {
+ file_name: file_name.clone(),
+ },
+ )
}
+ crate::litebox::init::types::ResolvedShareKind::ManagedDirectory => (
+ vol.host_path.clone(),
+ crate::volumes::ContainerMountPayload::WholeDirectory,
+ ),
+ crate::litebox::init::types::ResolvedShareKind::ManagedSubDirectory { sub_path } => (
+ vol.host_path.clone(),
+ crate::volumes::ContainerMountPayload::ManagedSubDirectory {
+ sub_path: sub_path.clone(),
+ },
+ ),
};
container_mgr.add_volume(
container_id.as_str(),
@@ -212,7 +242,7 @@ async fn build_config(
vol.read_only,
vol.owner_uid,
vol.owner_gid,
- vol.subpath.clone(),
+ payload,
);
}
let container_mounts = container_mgr.build_container_mounts();
@@ -241,6 +271,21 @@ async fn build_config(
build_network_backend(options, layout, runtime, outbound_policy.as_ref())?;
let network_backend_spec = network_backend.as_ref().map(|backend| backend.spec());
+ let volume_access = user_volumes
+ .iter()
+ .filter(|volume| {
+ matches!(
+ volume.kind,
+ crate::litebox::init::types::ResolvedShareKind::ManagedDirectory
+ | crate::litebox::init::types::ResolvedShareKind::ManagedSubDirectory { .. }
+ )
+ })
+ .map(|volume| crate::jailer::PathAccess {
+ path: volume.host_path.clone(),
+ writable: !volume.read_only,
+ })
+ .collect();
+
// Assemble VMM instance spec
let instance_spec = InstanceSpec {
engine: *engine_kind,
@@ -254,6 +299,7 @@ async fn build_config(
kernel: prepared_kernel.clone(),
// Filesystem and devices
fs_shares: vmm_config.fs_shares,
+ volume_access,
block_devices: vmm_config.block_devices,
guest_entrypoint,
transport: transport.clone(),
diff --git a/src/boxlite/src/litebox/init/types.rs b/src/boxlite/src/litebox/init/types.rs
index 9769313f2..5bdb6fc7d 100644
--- a/src/boxlite/src/litebox/init/types.rs
+++ b/src/boxlite/src/litebox/init/types.rs
@@ -10,7 +10,7 @@ use crate::litebox::ports::LivePublishedPorts;
use crate::portal::GuestSession;
use crate::portal::interfaces::ContainerRootfsInitConfig;
use crate::runtime::layout::BoxFilesystemLayout;
-use crate::runtime::options::VolumeSpec;
+use crate::runtime::options::{MountSpec, VolumeSpec};
use crate::runtime::rt_impl::SharedRuntimeImpl;
use crate::vmm::{PreparedKernel, controller::VmmHandler};
use crate::volumes::{ContainerMount, GuestVolumeManager, VolumeShare, classify_volume_share};
@@ -31,6 +31,14 @@ pub const USE_OVERLAYFS: bool = true;
/// When enabled, USE_OVERLAYFS is ignored.
pub const USE_DISK_ROOTFS: bool = true;
+#[derive(Debug, Clone)]
+pub enum ResolvedShareKind {
+ Directory,
+ SingleFile { file_name: String },
+ ManagedDirectory,
+ ManagedSubDirectory { sub_path: String },
+}
+
/// User-specified volume with resolved paths and generated tag.
#[derive(Debug, Clone)]
pub struct ResolvedVolume {
@@ -42,25 +50,68 @@ pub struct ResolvedVolume {
pub owner_uid: u32,
/// Owner GID of host directory (for auto-idmap in guest).
pub owner_gid: u32,
- /// For a single-file mount, the file's name (staged and bind-mounted on its
- /// own); `None` for a whole-directory mount.
- pub subpath: Option<String>,
+ pub kind: ResolvedShareKind,
}
-pub fn resolve_user_volumes(volumes: &[VolumeSpec]) -> BoxliteResult<Vec<ResolvedVolume>> {
- let mut resolved = Vec::with_capacity(volumes.len());
+fn managed_share_kind(mount: &crate::volumes::ResolvedLocalMount) -> ResolvedShareKind {
+ match &mount.payload {
+ crate::volumes::ResolvedLocalMountPayload::WholeVolume => {
+ ResolvedShareKind::ManagedDirectory
+ }
+ crate::volumes::ResolvedLocalMountPayload::SubDirectory { path } => {
+ ResolvedShareKind::ManagedSubDirectory {
+ sub_path: path.clone(),
+ }
+ }
+ }
+}
+
+fn managed_owner_path(kind: &ResolvedShareKind, resolved_path: &std::path::Path) -> PathBuf {
+ match kind {
+ ResolvedShareKind::ManagedSubDirectory { sub_path } => resolved_path.join(sub_path),
+ _ => resolved_path.to_path_buf(),
+ }
+}
+
+pub fn resolve_user_volumes(
+ volumes: &[VolumeSpec],
+ mounts: &[MountSpec],
+ store: &crate::volumes::LocalVolumeStore,
+) -> BoxliteResult<Vec<ResolvedVolume>> {
+ let options = crate::runtime::options::BoxOptions {
+ volumes: volumes.to_vec(),
+ mounts: mounts.to_vec(),
+ ..Default::default()
+ };
+ let managed = store.resolve_for_boot(&options)?;
+ let mut managed_by_id: std::collections::HashMap<_, _> = managed
+ .into_iter()
+ .map(|mount| (mount.volume_id.clone(), mount))
+ .collect();
+ let mut resolved = Vec::with_capacity(volumes.len() + mounts.len());
for (i, vol) in volumes.iter().enumerate() {
- // Managed volumes live on the server that owns the volume backend.
- // Without this the reference falls through to the host-path checks
- // below and surfaces as "host path does not exist: my-data", which
- // points the caller at their own filesystem instead of at the
- // runtime they used.
- if let Some(reference) = &vol.managed_volume {
- return Err(BoxliteError::Unsupported(format!(
- "managed volume {reference:?} requires a REST runtime; the local runtime has no \
- volume backend to resolve it against"
- )));
+ if let Some(selector) = &vol.managed_volume {
+ let mount = managed_by_id.remove(selector).ok_or_else(|| {
+ BoxliteError::Internal(format!("volume {selector} was not resolved for boot"))
+ })?;
+ let kind = managed_share_kind(&mount);
+ let resolved_path = mount.payload_root;
+ let owner_path = managed_owner_path(&kind, &resolved_path);
+ let metadata = std::fs::metadata(&owner_path).map_err(|error| {
+ BoxliteError::Config(format!("Failed to stat managed volume {selector}: {error}"))
+ })?;
+ use std::os::unix::fs::MetadataExt;
+ resolved.push(ResolvedVolume {
+ tag: format!("uservol{i}"),
+ host_path: resolved_path,
+ guest_path: mount.target,
+ read_only: mount.read_only,
+ owner_uid: metadata.uid(),
+ owner_gid: metadata.gid(),
+ kind,
+ });
+ continue;
}
let host_path = PathBuf::from(&vol.host_path);
@@ -82,9 +133,12 @@ pub fn resolve_user_volumes(volumes: &[VolumeSpec]) -> BoxliteResult<Vec<Resolve
// A directory is shared as-is; a single file keeps its own path here and
// is staged into a dedicated share dir later (see vmm_spawn), so virtio-fs
// never exposes the file's host siblings.
- let (source_path, subpath) = match classify_volume_share(&resolved_path) {
- Some(VolumeShare::Dir(dir)) => (dir, None),
- Some(VolumeShare::File(name)) => (resolved_path.clone(), Some(name)),
+ let (source_path, kind) = match classify_volume_share(&resolved_path) {
+ Some(VolumeShare::Dir(dir)) => (dir, ResolvedShareKind::Directory),
+ Some(VolumeShare::File(file_name)) => (
+ resolved_path.clone(),
+ ResolvedShareKind::SingleFile { file_name },
+ ),
None => {
return Err(BoxliteError::Config(format!(
"Volume host path is not a file or directory: {}",
@@ -111,7 +165,6 @@ pub fn resolve_user_volumes(volumes: &[VolumeSpec]) -> BoxliteResult<Vec<Resolve
tracing::debug!(
tag = %tag,
host_path = %source_path.display(),
- subpath = ?subpath,
guest_path = %vol.guest_path,
read_only = vol.read_only,
owner_uid,
@@ -126,10 +179,54 @@ pub fn resolve_user_volumes(volumes: &[VolumeSpec]) -> BoxliteResult<Vec<Resolve
read_only: vol.read_only,
owner_uid,
owner_gid,
- subpath,
+ kind,
});
}
+ for (i, mount) in mounts.iter().enumerate() {
+ let source = mount.source.as_deref().ok_or_else(|| {
+ BoxliteError::InvalidArgument(format!("mount to {:?} has no source", mount.target))
+ })?;
+ match mount.mount_type {
+ crate::runtime::options::MountType::Volume => {
+ let managed = managed_by_id.remove(source).ok_or_else(|| {
+ BoxliteError::Internal(format!("volume {source} was not resolved for boot"))
+ })?;
+ let kind = managed_share_kind(&managed);
+ let resolved_path = managed.payload_root;
+ let owner_path = managed_owner_path(&kind, &resolved_path);
+ let metadata = std::fs::metadata(&owner_path).map_err(|error| {
+ BoxliteError::Config(format!(
+ "Failed to stat volume path '{}': {error}",
+ resolved_path.display()
+ ))
+ })?;
+ use std::os::unix::fs::MetadataExt;
+ resolved.push(ResolvedVolume {
+ tag: format!("uservol{i}"),
+ host_path: resolved_path,
+ guest_path: managed.target,
+ read_only: managed.read_only,
+ owner_uid: metadata.uid(),
+ owner_gid: metadata.gid(),
+ kind,
+ });
+ }
+ crate::runtime::options::MountType::Bind => {
+ let bind = VolumeSpec {
+ managed_volume: None,
+ host_path: source.to_owned(),
+ guest_path: mount.target.clone(),
+ read_only: mount.read_only,
+ };
+ resolved.extend(resolve_user_volumes(&[bind], &[], store)?);
+ }
+ }
+ }
+ for (index, volume) in resolved.iter_mut().enumerate() {
+ volume.tag = format!("uservol{index}");
+ }
+
Ok(resolved)
}
@@ -393,8 +490,15 @@ mod tests {
guest_path: "/data".to_string(),
read_only: false,
}];
+ let runtime = crate::runtime::rt_impl::RuntimeImpl::new_for_test(
+ crate::runtime::options::BoxliteOptions {
+ home_dir: tmp.path().to_path_buf(),
+ ..Default::default()
+ },
+ )
+ .unwrap();
- let resolved = resolve_user_volumes(&volumes).unwrap();
+ let resolved = resolve_user_volumes(&volumes, &[], &runtime.local_volume_store).unwrap();
assert_eq!(resolved.len(), 1);
// owner_uid should be the current user's UID
@@ -405,38 +509,205 @@ mod tests {
assert_eq!(resolved[0].owner_uid, expected_uid);
assert_eq!(resolved[0].owner_gid, expected_gid);
assert_eq!(resolved[0].tag, "uservol0");
- assert_eq!(resolved[0].subpath, None);
+ assert!(matches!(resolved[0].kind, ResolvedShareKind::Directory));
}
#[test]
fn resolve_volume_nonexistent_path_errors() {
+ let tmp = tempfile::tempdir().unwrap();
+ let runtime = crate::runtime::rt_impl::RuntimeImpl::new_for_test(
+ crate::runtime::options::BoxliteOptions {
+ home_dir: tmp.path().to_path_buf(),
+ ..Default::default()
+ },
+ )
+ .unwrap();
let volumes = vec![VolumeSpec::bind_mount("/nonexistent/path/12345", "/data")];
- let result = resolve_user_volumes(&volumes);
+ let result = resolve_user_volumes(&volumes, &[], &runtime.local_volume_store);
assert!(result.is_err());
}
- /// The local runtime has no volume backend, so a managed volume has to say
- /// so. Without the guard the reference falls through to the host-path
- /// checks and reports "host path does not exist: my-data", which sends the
- /// caller looking for a directory they never asked for.
#[test]
- fn resolve_managed_volume_reports_the_missing_backend() {
- let volumes = vec![VolumeSpec::managed_volume("my-data", "/data")];
+ fn resolve_typed_bind_directory_uses_host_resolution() {
+ let tmp = tempfile::tempdir().unwrap();
+ let runtime = crate::runtime::rt_impl::RuntimeImpl::new_for_test(
+ crate::runtime::options::BoxliteOptions {
+ home_dir: tmp.path().to_path_buf(),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let mount = crate::runtime::options::MountSpec {
+ read_only: true,
+ ..crate::runtime::options::MountSpec::bind_mount(
+ tmp.path().to_string_lossy().to_string(),
+ "/data",
+ )
+ };
- let error = resolve_user_volumes(&volumes)
- .expect_err("the local runtime cannot resolve a managed volume");
+ let resolved = resolve_user_volumes(&[], &[mount], &runtime.local_volume_store).unwrap();
+ assert_eq!(resolved.len(), 1);
+ assert_eq!(resolved[0].host_path, tmp.path().canonicalize().unwrap());
+ assert_eq!(resolved[0].guest_path, "/data");
+ assert!(resolved[0].read_only);
+ assert_eq!(resolved[0].tag, "uservol0");
+ assert!(matches!(resolved[0].kind, ResolvedShareKind::Directory));
+ }
- assert!(
- matches!(error, BoxliteError::Unsupported(_)),
- "{error:?} should be Unsupported, not a config error about a path"
+ #[test]
+ fn resolve_typed_bind_single_file_preserves_file_name() {
+ let tmp = tempfile::tempdir().unwrap();
+ let file_path = tmp.path().join("app.conf");
+ std::fs::write(&file_path, b"key=value\n").unwrap();
+ let runtime = crate::runtime::rt_impl::RuntimeImpl::new_for_test(
+ crate::runtime::options::BoxliteOptions {
+ home_dir: tmp.path().to_path_buf(),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let mount = crate::runtime::options::MountSpec::bind_mount(
+ file_path.to_string_lossy().to_string(),
+ "/etc/app.conf",
);
- let message = error.to_string();
- assert!(message.contains("my-data"), "{message}");
- assert!(message.contains("REST runtime"), "{message}");
- assert!(
- !message.contains("host path"),
- "the error must not blame a host path: {message}"
+
+ let resolved = resolve_user_volumes(&[], &[mount], &runtime.local_volume_store).unwrap();
+ assert_eq!(resolved.len(), 1);
+ assert_eq!(resolved[0].host_path, file_path.canonicalize().unwrap());
+ assert_eq!(resolved[0].guest_path, "/etc/app.conf");
+ assert_eq!(resolved[0].tag, "uservol0");
+ assert!(matches!(
+ resolved[0].kind,
+ ResolvedShareKind::SingleFile { ref file_name } if file_name == "app.conf"
+ ));
+ }
+
+ #[test]
+ fn resolve_managed_volume_uses_the_local_store() {
+ let tmp = tempfile::tempdir().unwrap();
+ let runtime = crate::runtime::rt_impl::RuntimeImpl::new_for_test(
+ crate::runtime::options::BoxliteOptions {
+ home_dir: tmp.path().to_path_buf(),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let volume = runtime.local_volume_store.create(Some("my-data")).unwrap();
+ let options = crate::runtime::options::BoxOptions {
+ volumes: vec![VolumeSpec::managed_volume(&volume.id, "/data")],
+ ..Default::default()
+ };
+
+ let resolved = resolve_user_volumes(
+ &options.volumes,
+ &options.mounts,
+ &runtime.local_volume_store,
+ )
+ .expect("resolve a managed volume through the local store");
+ assert_eq!(resolved.len(), 1);
+ assert_eq!(resolved[0].guest_path, "/data");
+ let expected = runtime
+ .layout
+ .volumes_dir()
+ .canonicalize()
+ .unwrap()
+ .join(&volume.id)
+ .join("_data");
+ assert_eq!(resolved[0].host_path, expected);
+ assert!(matches!(
+ resolved[0].kind,
+ ResolvedShareKind::ManagedDirectory
+ ));
+ }
+
+ #[test]
+ fn resolve_typed_mount_subdirectory_records_the_payload_kind() {
+ let tmp = tempfile::tempdir().unwrap();
+ let runtime = crate::runtime::rt_impl::RuntimeImpl::new_for_test(
+ crate::runtime::options::BoxliteOptions {
+ home_dir: tmp.path().to_path_buf(),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ std::fs::create_dir_all(
+ runtime
+ .layout
+ .volumes_dir()
+ .join(&volume.id)
+ .join("_data")
+ .join("team/backend"),
+ )
+ .unwrap();
+ let mount = crate::runtime::options::MountSpec {
+ sub_path: Some("team/backend".to_string()),
+ ..crate::runtime::options::MountSpec::volume_mount(&volume.id, "/workspace")
+ };
+
+ let resolved = resolve_user_volumes(&[], &[mount], &runtime.local_volume_store).unwrap();
+ assert!(matches!(
+ resolved[0].kind,
+ ResolvedShareKind::ManagedSubDirectory { ref sub_path }
+ if sub_path == "team/backend"
+ ));
+ }
+
+ #[test]
+ fn resolve_typed_mount_subdirectory_uses_the_selected_directory_owner() {
+ use std::os::unix::fs::MetadataExt;
+
+ let tmp = tempfile::tempdir().unwrap();
+ let runtime = crate::runtime::rt_impl::RuntimeImpl::new_for_test(
+ crate::runtime::options::BoxliteOptions {
+ home_dir: tmp.path().to_path_buf(),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ let payload = runtime.layout.volumes_dir().join(&volume.id).join("_data");
+ let subdirectory = payload.join("team/backend");
+ std::fs::create_dir_all(&subdirectory).unwrap();
+ let mount = crate::runtime::options::MountSpec {
+ sub_path: Some("team/backend".to_string()),
+ ..crate::runtime::options::MountSpec::volume_mount(&volume.id, "/workspace")
+ };
+
+ let resolved = resolve_user_volumes(
+ &[],
+ std::slice::from_ref(&mount),
+ &runtime.local_volume_store,
+ )
+ .unwrap();
+ assert_eq!(
+ managed_owner_path(&resolved[0].kind, &resolved[0].host_path),
+ subdirectory.canonicalize().unwrap()
+ );
+ assert_eq!(
+ resolved[0].owner_gid,
+ std::fs::metadata(&subdirectory).unwrap().gid()
+ );
+
+ let whole = crate::runtime::options::MountSpec {
+ sub_path: None,
+ ..mount
+ };
+ let resolved = resolve_user_volumes(&[], &[whole], &runtime.local_volume_store).unwrap();
+ assert_eq!(
+ managed_owner_path(&resolved[0].kind, &resolved[0].host_path),
+ payload.canonicalize().unwrap()
+ );
+ assert_eq!(
+ resolved[0].owner_gid,
+ std::fs::metadata(payload).unwrap().gid()
);
}
@@ -452,12 +723,22 @@ mod tests {
guest_path: "/etc/app.conf".to_string(),
read_only: true,
}];
+ let runtime = crate::runtime::rt_impl::RuntimeImpl::new_for_test(
+ crate::runtime::options::BoxliteOptions {
+ home_dir: tmp.path().to_path_buf(),
+ ..Default::default()
+ },
+ )
+ .unwrap();
- let resolved = resolve_user_volumes(&volumes).unwrap();
+ let resolved = resolve_user_volumes(&volumes, &[], &runtime.local_volume_store).unwrap();
assert_eq!(resolved.len(), 1);
// Keeps the file's own path (staged into a share dir later) plus its name.
assert_eq!(resolved[0].host_path, file_path.canonicalize().unwrap());
- assert_eq!(resolved[0].subpath, Some("app.conf".to_string()));
+ assert!(matches!(
+ resolved[0].kind,
+ ResolvedShareKind::SingleFile { ref file_name } if file_name == "app.conf"
+ ));
assert_eq!(resolved[0].guest_path, "/etc/app.conf");
}
diff --git a/src/boxlite/src/litebox/manager.rs b/src/boxlite/src/litebox/manager.rs
index 9ea3f3356..7e14eba51 100644
--- a/src/boxlite/src/litebox/manager.rs
+++ b/src/boxlite/src/litebox/manager.rs
@@ -52,6 +52,24 @@ impl BoxManager {
/// Add a new box to the database.
pub fn add_box(&self, config: &BoxConfig, state: &BoxState) -> BoxliteResult<()> {
+ self.add_box_impl(config, state, None)
+ }
+
+ pub(crate) fn add_clone_box(
+ &self,
+ config: &BoxConfig,
+ state: &BoxState,
+ base_disk_id: &crate::BaseDiskID,
+ ) -> BoxliteResult<()> {
+ self.add_box_impl(config, state, Some(base_disk_id))
+ }
+
+ fn add_box_impl(
+ &self,
+ config: &BoxConfig,
+ state: &BoxState,
+ base_disk_id: Option<&crate::BaseDiskID>,
+ ) -> BoxliteResult<()> {
// Check name uniqueness if name is set
if let Some(ref name) = config.name
&& self.lookup_box_id(name)?.is_some()
@@ -70,7 +88,11 @@ impl BoxManager {
)));
}
- self.store.save(config, state)?;
+ if let Some(base_disk_id) = base_disk_id {
+ self.store.save_clone(config, state, base_disk_id)?;
+ } else {
+ self.store.save(config, state)?;
+ }
tracing::debug!(
box_id = %config.id,
@@ -156,6 +178,11 @@ impl BoxManager {
self.store.list_all()
}
+ /// Get every persisted configuration, including records with no state row.
+ pub fn all_box_configs(&self) -> BoxliteResult<Vec<BoxConfig>> {
+ self.store.list_configs()
+ }
+
/// Save box state to the database.
///
/// Reads state from the provided BoxState and persists to DB.
diff --git a/src/boxlite/src/lock/mod.rs b/src/boxlite/src/lock/mod.rs
index 5813124fe..5987ea270 100644
--- a/src/boxlite/src/lock/mod.rs
+++ b/src/boxlite/src/lock/mod.rs
@@ -288,6 +288,31 @@ impl Drop for LockGuard<'_> {
}
}
+/// An exclusive guard whose owned locker can move into background persistence.
+pub struct OwnedLockGuard {
+ lock: Arc<dyn Locker>,
+ _gate: Option<OwnedRwLockWriteGuard<()>>,
+}
+
+impl OwnedLockGuard {
+ pub async fn new_async(lock: Arc<dyn Locker>) -> Self {
+ let gate = match lock.gate() {
+ Some(gate) => Some(gate.clone().write_owned().await),
+ None => None,
+ };
+ while !lock.try_lock() {
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ Self { lock, _gate: gate }
+ }
+}
+
+impl Drop for OwnedLockGuard {
+ fn drop(&mut self) {
+ self.lock.unlock();
+ }
+}
+
/// RAII guard holding a shared read lock.
pub struct ReadLockGuard<'a> {
lock: &'a dyn Locker,
diff --git a/src/boxlite/src/portal/interfaces/container.rs b/src/boxlite/src/portal/interfaces/container.rs
index e1547ad73..4066cec4f 100644
--- a/src/boxlite/src/portal/interfaces/container.rs
+++ b/src/boxlite/src/portal/interfaces/container.rs
@@ -1,7 +1,7 @@
//! Container service interface.
use boxlite_shared::{
- BindMount, BoxliteError, BoxliteResult, CaCert,
+ BindMount, BindMountKind, BoxliteError, BoxliteResult, CaCert,
ContainerAdvancedOptions as ProtoContainerAdvancedOptions,
ContainerCapabilities as ProtoContainerCapabilities, ContainerClient,
ContainerConfig as ProtoContainerConfig, ContainerDevice, ContainerInitErrorKind,
@@ -173,13 +173,27 @@ impl ContainerInterface {
// Uses convention-based paths - guest will construct full path from volume_name
let proto_mounts: Vec<BindMount> = mounts
.into_iter()
- .map(|m| BindMount {
- volume_name: m.volume_name,
- destination: m.destination,
- read_only: m.read_only,
- owner_uid: m.owner_uid,
- owner_gid: m.owner_gid,
- subpath: m.subpath.unwrap_or_default(),
+ .map(|m| {
+ let (kind, subpath) = match m.payload {
+ crate::volumes::ContainerMountPayload::WholeDirectory => {
+ (BindMountKind::WholeDirectory, String::new())
+ }
+ crate::volumes::ContainerMountPayload::SingleFile { file_name } => {
+ (BindMountKind::SingleFile, file_name)
+ }
+ crate::volumes::ContainerMountPayload::ManagedSubDirectory { sub_path } => {
+ (BindMountKind::ManagedSubDirectory, sub_path)
+ }
+ };
+ BindMount {
+ volume_name: m.volume_name,
+ destination: m.destination,
+ read_only: m.read_only,
+ owner_uid: m.owner_uid,
+ owner_gid: m.owner_gid,
+ kind: kind as i32,
+ subpath,
+ }
})
.collect();
@@ -231,6 +245,10 @@ impl ContainerInterface {
Ok(ContainerInitErrorKind::Unsupported) => {
Err(BoxliteError::Unsupported(reason))
}
+ Ok(ContainerInitErrorKind::InvalidArgument) => {
+ Err(BoxliteError::InvalidArgument(reason))
+ }
+ Ok(ContainerInitErrorKind::NotFound) => Err(BoxliteError::NotFound(reason)),
_ => Err(BoxliteError::Internal(reason)),
}
}
@@ -323,9 +341,10 @@ fn map_container_init_status(status: tonic::Status) -> BoxliteError {
mod tests {
use super::*;
use boxlite_shared::{
- Container as ContainerService, ContainerInitRequest, ContainerInitResponse,
- ContainerInitSuccess, ContainerServer, ContainerStartRequest, ContainerStartResponse,
- ContainerStartSuccess, container_init_response, container_start_response,
+ Container as ContainerService, ContainerInitError, ContainerInitRequest,
+ ContainerInitResponse, ContainerInitSuccess, ContainerServer, ContainerStartRequest,
+ ContainerStartResponse, ContainerStartSuccess, container_init_response,
+ container_start_response,
};
use std::sync::{Arc, Mutex};
use tonic::transport::{Endpoint, Server};
@@ -355,6 +374,7 @@ mod tests {
struct StubGuest {
start_reply: StartReply,
+ init_error: Option<ContainerInitErrorKind>,
/// Last `Container.Init` request the stub saw, for wire assertions.
seen_init: Arc<Mutex<Option<ContainerInitRequest>>>,
}
@@ -368,6 +388,14 @@ mod tests {
let request = request.into_inner();
let container_id = request.container_id.clone();
*self.seen_init.lock().unwrap() = Some(request);
+ if let Some(kind) = self.init_error {
+ return Ok(Response::new(ContainerInitResponse {
+ result: Some(container_init_response::Result::Error(ContainerInitError {
+ reason: format!("injected {kind:?}"),
+ kind: kind.into(),
+ })),
+ }));
+ }
Ok(Response::new(ContainerInitResponse {
result: Some(container_init_response::Result::Success(
ContainerInitSuccess { container_id },
@@ -402,11 +430,12 @@ mod tests {
/// Serve `StubGuest` on an ephemeral loopback port and return a
/// `ContainerInterface` wired to it.
async fn interface_for(start_reply: StartReply) -> ContainerInterface {
- interface_recording(start_reply, Arc::new(Mutex::new(None))).await
+ interface_recording(start_reply, None, Arc::new(Mutex::new(None))).await
}
async fn interface_recording(
start_reply: StartReply,
+ init_error: Option<ContainerInitErrorKind>,
seen_init: Arc<Mutex<Option<ContainerInitRequest>>>,
) -> ContainerInterface {
// Bind with std to learn a free port, then hand the address to tonic.
@@ -418,6 +447,7 @@ mod tests {
Server::builder()
.add_service(ContainerServer::new(StubGuest {
start_reply,
+ init_error,
seen_init,
}))
.serve(addr)
@@ -477,6 +507,58 @@ mod tests {
assert!(iface.start("box-ok").await.is_ok());
}
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn container_init_sends_explicit_mount_kinds() {
+ let seen = Arc::new(Mutex::new(None));
+ let mut iface = interface_recording(StartReply::Success, None, Arc::clone(&seen)).await;
+ let mount = |payload| ContainerMount {
+ volume_name: "uservol0".to_string(),
+ destination: "/data".to_string(),
+ read_only: false,
+ owner_uid: 0,
+ owner_gid: 0,
+ payload,
+ };
+
+ iface
+ .init(ContainerInitConfig {
+ container_id: "container-1".to_string(),
+ image: crate::images::ContainerImageConfig::default(),
+ rootfs: ContainerRootfsInitConfig::Merged,
+ mounts: vec![
+ mount(crate::volumes::ContainerMountPayload::WholeDirectory),
+ mount(crate::volumes::ContainerMountPayload::SingleFile {
+ file_name: "app.conf".to_string(),
+ }),
+ mount(crate::volumes::ContainerMountPayload::ManagedSubDirectory {
+ sub_path: "team/backend".to_string(),
+ }),
+ ],
+ ca_certs: Vec::new(),
+ tty: false,
+ devices: Vec::new(),
+ resources: ContainerResources::default(),
+ advanced: ContainerAdvancedConfig::default(),
+ })
+ .await
+ .unwrap();
+
+ let request = seen.lock().unwrap().take().expect("guest saw Init");
+ let expected = [
+ (boxlite_shared::BindMountKind::WholeDirectory, ""),
+ (boxlite_shared::BindMountKind::SingleFile, "app.conf"),
+ (
+ boxlite_shared::BindMountKind::ManagedSubDirectory,
+ "team/backend",
+ ),
+ ];
+ assert_eq!(request.mounts.len(), expected.len());
+ for (mount, (kind, subpath)) in request.mounts.iter().zip(expected) {
+ assert_eq!(mount.kind, kind as i32);
+ assert_eq!(mount.subpath, subpath);
+ }
+ }
+
/// Devices are container-scoped, so they must reach the guest on the
/// request itself rather than inside the process config — and init's
/// session id must equal the container id, the rule `LiteBox::attach()`
@@ -484,7 +566,7 @@ mod tests {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn container_init_sends_devices_and_session_id() {
let seen = Arc::new(Mutex::new(None));
- let mut iface = interface_recording(StartReply::Success, Arc::clone(&seen)).await;
+ let mut iface = interface_recording(StartReply::Success, None, Arc::clone(&seen)).await;
iface
.init(ContainerInitConfig {
@@ -564,4 +646,43 @@ mod tests {
assert_eq!(mount.destination, "/sys");
assert!(!mount.options.contains(&"rro".to_string()));
}
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn container_init_maps_guest_error_kinds() {
+ for kind in [
+ ContainerInitErrorKind::InvalidArgument,
+ ContainerInitErrorKind::NotFound,
+ ContainerInitErrorKind::Unsupported,
+ ] {
+ let mut iface =
+ interface_recording(StartReply::Success, Some(kind), Arc::new(Mutex::new(None)))
+ .await;
+ let error = iface
+ .init(ContainerInitConfig {
+ container_id: "container-1".to_string(),
+ image: crate::images::ContainerImageConfig::default(),
+ rootfs: ContainerRootfsInitConfig::Merged,
+ mounts: Vec::new(),
+ ca_certs: Vec::new(),
+ tty: false,
+ devices: Vec::new(),
+ resources: ContainerResources::default(),
+ advanced: ContainerAdvancedConfig::default(),
+ })
+ .await
+ .expect_err("injected guest error must reach the caller");
+ match kind {
+ ContainerInitErrorKind::InvalidArgument => {
+ assert!(matches!(error, BoxliteError::InvalidArgument(_)))
+ }
+ ContainerInitErrorKind::NotFound => {
+ assert!(matches!(error, BoxliteError::NotFound(_)))
+ }
+ ContainerInitErrorKind::Unsupported => {
+ assert!(matches!(error, BoxliteError::Unsupported(_)))
+ }
+ _ => panic!("unexpected test kind"),
+ }
+ }
+ }
}
diff --git a/src/boxlite/src/portal/interfaces/guest.rs b/src/boxlite/src/portal/interfaces/guest.rs
index dcf70631b..7d541bc9e 100644
--- a/src/boxlite/src/portal/interfaces/guest.rs
+++ b/src/boxlite/src/portal/interfaces/guest.rs
@@ -79,6 +79,18 @@ impl GuestInterface {
ensure_guest_version(&response.version, minimum)
}
+ /// Fail before initialization if the guest cannot pin managed-volume subdirectories.
+ pub async fn require_safe_volume_sub_path(&mut self) -> BoxliteResult<()> {
+ let response = self.client.ping(PingRequest {}).await?.into_inner();
+ if response.safe_managed_volume_sub_path {
+ return Ok(());
+ }
+ Err(BoxliteError::Unsupported(
+ "guest does not support safe managed-volume sub_path mounts; recreate the box with the current runtime"
+ .into(),
+ ))
+ }
+
/// Shutdown the guest agent.
pub async fn shutdown(&mut self) -> BoxliteResult<()> {
let _response = self.client.shutdown(ShutdownRequest {}).await?;
@@ -119,7 +131,7 @@ fn parse_guest_version(version: &str) -> Option<GuestVersion> {
parts.next().is_none().then_some(parsed)
}
-fn ensure_guest_version(version: &str, minimum: GuestVersion) -> BoxliteResult<()> {
+pub(crate) fn ensure_guest_version(version: &str, minimum: GuestVersion) -> BoxliteResult<()> {
let (major, minor, patch) = minimum;
let Some(reported) = parse_guest_version(version) else {
return Err(BoxliteError::Unsupported(format!(
diff --git a/src/boxlite/src/runtime/import.rs b/src/boxlite/src/runtime/import.rs
index d494e8fd8..246892508 100644
--- a/src/boxlite/src/runtime/import.rs
+++ b/src/boxlite/src/runtime/import.rs
@@ -59,7 +59,7 @@ pub(crate) async fn import_box(
let litebox = runtime
// An archive carries the box's options but not what its image resolved
// to, so an imported box has no record until one is rebuilt.
- .provision_box(staging_dir, name, options, BoxStatus::Stopped, None)
+ .provision_box(staging_dir, name, options, BoxStatus::Stopped, None, None)
.await?;
tracing::info!(
@@ -100,14 +100,6 @@ fn options_from_manifest(
options.sanitize().map_err(|error| {
BoxliteError::InvalidArgument(format!("invalid archive box_options: {error}"))
})?;
- // The local runtime shares no typed mounts yet(TODO), so an archive that
- // carries one is refused rather than stored and dropped at boot.
- if !options.mounts.is_empty() {
- return Err(BoxliteError::Unsupported(
- "typed mounts are not supported by the local runtime yet".to_string(),
- ));
- }
-
if policy == ArchiveImportPolicy::Trusted {
return Ok(options);
}
@@ -131,7 +123,7 @@ fn options_from_manifest(
}
// Every mount, not just a host bind: a managed volume reference in an
// uploaded archive would also select storage the uploader does not own.
- if !options.volumes.is_empty() {
+ if !options.volumes.is_empty() || !options.mounts.is_empty() {
return Err(rejected_upload("volume mounts"));
}
options.advanced.security = SecurityOptions::default();
@@ -466,28 +458,30 @@ mod tests {
assert!(error.to_string().contains("volume mounts"));
}
- /// The local runtime shares no typed mounts yet, so an archive that carries
- /// one is refused whoever imports it, rather than stored and later dropped.
#[test]
- fn import_refuses_typed_mounts_until_the_local_runtime_shares_them() {
+ fn import_typed_mount_policy_depends_on_trust() {
use crate::runtime::options::MountSpec;
- for policy in [
- ArchiveImportPolicy::Trusted,
- ArchiveImportPolicy::UntrustedRemote,
+ let trusted = BoxOptions {
+ mounts: vec![MountSpec::bind_mount("/srv/data", "/data")],
+ ..Default::default()
+ };
+ options_from_manifest(&v3_manifest(trusted), ArchiveImportPolicy::Trusted)
+ .expect("trusted archives may carry typed mounts");
+
+ for mount in [
+ MountSpec::bind_mount("/srv/data", "/data"),
+ MountSpec::volume_mount("workspace", "/workspace"),
] {
let options = BoxOptions {
- mounts: vec![MountSpec::bind_mount("/srv/data", "/data")],
+ mounts: vec![mount],
..Default::default()
};
-
- let error = options_from_manifest(&v3_manifest(options), policy)
- .expect_err("the local runtime shares no typed mounts yet");
-
- assert!(
- error.to_string().contains("typed mounts"),
- "{policy:?}: {error}"
- );
+ let error =
+ options_from_manifest(&v3_manifest(options), ArchiveImportPolicy::UntrustedRemote)
+ .expect_err("untrusted archives must not select server storage");
+ assert!(matches!(error, BoxliteError::Unsupported(_)), "{error:?}");
+ assert!(error.to_string().contains("volume mounts"), "{error}");
}
}
@@ -668,7 +662,7 @@ mod tests {
std::fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap();
build_zstd_tar_archive(&archive_path, &manifest_path, &container_path, 1).unwrap();
let result = extract_and_validate(&archive_path, &layout);
- if version > 6 {
+ if version > crate::litebox::archive::MAX_SUPPORTED_VERSION {
let error = result.unwrap_err();
assert!(error.to_string().contains(&format!("version {version}")));
} else {
@@ -795,4 +789,56 @@ mod required_import_safety_tests {
}
}
}
+
+ #[tokio::test]
+ async fn trusted_import_rejects_missing_canonical_volume_without_leaking_box() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().join("runtime"),
+ ..Default::default()
+ })
+ .unwrap();
+ let disk = home.path().join("disk.qcow2");
+ crate::disk::qcow2::write_test_qcow2(&disk, None);
+ let missing_id = uuid::Uuid::new_v4().to_string();
+ let manifest = ArchiveManifest {
+ version: crate::litebox::archive::MANAGED_MOUNTS_ARCHIVE_VERSION,
+ box_name: None,
+ image: "alpine:latest".into(),
+ box_options: Some(BoxOptions {
+ mounts: vec![crate::runtime::options::MountSpec::volume_mount(
+ &missing_id,
+ "/workspace",
+ )],
+ ..Default::default()
+ }),
+ guest_disk_checksum: String::new(),
+ container_disk_checksum: sha256_file(&disk).unwrap(),
+ exported_at: "2026-11-15T00:00:00Z".into(),
+ };
+ let manifest_path = home.path().join("manifest.json");
+ std::fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap();
+ let path = home.path().join("saved.boxlite");
+ crate::litebox::archive::build_zstd_tar_archive(&path, &manifest_path, &disk, 1).unwrap();
+
+ let error = import_box(&runtime, BoxArchive::new(&path), None)
+ .await
+ .err()
+ .expect("an archive must not acquire a missing canonical volume");
+ assert!(matches!(error, BoxliteError::NotFound(_)), "{error:?}");
+ assert!(error.to_string().contains(&missing_id));
+ assert!(runtime.list_info().await.unwrap().is_empty());
+ assert_eq!(
+ std::fs::read_dir(runtime.layout.boxes_dir())
+ .unwrap()
+ .count(),
+ 0
+ );
+ assert_eq!(
+ std::fs::read_dir(runtime.layout.temp_dir())
+ .unwrap()
+ .count(),
+ 0
+ );
+ }
}
diff --git a/src/boxlite/src/runtime/layout.rs b/src/boxlite/src/runtime/layout.rs
index e65e7b84a..383146f0c 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 managed local volumes
+ pub const VOLUMES_DIR: &str = "volumes";
+
/// Subdirectory for Unix domain sockets
pub const SOCKETS_DIR: &str = "sockets";
@@ -108,6 +111,8 @@ impl FsLayoutConfig {
/// ├── bases/ # Flat backing files (nanoid-named)
/// │ ├── {nanoid}.qcow2 # Snapshot / clone base container disk
/// │ └── {nanoid}.ext4 # Guest rootfs cache
+/// ├── volumes/ # Managed local volumes and legacy anonymous binds
+/// │ └── {volume_id}/ # .metadata.json + _data/
/// ├── locks/ # Per-entity lock files
/// ├── logs/ # Home-level logs
/// └── tmp/ # Transient temp files (same-fs for rename)
@@ -165,6 +170,11 @@ impl FilesystemLayout {
self.home_dir.join(dirs::BOXES_DIR)
}
+ /// Root directory for managed local volumes: ~/.boxlite/volumes
+ pub fn volumes_dir(&self) -> PathBuf {
+ self.home_dir.join(dirs::VOLUMES_DIR)
+ }
+
/// Bases directory: ~/.boxlite/bases
///
/// Flat directory of immutable backing files (snapshots, clone bases, rootfs cache).
diff --git a/src/boxlite/src/runtime/options.rs b/src/boxlite/src/runtime/options.rs
index dde8d32af..58fdbe1cb 100644
--- a/src/boxlite/src/runtime/options.rs
+++ b/src/boxlite/src/runtime/options.rs
@@ -851,6 +851,12 @@ impl BoxOptions {
port.validate_publishable()?;
}
+ if !self.volumes.is_empty() && !self.mounts.is_empty() {
+ return Err(boxlite_shared::errors::BoxliteError::InvalidArgument(
+ "volumes and mounts cannot both be non-empty".into(),
+ ));
+ }
+
for volume in &self.volumes {
volume.validate()?;
}
@@ -1066,8 +1072,8 @@ pub struct VolumeSpec {
/// Managed volume to mount, addressed by its server-assigned id **or** by
/// its name — the server resolves either.
///
- /// Managed volumes need a REST runtime, since the local runtime has no
- /// volume backend to resolve a reference against.
+ /// LocalRuntime resolves references through `LocalVolumeStore`; a REST
+ /// runtime resolves them on the server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub managed_volume: Option<String>,
@@ -1143,8 +1149,7 @@ impl VolumeSpec {
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MountType {
- /// A managed volume, by server-assigned id or by name. REST runtimes only:
- /// the local runtime has no volume backend to resolve one against.
+ /// A managed volume, addressed by runtime-assigned id or by name.
Volume,
/// A host directory or file. Local runtime only: over REST the path would
/// name the server's filesystem, not the caller's.
diff --git a/src/boxlite/src/runtime/rt_impl.rs b/src/boxlite/src/runtime/rt_impl.rs
index 256f48828..8073b8239 100644
--- a/src/boxlite/src/runtime/rt_impl.rs
+++ b/src/boxlite/src/runtime/rt_impl.rs
@@ -132,6 +132,8 @@ pub struct RuntimeImpl {
// ========================================================================
/// Box manager with integrated persistence (has internal RwLock)
pub(crate) box_manager: BoxManager,
+ /// Local managed-volume storage
+ pub(crate) local_volume_store: crate::volumes::LocalVolumeStore,
/// Image management (has internal RwLock via ImageStore)
pub(crate) image_manager: ImageManager,
@@ -218,6 +220,11 @@ pub struct SynchronizedState {
/// cached image disk.
const IMAGE_DISK_GUEST_BINARY_HEADROOM_BYTES: u64 = 512 * 1024 * 1024;
+pub(crate) struct CloneDependency {
+ pub base_disk_id: crate::BaseDiskID,
+ pub source_admission: Arc<crate::lock::OwnedLockGuard>,
+}
+
impl RuntimeImpl {
// ========================================================================
// CONSTRUCTION
@@ -330,6 +337,19 @@ impl RuntimeImpl {
let snapshot_store = crate::db::SnapshotStore::new(db.clone());
let snapshot_mgr = crate::litebox::snapshot_mgr::SnapshotManager::new(snapshot_store);
let box_store = BoxStore::new(db);
+ let box_manager = BoxManager::new(box_store);
+ let local_volume_store =
+ crate::volumes::LocalVolumeStore::new(layout.volumes_dir(), box_manager.clone())
+ .map_err(|error| {
+ BoxliteError::Storage(format!(
+ "Failed to initialize local volume store: {error}"
+ ))
+ })?;
+ // Reconcile staging/trash left by a crashed volume operation before
+ // any box can start and refer to a volume.
+ local_volume_store.recover().map_err(|error| {
+ BoxliteError::Storage(format!("Failed to recover local volume store: {error}"))
+ })?;
// Initialize lock manager for per-entity multiprocess-safe locking
let lock_manager: Arc<dyn LockManager> =
@@ -363,7 +383,8 @@ impl RuntimeImpl {
active_boxes_by_id: HashMap::new(),
active_boxes_by_name: HashMap::new(),
}),
- box_manager: BoxManager::new(box_store),
+ box_manager,
+ local_volume_store,
image_manager,
layout,
image_disk_mgr,
@@ -488,10 +509,20 @@ impl RuntimeImpl {
options.validate_secrets()?;
// Initialize box variables with defaults
- let (config, mut state) = self.init_box_variables(&options, name.clone());
+ let (mut config, mut state) = self.init_box_variables(&options, name.clone());
// Persist Configured state only after both lock namespaces are allocated.
- if let Err(e) = self.persist_box_with_locks(&config, &mut state) {
+ // Persisting a new box also registers its selected volume holders.
+ // Clone/import re-registers volume holders before the new box persists.
+ if let Err(e) = self
+ .persist_box_with_locks(
+ &mut config,
+ &mut state,
+ crate::volumes::VolumeReferenceMode::Selector,
+ None,
+ )
+ .await
+ {
// TOCTOU race recovery: lookup_box (line ~268) and add_box are
// separate non-atomic operations. Between them, another concurrent
// caller can complete the full create path and persist first:
@@ -518,8 +549,9 @@ impl RuntimeImpl {
// Create LiteBox handle with shared BoxImpl
// This also checks in-memory cache for duplicate names
+ let box_id = config.id.clone();
let (box_impl, inserted) = self.get_or_create_box_impl(config, state);
- if !inserted {
+ if !inserted && box_impl.id() != &box_id {
return Err(BoxliteError::InvalidArgument(
"box with this name already exists".into(),
));
@@ -1367,6 +1399,7 @@ impl RuntimeImpl {
options: BoxOptions,
initial_status: BoxStatus,
resolved_image: Option<crate::images::ResolvedImage>,
+ clone_dependency: Option<CloneDependency>,
) -> BoxliteResult<LiteBox> {
use crate::litebox::config::ContainerRuntimeConfig;
@@ -1387,7 +1420,7 @@ impl RuntimeImpl {
})?;
let engine_kind = options.advanced.engine.unwrap_or_default();
- let config = BoxConfig {
+ let mut config = BoxConfig {
id: box_id.clone(),
name,
created_at: now,
@@ -1401,7 +1434,15 @@ impl RuntimeImpl {
state.set_status(initial_status);
state.resolved_image = resolved_image;
- if let Err(e) = self.persist_box_with_locks(&config, &mut state) {
+ if let Err(e) = self
+ .persist_box_with_locks(
+ &mut config,
+ &mut state,
+ crate::volumes::VolumeReferenceMode::CanonicalId,
+ clone_dependency,
+ )
+ .await
+ {
let _ = std::fs::remove_dir_all(&config.box_home);
config.sockets().remove();
return Err(e);
@@ -1414,10 +1455,12 @@ impl RuntimeImpl {
/// Allocate the paired namespaces before publishing the persisted lock ID.
/// A numeric ID stays unavailable until its disk namespace is clean.
- fn persist_box_with_locks(
- &self,
- config: &BoxConfig,
+ async fn persist_box_with_locks(
+ self: &Arc<Self>,
+ config: &mut BoxConfig,
state: &mut BoxState,
+ mode: crate::volumes::VolumeReferenceMode,
+ clone_dependency: Option<CloneDependency>,
) -> BoxliteResult<()> {
let id = self.lock_manager.allocate()?;
if let Err(e) = self.disk_lock_manager.allocate_and_retrieve(id) {
@@ -1426,10 +1469,51 @@ impl RuntimeImpl {
return Err(e);
}
state.set_lock_id(id);
- if let Err(e) = self.box_manager.add_box(config, state) {
+
+ let store = self.local_volume_store.clone();
+ let runtime = Arc::clone(self);
+ let mut persisted_config = config.clone();
+ let state_for_persist = state.clone();
+ let (base_disk_id, source_admission) = clone_dependency
+ .map(|dependency| {
+ (
+ Some(dependency.base_disk_id),
+ Some(dependency.source_admission),
+ )
+ })
+ .unwrap_or((None, None));
+ let persist_task = tokio::task::spawn_blocking(move || {
+ let _runtime = runtime;
+ let _source_admission = source_admission;
+ let result = match base_disk_id {
+ Some(ref id) => store.add_clone_box_with_resolved_volumes(
+ &mut persisted_config,
+ &state_for_persist,
+ mode,
+ id,
+ ),
+ None => store.add_box_with_resolved_volumes(
+ &mut persisted_config,
+ &state_for_persist,
+ mode,
+ ),
+ };
+ (persisted_config, result)
+ });
+ let (persisted_config, persist_result) = match persist_task.await {
+ Ok(result) => result,
+ Err(error) => {
+ self.free_box_locks(id);
+ return Err(BoxliteError::Internal(format!(
+ "box persist task failed: {error}"
+ )));
+ }
+ };
+ if let Err(e) = persist_result {
self.free_box_locks(id);
return Err(e);
}
+ *config = persisted_config;
Ok(())
}
@@ -1922,28 +2006,6 @@ fn reject_local_unsupported_options(options: &BoxOptions) -> BoxliteResult<()> {
));
}
- // `resolve_user_volumes` catches this too, but only once boot is under way
- // — after the image is pulled and the box record exists. Fail here instead,
- // mirroring `BoxOptions::sanitize_remote`'s mount rules on the REST side.
- if let Some(volume) = options
- .volumes
- .iter()
- .find_map(|volume| volume.managed_volume.as_deref())
- {
- return Err(BoxliteError::Unsupported(format!(
- "managed volume {volume:?} is only supported by REST runtimes; the local runtime has \
- no volume backend to resolve it against"
- )));
- }
-
- // The local runtime shares no typed mounts yet(TODO): refused here, before
- // the image pull and the box record, rather than dropped at boot.
- if !options.mounts.is_empty() {
- return Err(BoxliteError::Unsupported(
- "typed mounts are not supported by the local runtime yet".into(),
- ));
- }
-
Ok(())
}
@@ -2089,37 +2151,67 @@ impl super::images::ImageBackend for LocalRuntime {
}
}
-// Named-volume operations (separate from RuntimeBackend). The concrete backend
-// is not yet implemented: the local filesystem store was removed in favor of a
-// future managed volume backend, so every operation returns `Unsupported`.
+// Named-volume operations (separate from RuntimeBackend).
+// Each volume action performs filesystem work on a blocking thread while
+// retaining an async shutdown check on the caller thread.
#[async_trait::async_trait]
impl super::volumes::VolumeBackend for LocalRuntime {
- async fn create_volume(
- &self,
- _name: Option<&str>,
- ) -> BoxliteResult<crate::volumes::VolumeInfo> {
- Err(volumes_unsupported())
+ async fn create_volume(&self, name: Option<&str>) -> BoxliteResult<crate::volumes::VolumeInfo> {
+ if self.0.shutdown_token.is_cancelled() {
+ return Err(BoxliteError::Stopped(
+ "Cannot create volume: runtime is shut down".into(),
+ ));
+ }
+ let store = self.0.local_volume_store.clone();
+ let name = name.map(str::to_owned);
+ tokio::task::spawn_blocking(move || store.create(name.as_deref()))
+ .await
+ .map_err(|error| {
+ BoxliteError::Internal(format!("volume create task failed: {error}"))
+ })?
}
async fn list_volumes(&self) -> BoxliteResult<Vec<crate::volumes::VolumeInfo>> {
- Err(volumes_unsupported())
+ if self.0.shutdown_token.is_cancelled() {
+ return Err(BoxliteError::Stopped(
+ "Cannot list volumes: runtime is shut down".into(),
+ ));
+ }
+ let store = self.0.local_volume_store.clone();
+ tokio::task::spawn_blocking(move || store.list())
+ .await
+ .map_err(|error| BoxliteError::Internal(format!("volume list task failed: {error}")))?
}
- async fn get_volume(&self, _id: &str) -> BoxliteResult<crate::volumes::VolumeInfo> {
- Err(volumes_unsupported())
+ async fn get_volume(&self, id: &str) -> BoxliteResult<crate::volumes::VolumeInfo> {
+ if self.0.shutdown_token.is_cancelled() {
+ return Err(BoxliteError::Stopped(
+ "Cannot get volume: runtime is shut down".into(),
+ ));
+ }
+ let store = self.0.local_volume_store.clone();
+ let id = id.to_owned();
+ tokio::task::spawn_blocking(move || store.get(&id))
+ .await
+ .map_err(|error| BoxliteError::Internal(format!("volume get task failed: {error}")))?
}
- async fn remove_volume(&self, _id: &str, _force: bool) -> BoxliteResult<()> {
- Err(volumes_unsupported())
+ async fn remove_volume(&self, id: &str, force: bool) -> BoxliteResult<()> {
+ if self.0.shutdown_token.is_cancelled() {
+ return Err(BoxliteError::Stopped(
+ "Cannot remove volume: runtime is shut down".into(),
+ ));
+ }
+ let store = self.0.local_volume_store.clone();
+ let id = id.to_owned();
+ tokio::task::spawn_blocking(move || store.remove(&id, force))
+ .await
+ .map_err(|error| {
+ BoxliteError::Internal(format!("volume remove task failed: {error}"))
+ })?
}
}
-/// Error returned by every named-volume operation until a volume backend is
-/// wired up.
-fn volumes_unsupported() -> BoxliteError {
- BoxliteError::Unsupported("named volumes are not supported yet".to_string())
-}
-
// ============================================================================
// Drop — Safety net for non-default runtimes
// ============================================================================
@@ -2143,7 +2235,8 @@ mod tests {
use crate::litebox::config::{BoxConfig, ContainerRuntimeConfig};
use crate::runtime::backend::RuntimeBackend;
use crate::runtime::images::ImageBackend;
- use crate::runtime::options::RootfsSpec;
+ use crate::runtime::options::{RootfsSpec, VolumeSpec};
+ use crate::runtime::volumes::VolumeBackend;
use crate::vmm::guest_binary::GuestBinary;
use tempfile::TempDir;
@@ -2198,14 +2291,9 @@ mod tests {
assert!(sanitize_local_options(&features, options).await.is_ok());
}
- /// The local runtime has no volume backend. `resolve_user_volumes` also
- /// refuses a managed volume, but only once boot is under way — after the
- /// image is pulled and the box record exists. This guard is the whole
- /// reason the failure is cheap, so it needs its own test: without it every
- /// suite still passes and the rejection silently moves back to boot time.
#[tokio::test]
- async fn local_runtime_rejects_managed_volumes_before_boot() {
- use crate::runtime::options::VolumeSpec;
+ async fn local_runtime_sanitizes_managed_mounts_but_rejects_mixed_mount_lists() {
+ use crate::runtime::options::{MountSpec, VolumeSpec};
let features = ExperimentalFeatures::default();
let host_bind = BoxOptions {
@@ -2218,14 +2306,25 @@ mod tests {
volumes: vec![VolumeSpec::managed_volume("my-data", "/data")],
..Default::default()
};
- let error = sanitize_local_options(&features, managed)
- .await
- .expect_err("a managed volume has no local backend to resolve against");
+ assert!(sanitize_local_options(&features, managed).await.is_ok());
+ let typed = BoxOptions {
+ mounts: vec![MountSpec::volume_mount("my-data", "/data")],
+ ..Default::default()
+ };
+ assert!(sanitize_local_options(&features, typed).await.is_ok());
- assert!(matches!(error, BoxliteError::Unsupported(_)), "{error:?}");
- let message = error.to_string();
- assert!(message.contains("my-data"), "{message}");
- assert!(message.contains("REST runtime"), "{message}");
+ let mixed = BoxOptions {
+ volumes: vec![VolumeSpec::managed_volume("my-data", "/data")],
+ mounts: vec![MountSpec::volume_mount("my-data", "/data")],
+ ..Default::default()
+ };
+ let error = sanitize_local_options(&features, mixed)
+ .await
+ .expect_err("non-empty volumes and mounts must be rejected");
+ assert!(
+ matches!(error, BoxliteError::InvalidArgument(_)),
+ "{error:?}"
+ );
}
/// The bundled guest kernel brings up at most `MAX_CPUS` vCPUs. Without
@@ -2324,22 +2423,17 @@ mod tests {
.expect("a custom kernel sets its own vCPU ceiling");
}
- /// Until the local runtime shares typed mounts, create refuses them rather
- /// than booting a box without them.
#[tokio::test]
- async fn local_runtime_refuses_typed_mounts_until_it_shares_them() {
+ async fn local_runtime_sanitizes_typed_bind_mounts() {
use crate::runtime::options::MountSpec;
let options = BoxOptions {
mounts: vec![MountSpec::bind_mount("/tmp/data", "/data")],
..Default::default()
};
- let error = sanitize_local_options(&ExperimentalFeatures::default(), options)
+ sanitize_local_options(&ExperimentalFeatures::default(), options)
.await
- .expect_err("the local runtime shares no typed mounts yet");
-
- assert!(matches!(error, BoxliteError::Unsupported(_)), "{error:?}");
- assert!(error.to_string().contains("typed mounts"), "{error}");
+ .expect("typed bind mounts share the local resolution path");
}
#[test]
@@ -2512,6 +2606,167 @@ mod tests {
(runtime, temp_dir)
}
+ #[tokio::test]
+ async fn local_volume_crud_uses_canonical_ids_without_implicit_creation() {
+ let (runtime, _dir) = create_test_runtime();
+ let local = LocalRuntime(Arc::clone(&runtime));
+ let missing_id = uuid::Uuid::new_v4().to_string();
+
+ let error = local
+ .get_volume(&missing_id)
+ .await
+ .expect_err("an unknown canonical id must be NotFound");
+ assert!(matches!(error, BoxliteError::NotFound(_)), "{error:?}");
+
+ let created = local
+ .create_volume(Some("workspace"))
+ .await
+ .expect("create a local volume");
+ assert_eq!(created.name, "workspace");
+ assert_eq!(
+ created.id,
+ uuid::Uuid::parse_str(&created.id).unwrap().to_string()
+ );
+ assert_eq!(created.size_bytes, None);
+
+ let error = local
+ .create_volume(Some("workspace"))
+ .await
+ .expect_err("a duplicate name must be rejected");
+ assert!(matches!(error, BoxliteError::AlreadyExists(_)), "{error:?}");
+
+ let fetched = local
+ .get_volume(&created.id)
+ .await
+ .expect("get by canonical id");
+ assert_eq!(fetched.id, created.id);
+ assert_eq!(fetched.name, created.name);
+ assert_eq!(fetched.created_at, created.created_at);
+ assert_eq!(local.list_volumes().await.unwrap().len(), 1);
+
+ local
+ .remove_volume(&created.id, false)
+ .await
+ .expect("remove");
+ let error = local
+ .get_volume(&created.id)
+ .await
+ .expect_err("the removed id must be NotFound");
+ assert!(matches!(error, BoxliteError::NotFound(_)), "{error:?}");
+ assert!(local.list_volumes().await.unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn local_volume_remove_rejects_persisted_holders_even_with_force() {
+ let (runtime, _dir) = create_test_runtime();
+ let local = LocalRuntime(Arc::clone(&runtime));
+ let volume = local.create_volume(Some("workspace")).await.unwrap();
+ let box_id = BoxIDMint::mint();
+ let config = BoxConfig {
+ id: box_id.clone(),
+ name: None,
+ created_at: Utc::now(),
+ container: ContainerRuntimeConfig {
+ id: ContainerID::new(),
+ },
+ options: BoxOptions {
+ volumes: vec![VolumeSpec::managed_volume(&volume.id, "/workspace")],
+ auto_delete: Some(0),
+ ..Default::default()
+ },
+ engine_kind: crate::vmm::VmmKind::Libkrun,
+ box_home: runtime.layout.boxes_dir().join(box_id.as_str()),
+ };
+ runtime
+ .box_manager
+ .add_box(&config, &BoxState::new())
+ .expect("seed a volume holder");
+
+ for force in [false, true] {
+ let error = local
+ .remove_volume(&volume.id, force)
+ .await
+ .expect_err("a persisted box must prevent volume removal");
+ assert!(matches!(error, BoxliteError::InvalidState(_)), "{error:?}");
+ local.get_volume(&volume.id).await.expect("payload remains");
+ }
+
+ runtime.box_manager.remove_box(&box_id).unwrap();
+ local
+ .remove_volume(&volume.id, true)
+ .await
+ .expect("remove after holder deletion");
+ }
+
+ #[tokio::test]
+ async fn local_box_create_persists_canonical_volume_id_and_rejects_duplicates() {
+ let (runtime, _dir) = create_test_runtime();
+ let local = LocalRuntime(Arc::clone(&runtime));
+ let volume = local.create_volume(Some("workspace")).await.unwrap();
+ let litebox = RuntimeBackend::create(
+ &local,
+ BoxOptions {
+ volumes: vec![VolumeSpec::managed_volume("workspace", "/workspace")],
+ auto_delete: Some(0),
+ ..Default::default()
+ },
+ None,
+ )
+ .await
+ .expect("create a box from a volume name");
+ let (config, _) = runtime
+ .box_manager
+ .box_by_id(litebox.id())
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ config.options.volumes[0].managed_volume.as_deref(),
+ Some(volume.id.as_str())
+ );
+ assert!(config.options.volumes[0].host_path.is_empty());
+
+ let before = runtime.box_manager.all_box_configs().unwrap().len();
+ let error = RuntimeBackend::create(
+ &local,
+ BoxOptions {
+ volumes: vec![
+ VolumeSpec::managed_volume(&volume.id, "/one"),
+ VolumeSpec::managed_volume("workspace", "/two"),
+ ],
+ auto_delete: Some(0),
+ ..Default::default()
+ },
+ None,
+ )
+ .await
+ .err()
+ .expect("aliases of one volume are still a duplicate mount");
+ assert!(
+ matches!(error, BoxliteError::InvalidArgument(_)),
+ "{error:?}"
+ );
+ let typed_error = RuntimeBackend::create(
+ &local,
+ BoxOptions {
+ mounts: vec![
+ crate::runtime::options::MountSpec::volume_mount(&volume.id, "/one"),
+ crate::runtime::options::MountSpec::volume_mount("workspace", "/two"),
+ ],
+ auto_delete: Some(0),
+ ..Default::default()
+ },
+ None,
+ )
+ .await
+ .err()
+ .expect("typed aliases of one volume are also duplicates");
+ assert!(
+ matches!(typed_error, BoxliteError::InvalidArgument(_)),
+ "{typed_error:?}"
+ );
+ assert_eq!(runtime.box_manager.all_box_configs().unwrap().len(), before);
+ }
+
fn secret_without_hosts() -> crate::runtime::options::Secret {
crate::runtime::options::Secret {
name: "legacy".to_string(),
@@ -3849,12 +4104,12 @@ mod tests {
// Remove box clone dependency guard (Fix #7)
// ====================================================================
- #[test]
- fn test_remove_box_blocked_by_clone_dependency() {
+ #[tokio::test]
+ async fn test_remove_box_blocked_by_clone_dependency() {
let (runtime, _dir) = create_test_runtime();
// Create box A with a disk.
- let config_a = test_box_config_in_layout(false, &runtime);
+ let mut config_a = test_box_config_in_layout(false, &runtime);
let mut state_a = BoxState::new();
let disks_a = config_a.box_home.join("disks");
std::fs::create_dir_all(&disks_a).unwrap();
@@ -3864,7 +4119,13 @@ mod tests {
crate::disk::qcow2::write_test_qcow2(&disk_a, None);
runtime
- .persist_box_with_locks(&config_a, &mut state_a)
+ .persist_box_with_locks(
+ &mut config_a,
+ &mut state_a,
+ crate::volumes::VolumeReferenceMode::CanonicalId,
+ None,
+ )
+ .await
.unwrap();
// Create box B.
@@ -3913,11 +4174,11 @@ mod tests {
assert!(msg.contains(&config_b.id.to_string()));
}
- #[test]
- fn test_remove_box_succeeds_when_no_dependents() {
+ #[tokio::test]
+ async fn test_remove_box_succeeds_when_no_dependents() {
let (runtime, _dir) = create_test_runtime();
- let config = test_box_config_in_layout(false, &runtime);
+ let mut config = test_box_config_in_layout(false, &runtime);
let mut state = BoxState::new();
let disks_dir = config.box_home.join("disks");
std::fs::create_dir_all(&disks_dir).unwrap();
@@ -3926,7 +4187,15 @@ mod tests {
let disk = disks_dir.join("disk.qcow2");
crate::disk::qcow2::write_test_qcow2(&disk, None);
- runtime.persist_box_with_locks(&config, &mut state).unwrap();
+ runtime
+ .persist_box_with_locks(
+ &mut config,
+ &mut state,
+ crate::volumes::VolumeReferenceMode::CanonicalId,
+ None,
+ )
+ .await
+ .unwrap();
// The socket binding symlink must be removed with the box.
config.sockets().ensure().unwrap();
@@ -3941,19 +4210,25 @@ mod tests {
);
}
- #[test]
- fn test_remove_box_with_force_ignores_dependents() {
+ #[tokio::test]
+ async fn test_remove_box_with_force_ignores_dependents() {
let (runtime, _dir) = create_test_runtime();
// Create box A.
- let config_a = test_box_config_in_layout(false, &runtime);
+ let mut config_a = test_box_config_in_layout(false, &runtime);
let mut state_a = BoxState::new();
let disks_a = config_a.box_home.join("disks");
std::fs::create_dir_all(&disks_a).unwrap();
let disk_a = disks_a.join("disk.qcow2");
crate::disk::qcow2::write_test_qcow2(&disk_a, None);
runtime
- .persist_box_with_locks(&config_a, &mut state_a)
+ .persist_box_with_locks(
+ &mut config_a,
+ &mut state_a,
+ crate::volumes::VolumeReferenceMode::CanonicalId,
+ None,
+ )
+ .await
.unwrap();
// Create box B.
diff --git a/src/boxlite/src/runtime/tests/disk_lock.rs b/src/boxlite/src/runtime/tests/disk_lock.rs
index 304fe7a12..1196c3a70 100644
--- a/src/boxlite/src/runtime/tests/disk_lock.rs
+++ b/src/boxlite/src/runtime/tests/disk_lock.rs
@@ -47,6 +47,7 @@ async fn disk_lock_create_provision_stop_shutdown_and_restart_pair_lifetimes() {
},
BoxStatus::Stopped,
None,
+ None,
)
.await
.unwrap();
@@ -105,6 +106,7 @@ async fn disk_lock_db_insert_failure_rolls_back_create_and_provision() {
None,
BoxOptions::default(),
BoxStatus::Stopped,
+ None,
None
)
.await
@@ -146,6 +148,7 @@ async fn disk_lock_b2_failed_allocation_preserves_file_and_reserves_id() {
BoxOptions::default(),
BoxStatus::Stopped,
None,
+ None,
)
.await
.expect("provision reused the ID reserved after failed disk allocation");
@@ -541,7 +544,7 @@ async fn disk_lock_remove_commits_metadata_despite_directory_and_lifecycle_unlin
}
#[tokio::test]
-async fn disk_lock_clone_recovers_after_staging_failure_and_tolerates_ref_write_failure() {
+async fn disk_lock_clone_recovers_after_staging_failure_and_rejects_ref_write_failure() {
enable_disk_lock_logs();
let home = TempDir::new_in("/tmp").unwrap();
let runtime = RuntimeImpl::new_for_test(options(&home)).unwrap();
@@ -588,18 +591,23 @@ async fn disk_lock_clone_recovers_after_staging_failure_and_tolerates_ref_write_
BEGIN SELECT RAISE(ABORT, 'injected clone reference failure'); END;",
)
.unwrap();
- let cloned = source.clone_box(Default::default(), None).await.unwrap();
+ let failed = source.clone_box(Default::default(), None).await;
database
.execute_batch("DROP TRIGGER reject_clone_ref")
.unwrap();
- let (cloned_config, cloned_state) =
- runtime.box_manager.box_by_id(cloned.id()).unwrap().unwrap();
- let backing = crate::disk::read_backing_file_path(&disk).unwrap().unwrap();
- assert_eq!(
- crate::disk::read_backing_file_path(&cloned_config.box_home.join("disks/disk.qcow2"))
- .unwrap(),
- Some(backing.clone())
+ let error = failed
+ .err()
+ .expect("a clone without its dependency must not be published");
+ assert!(
+ error
+ .to_string()
+ .contains("injected clone reference failure"),
+ "{error:?}"
);
+ assert_eq!(runtime.box_manager.all_boxes(true).unwrap().len(), 1);
+ assert_eq!(runtime.lock_manager.allocated_count().unwrap(), 1);
+ assert_eq!(runtime.disk_lock_manager.allocated_count().unwrap(), 1);
+ let backing = crate::disk::read_backing_file_path(&disk).unwrap().unwrap();
let base = runtime
.base_disk_mgr
.store()
@@ -614,8 +622,6 @@ async fn disk_lock_clone_recovers_after_staging_failure_and_tolerates_ref_write_
.unwrap(),
vec![source.id().to_string()]
);
- assert_eq!(cloned_state.status, BoxStatus::Stopped);
- assert_pair(&runtime, cloned.id(), true);
assert!(crate::lock::LockGuard::try_new(disk_locker.as_ref()).is_some());
assert!(crate::lock::LockGuard::try_new(lifecycle.as_ref()).is_some());
assert_eq!(
@@ -630,7 +636,7 @@ async fn disk_lock_clone_recovers_after_staging_failure_and_tolerates_ref_write_
.collect();
assert_eq!(
box_dirs,
- std::collections::BTreeSet::from([config.box_home, cloned_config.box_home])
+ std::collections::BTreeSet::from([config.box_home])
);
}
diff --git a/src/boxlite/src/runtime/volumes.rs b/src/boxlite/src/runtime/volumes.rs
index 086dc96bd..c23d7f0d9 100644
--- a/src/boxlite/src/runtime/volumes.rs
+++ b/src/boxlite/src/runtime/volumes.rs
@@ -8,8 +8,7 @@
//! The trait is `#[async_trait]` like the other capability backends
//! ([`ImageBackend`](crate::runtime::images::ImageBackend),
//! [`AuthBackend`](crate::runtime::auth::AuthBackend)) so REST backends can
-//! perform network calls. The concrete backend is not implemented yet — every
-//! operation currently returns `Unsupported`.
+//! perform network calls. LocalRuntime delegates to `LocalVolumeStore`.
use std::sync::Arc;
@@ -20,8 +19,7 @@ use crate::volumes::VolumeInfo;
/// Internal trait for named-volume management.
///
-/// Implemented by both `LocalRuntime` and the REST runtime. Both return
-/// `Unsupported` until a managed volume backend is wired up.
+/// Implemented by `LocalRuntime` and the REST runtime.
#[allow(
clippy::double_must_use,
reason = "async_trait generates a must-use boxed future"
diff --git a/src/boxlite/src/vmm/controller/shim.rs b/src/boxlite/src/vmm/controller/shim.rs
index d01950ddf..16481e2dd 100644
--- a/src/boxlite/src/vmm/controller/shim.rs
+++ b/src/boxlite/src/vmm/controller/shim.rs
@@ -330,6 +330,7 @@ impl VmmController for ShimController {
memory_mib: config.memory_mib,
kernel: config.kernel.clone(),
fs_shares: config.fs_shares.clone(),
+ volume_access: Vec::new(),
block_devices: config.block_devices.clone(),
guest_entrypoint,
transport: config.transport.clone(),
@@ -374,7 +375,8 @@ impl VmmController for ShimController {
self.box_id.as_str(),
&self.options,
)
- .with_nested_virtualization(config.nested_virtualization);
+ .with_nested_virtualization(config.nested_virtualization)
+ .with_volume_access(config.volume_access.clone());
let spawned = spawner.spawn(&config_json, config.detach)?;
// spawn_duration: time to create Box subprocess
let shim_spawn_duration = shim_spawn_start.elapsed();
diff --git a/src/boxlite/src/vmm/controller/spawn.rs b/src/boxlite/src/vmm/controller/spawn.rs
index 1df500d97..ba720c4cd 100644
--- a/src/boxlite/src/vmm/controller/spawn.rs
+++ b/src/boxlite/src/vmm/controller/spawn.rs
@@ -46,6 +46,7 @@ pub struct ShimSpawner<'a> {
box_id: &'a str,
options: &'a BoxOptions,
nested_virtualization: bool,
+ volume_access: Vec<PathAccess>,
}
impl<'a> ShimSpawner<'a> {
@@ -61,6 +62,7 @@ impl<'a> ShimSpawner<'a> {
box_id,
options,
nested_virtualization: false,
+ volume_access: Vec::new(),
}
}
@@ -96,6 +98,11 @@ impl<'a> ShimSpawner<'a> {
self
}
+ pub fn with_volume_access(mut self, paths: Vec<PathAccess>) -> Self {
+ self.volume_access = paths;
+ self
+ }
+
/// Host files this shim's VM request needs to read. Empty unless the box
/// asked for nesting, so an ordinary box widens its sandbox by nothing.
fn required_probe_paths(&self) -> &'static [&'static str] {
@@ -117,6 +124,7 @@ impl<'a> ShimSpawner<'a> {
path,
writable: false,
})
+ .chain(self.volume_access.clone())
.collect()
}
@@ -379,6 +387,27 @@ mod tests {
}
}
+ #[test]
+ fn managed_volume_grants_include_only_the_payload() {
+ let layout = test_layout();
+ let options = BoxOptions::default();
+ let volume_root = PathBuf::from("/home/test/volumes/volume-id");
+ let payload = volume_root.join("_data");
+ let spawner = ShimSpawner::new(Path::new("/bin/true"), &layout, "box", &options)
+ .with_volume_access(vec![PathAccess {
+ path: payload.clone(),
+ writable: false,
+ }]);
+
+ let paths = spawner.additional_path_access();
+ assert!(
+ paths
+ .iter()
+ .any(|entry| entry.path == payload && !entry.writable)
+ );
+ assert!(!paths.iter().any(|entry| entry.path == volume_root));
+ }
+
#[test]
fn test_configure_env_sets_box_scoped_temp_dir() {
use crate::runtime::advanced_options::{AdvancedBoxOptions, SecurityOptions};
diff --git a/src/boxlite/src/vmm/mod.rs b/src/boxlite/src/vmm/mod.rs
index 53e0c9dca..709b0e0f9 100644
--- a/src/boxlite/src/vmm/mod.rs
+++ b/src/boxlite/src/vmm/mod.rs
@@ -229,6 +229,9 @@ pub struct InstanceSpec {
pub kernel: Option<PreparedKernel>,
/// Filesystem shares from host to guest
pub fs_shares: FsShares,
+ /// Managed-volume paths granted to the host-side jailer before spawn.
+ #[serde(skip)]
+ pub volume_access: Vec<crate::jailer::PathAccess>,
/// Block device attachments via virtio-blk
pub block_devices: BlockDevices,
/// Guest agent entrypoint (e.g., /boxlite/bin/boxlite-guest)
diff --git a/src/boxlite/src/vmm/native/tests/mod.rs b/src/boxlite/src/vmm/native/tests/mod.rs
index eda51c2f3..96fc7467d 100644
--- a/src/boxlite/src/vmm/native/tests/mod.rs
+++ b/src/boxlite/src/vmm/native/tests/mod.rs
@@ -87,6 +87,7 @@ impl TestBox {
memory_mib: Some(256),
kernel,
fs_shares: FsShares::new(),
+ volume_access: Vec::new(),
block_devices: BlockDevices::new(),
guest_entrypoint: Entrypoint {
executable: "/init".to_string(),
diff --git a/src/boxlite/src/volumes/container_volume.rs b/src/boxlite/src/volumes/container_volume.rs
index 55dd26f3d..bc65119ba 100644
--- a/src/boxlite/src/volumes/container_volume.rs
+++ b/src/boxlite/src/volumes/container_volume.rs
@@ -11,6 +11,17 @@ use std::path::PathBuf;
use super::guest_volume::GuestVolumeManager;
+/// The exact payload selected inside a container mount's shared directory.
+#[derive(Debug, Clone)]
+pub(crate) enum ContainerMountPayload {
+ /// Mount the shared directory itself.
+ WholeDirectory,
+ /// Bind one file from the staged share directory.
+ SingleFile { file_name: String },
+ /// Pin one relative directory from a managed volume payload.
+ ManagedSubDirectory { sub_path: String },
+}
+
/// Container bind mount entry.
///
/// Uses convention-based paths - guest constructs full path from volume_name:
@@ -27,9 +38,8 @@ pub struct ContainerMount {
pub owner_uid: u32,
/// Owner GID of host directory (for auto-idmap in guest)
pub owner_gid: u32,
- /// For a single-file mount, the file name to bind-mount from the staged
- /// share dir; `None` for a whole-directory mount.
- pub subpath: Option<String>,
+ /// Payload selected from the shared directory.
+ pub(crate) payload: ContainerMountPayload,
}
/// Manages container-level volume configuration.
@@ -79,7 +89,7 @@ impl<'a> ContainerVolumeManager<'a> {
read_only: bool,
owner_uid: u32,
owner_gid: u32,
- subpath: Option<String>,
+ payload: ContainerMountPayload,
) {
// Add virtiofs share to guest with container_id
// Guest will mount at convention path: /run/boxlite/shared/containers/{container_id}/volumes/{tag}
@@ -98,7 +108,7 @@ impl<'a> ContainerVolumeManager<'a> {
read_only,
owner_uid,
owner_gid,
- subpath,
+ payload,
});
}
@@ -113,7 +123,7 @@ impl<'a> ContainerVolumeManager<'a> {
read_only,
owner_uid: 0,
owner_gid: 0,
- subpath: None,
+ payload: ContainerMountPayload::WholeDirectory,
});
}
@@ -128,7 +138,7 @@ mod tests {
use super::*;
#[test]
- fn add_volume_carries_subpath_for_single_file() {
+ fn add_volume_carries_the_selected_payload() {
let mut guest = GuestVolumeManager::new();
let mut mgr = ContainerVolumeManager::new(&mut guest);
mgr.add_volume(
@@ -140,11 +150,17 @@ mod tests {
true,
0,
0,
- Some("app.conf".to_string()),
+ ContainerMountPayload::SingleFile {
+ file_name: "app.conf".to_string(),
+ },
);
let mounts = mgr.build_container_mounts();
assert_eq!(mounts.len(), 1);
- assert_eq!(mounts[0].subpath, Some("app.conf".to_string()));
+ assert!(matches!(
+ mounts[0].payload,
+ ContainerMountPayload::SingleFile { ref file_name }
+ if file_name == "app.conf"
+ ));
}
}
diff --git a/src/boxlite/src/volumes/local_store.rs b/src/boxlite/src/volumes/local_store.rs
new file mode 100644
index 000000000..20bd2a0b8
--- /dev/null
+++ b/src/boxlite/src/volumes/local_store.rs
@@ -0,0 +1,1795 @@
+use std::fs::{File, OpenOptions};
+use std::io::ErrorKind;
+use std::path::{Path, PathBuf};
+
+use boxlite_shared::errors::{BoxliteError, BoxliteResult};
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::VolumeInfo;
+use crate::litebox::BoxManager;
+use crate::litebox::config::BoxConfig;
+use crate::runtime::options::MountType;
+use crate::runtime::types::BoxState;
+
+const METADATA_FILE: &str = ".metadata.json";
+const PAYLOAD_DIR: &str = "_data";
+const REGISTRY_LOCK: &str = ".registry.lock";
+const STAGING_DIR: &str = ".staging";
+const TRASH_DIR: &str = ".trash";
+
+#[derive(Debug, Clone)]
+pub(crate) enum ResolvedLocalMountPayload {
+ WholeVolume,
+ SubDirectory { path: String },
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct ResolvedLocalMount {
+ pub volume_id: String,
+ pub payload_root: PathBuf,
+ pub target: String,
+ pub read_only: bool,
+ pub payload: ResolvedLocalMountPayload,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub(crate) enum VolumeReferenceMode {
+ Selector,
+ CanonicalId,
+}
+
+/// Managed-volume backend for the local runtime. Owns the on-disk layout
+/// under `~/.boxlite/volumes` (one canonical UUID directory per volume, with
+/// `.metadata.json` and a `_data/` payload) and serializes every mutation
+/// through a flock on `.registry.lock`.
+#[derive(Debug, Clone)]
+pub(crate) struct LocalVolumeStore {
+ root: PathBuf,
+ box_manager: BoxManager,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+struct VolumeMetadata {
+ version: u32,
+ id: String,
+ name: String,
+ created_at: DateTime<Utc>,
+}
+
+impl LocalVolumeStore {
+ pub(crate) fn new(root: PathBuf, box_manager: BoxManager) -> BoxliteResult<Self> {
+ for path in [root.clone(), root.join(STAGING_DIR), root.join(TRASH_DIR)] {
+ std::fs::create_dir_all(&path)
+ .map_err(|error| storage("create volume directory", &path, error))?;
+ }
+ let root = root
+ .canonicalize()
+ .map_err(|error| storage("resolve volume root", &root, error))?;
+ Ok(Self { root, box_manager })
+ }
+
+ /// Startup-only cleanup: remove leftovers from crashed staging or trash
+ /// operations. Never touches canonical volume directories.
+ pub(crate) fn recover(&self) -> BoxliteResult<()> {
+ self.recover_impl(|_| Ok(()))
+ }
+
+ fn recover_impl(
+ &self,
+ before_cleanup: impl Fn(&Path) -> BoxliteResult<()>,
+ ) -> BoxliteResult<()> {
+ self.with_registry_lock(true, || {
+ for directory in [STAGING_DIR, TRASH_DIR] {
+ let root = self.root.join(directory);
+ let entries = std::fs::read_dir(&root)
+ .map_err(|error| storage("read volume recovery directory", &root, error))?;
+ for entry in entries {
+ let entry = entry
+ .map_err(|error| storage("read volume recovery entry", &root, error))?;
+ let path = entry.path();
+ let result = before_cleanup(&path).and_then(|()| remove_entry_nofollow(&path));
+ if let Err(error) = result {
+ tracing::error!(path = %path.display(), %error, "Failed to remove local volume recovery entry");
+ }
+ }
+ }
+ Ok(())
+ })
+ }
+
+ pub(crate) fn create(&self, name: Option<&str>) -> BoxliteResult<VolumeInfo> {
+ self.create_impl(name, |_, _| {})
+ }
+
+ fn create_impl(
+ &self,
+ name: Option<&str>,
+ before_publish: impl FnOnce(&str, &Path),
+ ) -> BoxliteResult<VolumeInfo> {
+ if let Some(name) = name {
+ validate_name(name)?;
+ if validate_id(name).is_ok() {
+ return Err(BoxliteError::InvalidArgument(format!(
+ "volume name {name:?} must not be a canonical UUID"
+ )));
+ }
+ }
+ self.with_registry_lock(true, || {
+ let existing = self.scan_valid()?;
+ if let Some(name) = name
+ && existing.iter().any(|volume| volume.name == name)
+ {
+ return Err(BoxliteError::AlreadyExists(format!("volume name {name:?}")));
+ }
+
+ let id = Uuid::new_v4().to_string();
+ let final_path = self.root.join(&id);
+ if path_exists(&final_path)? {
+ return Err(BoxliteError::AlreadyExists(format!("volume id {id}")));
+ }
+ let name = name.unwrap_or(&id).to_string();
+ let metadata = VolumeMetadata {
+ version: 1,
+ id: id.clone(),
+ name: name.clone(),
+ created_at: Utc::now(),
+ };
+ // Build the volume inside .staging, then rename it into place so
+ // a partially written volume never appears in the registry.
+ let operation = Uuid::new_v4().simple().to_string();
+ let staging = self.root.join(STAGING_DIR).join(&operation);
+ std::fs::create_dir(&staging)
+ .map_err(|error| storage("create volume staging", &staging, error))?;
+ if let Err(error) = std::fs::create_dir(staging.join(PAYLOAD_DIR)) {
+ let _ = std::fs::remove_dir_all(&staging);
+ return Err(storage("create volume payload", &staging, error));
+ }
+ let metadata_path = staging.join(METADATA_FILE);
+ let write_result = serde_json::to_vec_pretty(&metadata)
+ .map_err(|error| {
+ BoxliteError::Internal(format!("serialize volume metadata: {error}"))
+ })
+ .and_then(|json| {
+ std::fs::write(&metadata_path, json)
+ .map_err(|error| volume_storage(&id, "write volume metadata", error))
+ });
+ if let Err(error) = write_result {
+ let _ = std::fs::remove_dir_all(&staging);
+ return Err(error);
+ }
+ // Hook runs before the rename publishes the volume (used by
+ // callers that must observe the payload while it is still hidden).
+ before_publish(&id, &staging);
+ if let Err(error) = std::fs::rename(&staging, &final_path) {
+ let _ = std::fs::remove_dir_all(&staging);
+ return Err(volume_storage(&id, "publish volume", error));
+ }
+ Ok(VolumeInfo {
+ id,
+ name,
+ created_at: metadata.created_at,
+ size_bytes: None,
+ })
+ })
+ }
+
+ pub(crate) fn list(&self) -> BoxliteResult<Vec<VolumeInfo>> {
+ self.with_registry_lock(false, || {
+ let mut volumes = Vec::new();
+ for entry in self.canonical_entries()? {
+ let id = entry
+ .file_name()
+ .and_then(|name| name.to_str())
+ .unwrap_or_default()
+ .to_owned();
+ match self.read_info(&entry) {
+ Ok(info) => volumes.push(info),
+ Err(error) => {
+ tracing::warn!(volume_id = %id, %error, "Skipping invalid local volume");
+ }
+ }
+ }
+ volumes.sort_by(|left, right| {
+ right
+ .created_at
+ .cmp(&left.created_at)
+ .then_with(|| left.id.cmp(&right.id))
+ });
+ Ok(volumes)
+ })
+ }
+
+ pub(crate) fn get(&self, id: &str) -> BoxliteResult<VolumeInfo> {
+ validate_id(id)?;
+ self.with_registry_lock(false, || {
+ let path = self.root.join(id);
+ if !path_exists(&path)? {
+ return Err(BoxliteError::NotFound(format!("volume {id}")));
+ }
+ self.read_info(&path)
+ })
+ }
+
+ pub(crate) fn remove(&self, id: &str, force: bool) -> BoxliteResult<()> {
+ self.remove_impl(id, force, |_| Ok(()))
+ }
+
+ fn remove_impl(
+ &self,
+ id: &str,
+ force: bool,
+ before_cleanup: impl FnOnce(&Path) -> BoxliteResult<()>,
+ ) -> BoxliteResult<()> {
+ validate_id(id)?;
+ let Some(trash) = self.with_registry_lock(true, || {
+ let path = self.root.join(id);
+ if !path_exists(&path)? {
+ return if force {
+ Ok(None)
+ } else {
+ Err(BoxliteError::NotFound(format!("volume {id}")))
+ };
+ }
+ // Refuse deletion while any box still mounts this volume, in
+ // either the legacy or typed mount format.
+ for config in self.box_manager.all_box_configs()? {
+ let legacy_holder = config
+ .options
+ .volumes
+ .iter()
+ .any(|mount| mount.managed_volume.as_deref() == Some(id));
+ let typed_holder = config.options.mounts.iter().any(|mount| {
+ mount.mount_type == MountType::Volume && mount.source.as_deref() == Some(id)
+ });
+ if legacy_holder || typed_holder {
+ return Err(BoxliteError::InvalidState(format!(
+ "volume {id} is still referenced by box {}",
+ config.id
+ )));
+ }
+ }
+
+ // Rename out of the registry first so the volume disappears
+ // atomically; deleting the payload below is best-effort — a crash
+ // mid-way leaves trash for recover() to clean on next startup.
+ let operation = Uuid::new_v4().simple().to_string();
+ let trash = self.root.join(TRASH_DIR).join(operation);
+ if path_exists(&trash)? {
+ return Err(BoxliteError::AlreadyExists(format!(
+ "volume remove operation for {id}"
+ )));
+ }
+ std::fs::rename(&path, &trash)
+ .map_err(|error| storage("move volume to trash", &path, error))?;
+ Ok(Some(trash))
+ })?
+ else {
+ return Ok(());
+ };
+ let result = before_cleanup(&trash).and_then(|()| remove_entry_nofollow(&trash));
+ if let Err(error) = result {
+ tracing::error!(volume_id = %id, path = %trash.display(), %error, "Failed to remove local volume payload from trash");
+ }
+ Ok(())
+ }
+
+ pub(crate) fn add_box_with_resolved_volumes(
+ &self,
+ config: &mut BoxConfig,
+ state: &BoxState,
+ mode: VolumeReferenceMode,
+ ) -> BoxliteResult<()> {
+ self.add_box_impl(config, state, mode, None, || {})
+ }
+
+ pub(crate) fn add_clone_box_with_resolved_volumes(
+ &self,
+ config: &mut BoxConfig,
+ state: &BoxState,
+ mode: VolumeReferenceMode,
+ base_disk_id: &crate::BaseDiskID,
+ ) -> BoxliteResult<()> {
+ self.add_box_impl(config, state, mode, Some(base_disk_id), || {})
+ }
+
+ fn add_box_impl(
+ &self,
+ config: &mut BoxConfig,
+ state: &BoxState,
+ mode: VolumeReferenceMode,
+ base_disk_id: Option<&crate::BaseDiskID>,
+ before_commit: impl FnOnce(),
+ ) -> BoxliteResult<()> {
+ let has_managed = config
+ .options
+ .volumes
+ .iter()
+ .any(|mount| mount.managed_volume.is_some())
+ || config
+ .options
+ .mounts
+ .iter()
+ .any(|mount| mount.mount_type == MountType::Volume);
+ if !has_managed {
+ return self.persist_box(config, state, base_disk_id);
+ }
+ // Persist canonical ids, never user selectors: the stored config must
+ // stay resolvable regardless of later resolution rules. Selector
+ // resolution and duplicate rejection share the registry's exclusive
+ // lock with holder registration.
+ self.with_registry_lock(true, || {
+ if !config.options.volumes.is_empty() && !config.options.mounts.is_empty() {
+ return Err(BoxliteError::InvalidArgument(
+ "volumes and mounts cannot both be non-empty".into(),
+ ));
+ }
+ let mut volume_ids = std::collections::HashSet::new();
+ for mount in &mut config.options.volumes {
+ if let Some(selector) = mount.managed_volume.clone() {
+ let volume = self.resolve_selector(&selector, mode)?;
+ if !volume_ids.insert(volume.id.clone()) {
+ return Err(BoxliteError::InvalidArgument(format!(
+ "volume {} is mounted more than once in box {}",
+ volume.id, config.id
+ )));
+ }
+ mount.managed_volume = Some(volume.id);
+ mount.host_path.clear();
+ }
+ }
+ for mount in &mut config.options.mounts {
+ if mount.mount_type != MountType::Volume {
+ continue;
+ }
+ let selector = mount.source.clone().ok_or_else(|| {
+ BoxliteError::InvalidArgument("volume mount is missing a source".into())
+ })?;
+ let volume = self.resolve_selector(&selector, mode)?;
+ if let Some(sub_path) = mount.sub_path.as_deref() {
+ validate_sub_path(&self.root.join(&volume.id).join(PAYLOAD_DIR), sub_path)?;
+ }
+ if !volume_ids.insert(volume.id.clone()) {
+ return Err(BoxliteError::InvalidArgument(format!(
+ "volume {} is mounted more than once in box {}",
+ volume.id, config.id
+ )));
+ }
+ mount.source = Some(volume.id);
+ }
+ before_commit();
+ self.persist_box(config, state, base_disk_id)
+ })
+ }
+
+ fn persist_box(
+ &self,
+ config: &BoxConfig,
+ state: &BoxState,
+ base_disk_id: Option<&crate::BaseDiskID>,
+ ) -> BoxliteResult<()> {
+ match base_disk_id {
+ Some(id) => self.box_manager.add_clone_box(config, state, id),
+ None => self.box_manager.add_box(config, state),
+ }
+ }
+
+ /// Resolve every managed-volume reference (legacy and typed formats) to
+ /// its current payload path for a box boot. Mirrors the validation in
+ /// add_box_impl so a persisted config always boots.
+ pub(crate) fn resolve_for_boot(
+ &self,
+ options: &crate::runtime::options::BoxOptions,
+ ) -> BoxliteResult<Vec<ResolvedLocalMount>> {
+ if !options.volumes.is_empty() && !options.mounts.is_empty() {
+ return Err(BoxliteError::InvalidArgument(
+ "volumes and mounts cannot both be non-empty".into(),
+ ));
+ }
+ let has_managed = options
+ .volumes
+ .iter()
+ .any(|mount| mount.managed_volume.is_some())
+ || options
+ .mounts
+ .iter()
+ .any(|mount| mount.mount_type == MountType::Volume);
+ if !has_managed {
+ return Ok(Vec::new());
+ }
+ self.with_registry_lock(false, || {
+ let mut resolved = Vec::new();
+ let mut volume_ids = std::collections::HashSet::new();
+ for mount in &options.volumes {
+ let Some(selector) = mount.managed_volume.as_deref() else {
+ continue;
+ };
+ let volume = self.resolve_selector(selector, VolumeReferenceMode::CanonicalId)?;
+ if !volume_ids.insert(volume.id.clone()) {
+ return Err(BoxliteError::InvalidArgument(format!(
+ "volume {} is mounted more than once",
+ volume.id
+ )));
+ }
+ resolved.push(ResolvedLocalMount {
+ payload_root: self.root.join(&volume.id).join(PAYLOAD_DIR),
+ volume_id: volume.id,
+ target: mount.guest_path.clone(),
+ read_only: mount.read_only,
+ payload: ResolvedLocalMountPayload::WholeVolume,
+ });
+ }
+ for mount in &options.mounts {
+ if mount.mount_type != MountType::Volume {
+ continue;
+ }
+ let selector = mount.source.as_deref().ok_or_else(|| {
+ BoxliteError::InvalidArgument("volume mount is missing a source".into())
+ })?;
+ let volume = self.resolve_selector(selector, VolumeReferenceMode::CanonicalId)?;
+ let payload = match mount.sub_path.as_deref() {
+ None => ResolvedLocalMountPayload::WholeVolume,
+ Some(path) => {
+ validate_sub_path(&self.root.join(&volume.id).join(PAYLOAD_DIR), path)?;
+ ResolvedLocalMountPayload::SubDirectory {
+ path: path.to_owned(),
+ }
+ }
+ };
+ if !volume_ids.insert(volume.id.clone()) {
+ return Err(BoxliteError::InvalidArgument(format!(
+ "volume {} is mounted more than once",
+ volume.id
+ )));
+ }
+ resolved.push(ResolvedLocalMount {
+ payload_root: self.root.join(&volume.id).join(PAYLOAD_DIR),
+ volume_id: volume.id,
+ target: mount.target.clone(),
+ read_only: mount.read_only,
+ payload,
+ });
+ }
+ Ok(resolved)
+ })
+ }
+
+ fn resolve_selector(
+ &self,
+ selector: &str,
+ mode: VolumeReferenceMode,
+ ) -> BoxliteResult<VolumeInfo> {
+ match mode {
+ VolumeReferenceMode::CanonicalId => {
+ validate_id(selector)?;
+ let path = self.root.join(selector);
+ if !path_exists(&path)? {
+ return Err(BoxliteError::NotFound(format!("volume {selector}")));
+ }
+ self.read_info(&path)
+ }
+ VolumeReferenceMode::Selector => {
+ validate_name(selector)?;
+ if validate_id(selector).is_ok() {
+ let path = self.root.join(selector);
+ if path_exists(&path)? {
+ return self.read_info(&path);
+ }
+ }
+ let volume = self
+ .scan_valid()?
+ .into_iter()
+ .find(|volume| volume.name == selector)
+ .ok_or_else(|| BoxliteError::NotFound(format!("volume {selector}")))?;
+ self.read_info(&self.root.join(&volume.id))
+ }
+ }
+ }
+
+ fn scan_valid(&self) -> BoxliteResult<Vec<VolumeInfo>> {
+ let mut volumes = Vec::new();
+ let mut names = std::collections::HashSet::new();
+ for path in self.canonical_entries()? {
+ let info = self.read_metadata(&path)?;
+ if !names.insert(info.name.clone()) {
+ return Err(BoxliteError::MetadataError(format!(
+ "duplicate volume name {:?} in local store",
+ info.name
+ )));
+ }
+ volumes.push(info);
+ }
+ Ok(volumes)
+ }
+
+ fn canonical_entries(&self) -> BoxliteResult<Vec<PathBuf>> {
+ let entries = std::fs::read_dir(&self.root)
+ .map_err(|error| storage("list volumes", &self.root, error))?;
+ let mut paths = Vec::new();
+ for entry in entries {
+ let entry = match entry {
+ Ok(entry) => entry,
+ Err(error) => {
+ tracing::warn!(%error, "Skipping unreadable local volume entry");
+ continue;
+ }
+ };
+ let name = entry.file_name();
+ let Some(name) = name.to_str() else {
+ continue;
+ };
+ if Uuid::parse_str(name).is_ok_and(|id| id.to_string() == name) {
+ paths.push(entry.path());
+ }
+ }
+ Ok(paths)
+ }
+
+ fn read_metadata(&self, path: &Path) -> BoxliteResult<VolumeInfo> {
+ let id = path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .ok_or_else(|| BoxliteError::Internal("volume path has no UTF-8 id".into()))?;
+ let metadata_path = path.join(METADATA_FILE);
+ let json = std::fs::read_to_string(&metadata_path)
+ .map_err(|error| volume_storage(id, "read volume metadata", error))?;
+ let metadata: VolumeMetadata = serde_json::from_str(&json).map_err(|error| {
+ BoxliteError::MetadataError(format!("volume {id} has invalid metadata: {error}"))
+ })?;
+ if metadata.version != 1 {
+ return Err(BoxliteError::MetadataError(format!(
+ "volume {id} uses unsupported metadata version {}",
+ metadata.version
+ )));
+ }
+ if metadata.id != id {
+ return Err(BoxliteError::MetadataError(format!(
+ "volume directory id {id} does not match metadata id {:?}",
+ metadata.id
+ )));
+ }
+ validate_name(&metadata.name)
+ .map_err(|error| BoxliteError::MetadataError(error.to_string()))?;
+ Ok(VolumeInfo {
+ id: metadata.id,
+ name: metadata.name,
+ created_at: metadata.created_at,
+ size_bytes: None,
+ })
+ }
+
+ fn read_info(&self, path: &Path) -> BoxliteResult<VolumeInfo> {
+ let info = self.read_metadata(path)?;
+ let payload = path.join(PAYLOAD_DIR);
+ let payload_metadata = match std::fs::symlink_metadata(&payload) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == ErrorKind::NotFound => {
+ return Err(BoxliteError::MetadataError(format!(
+ "volume {} payload is missing",
+ info.id
+ )));
+ }
+ Err(error) => return Err(volume_storage(&info.id, "inspect volume payload", error)),
+ };
+ if !payload_metadata.file_type().is_dir() || payload_metadata.file_type().is_symlink() {
+ return Err(BoxliteError::MetadataError(format!(
+ "volume {} payload is not a real directory",
+ info.id
+ )));
+ }
+ Ok(info)
+ }
+
+ /// flock-based cross-process lock over the registry: LOCK_EX for mutations
+ /// (create/remove/add_box), LOCK_SH for reads. Holder checks and renames
+ /// run inside one critical section with resolution, so there is no
+ /// TOCTOU window between "no box references this volume" and its removal.
+ /// The guard releases on drop, including on early returns.
+ fn with_registry_lock<T>(
+ &self,
+ exclusive: bool,
+ operation: impl FnOnce() -> BoxliteResult<T>,
+ ) -> BoxliteResult<T> {
+ let lock_path = self.root.join(REGISTRY_LOCK);
+ let file = OpenOptions::new()
+ .create(true)
+ .read(true)
+ .write(true)
+ .truncate(false)
+ .open(&lock_path)
+ .map_err(|error| storage("open volume registry lock", &lock_path, error))?;
+ let operation_flags = if exclusive {
+ libc::LOCK_EX
+ } else {
+ libc::LOCK_SH
+ };
+ flock(&file, operation_flags)?;
+ let _guard = RegistryLockGuard(file);
+ operation()
+ }
+}
+
+struct RegistryLockGuard(File);
+
+impl Drop for RegistryLockGuard {
+ fn drop(&mut self) {
+ let result = unsafe { libc::flock(self.0.as_raw_fd(), libc::LOCK_UN) };
+ if result != 0 {
+ tracing::warn!(error = %std::io::Error::last_os_error(), "Failed to unlock volume registry");
+ }
+ }
+}
+
+use std::os::unix::io::AsRawFd;
+
+fn flock(file: &File, operation: i32) -> BoxliteResult<()> {
+ loop {
+ let result = unsafe { libc::flock(file.as_raw_fd(), operation) };
+ if result == 0 {
+ return Ok(());
+ }
+ let error = std::io::Error::last_os_error();
+ if error.kind() == ErrorKind::Interrupted {
+ continue;
+ }
+ return Err(BoxliteError::Storage(format!(
+ "failed to lock volume registry: {error}"
+ )));
+ }
+}
+
+fn path_exists(path: &Path) -> BoxliteResult<bool> {
+ match std::fs::symlink_metadata(path) {
+ Ok(_) => Ok(true),
+ Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
+ Err(error) => Err(storage("inspect path", path, error)),
+ }
+}
+
+/// Delete a trash entry without ever following a symlink out of the trash dir.
+fn remove_entry_nofollow(path: &Path) -> BoxliteResult<()> {
+ let metadata = std::fs::symlink_metadata(path)
+ .map_err(|error| storage("inspect volume trash", path, error))?;
+ if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
+ std::fs::remove_file(path).map_err(|error| storage("remove volume trash", path, error))
+ } else {
+ std::fs::remove_dir_all(path).map_err(|error| storage("remove volume trash", path, error))
+ }
+}
+
+fn validate_id(id: &str) -> BoxliteResult<()> {
+ if Uuid::parse_str(id).is_ok_and(|parsed| parsed.to_string() == id) {
+ Ok(())
+ } else {
+ Err(BoxliteError::InvalidArgument(format!(
+ "volume id {id:?} is not a canonical UUID"
+ )))
+ }
+}
+
+fn validate_name(name: &str) -> BoxliteResult<()> {
+ let valid = (2..=255).contains(&name.len())
+ && name
+ .bytes()
+ .next()
+ .is_some_and(|byte| byte.is_ascii_alphanumeric())
+ && name
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'));
+ if valid {
+ Ok(())
+ } else {
+ Err(BoxliteError::InvalidArgument(format!(
+ "invalid volume name {name:?}; expected 2-255 characters of [a-zA-Z0-9][a-zA-Z0-9_.-]"
+ )))
+ }
+}
+
+/// Reject path traversal up front, then verify every component actually
+/// resolves inside `payload_root` via an O_NOFOLLOW openat walk.
+fn validate_sub_path(payload_root: &Path, sub_path: &str) -> BoxliteResult<()> {
+ if sub_path.is_empty()
+ || sub_path.contains('\0')
+ || sub_path.len() > 4096
+ || sub_path.starts_with('/')
+ || sub_path.ends_with('/')
+ || sub_path.split('/').count() > 64
+ || sub_path
+ .split('/')
+ .any(|part| part.is_empty() || part == "." || part == "..")
+ || sub_path.split('/').any(|part| part.len() > 255)
+ {
+ return Err(BoxliteError::InvalidArgument(format!(
+ "invalid volume sub_path {sub_path:?}"
+ )));
+ }
+
+ use nix::fcntl::{OFlag, open, openat};
+ use nix::sys::stat::Mode;
+ let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC | OFlag::O_NOFOLLOW;
+ let mut directory = open(payload_root, flags, Mode::empty())
+ .map_err(|error| sub_path_io_error(payload_root, error))?;
+ for component in sub_path.split('/') {
+ directory = openat(&directory, component, flags, Mode::empty())
+ .map_err(|error| sub_path_io_error(payload_root, error))?;
+ }
+ Ok(())
+}
+
+fn sub_path_io_error(_root: &Path, error: nix::errno::Errno) -> BoxliteError {
+ match error {
+ nix::errno::Errno::ENOENT => {
+ BoxliteError::NotFound("volume sub_path does not exist".into())
+ }
+ nix::errno::Errno::ELOOP | nix::errno::Errno::ENOTDIR => BoxliteError::InvalidArgument(
+ "volume sub_path contains a symlink or non-directory component".into(),
+ ),
+ _ => BoxliteError::Storage(format!("failed to resolve volume sub_path: {error}")),
+ }
+}
+
+/// Error constructors deliberately omit internal volume paths: public errors
+/// must not leak where the runtime stores payloads on the host.
+fn storage(action: &str, _path: &Path, error: std::io::Error) -> BoxliteError {
+ BoxliteError::Storage(format!("{action}: {error}"))
+}
+
+fn volume_storage(id: &str, action: &str, error: std::io::Error) -> BoxliteError {
+ BoxliteError::Storage(format!("{action} for volume {id}: {error}"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::runtime::options::{BoxOptions, BoxliteOptions, MountSpec, VolumeSpec};
+ use crate::runtime::rt_impl::RuntimeImpl;
+ use std::sync::Arc;
+
+ #[tokio::test]
+ async fn boot_resolution_returns_canonical_id_and_current_payload() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ let options = BoxOptions {
+ volumes: vec![VolumeSpec {
+ read_only: true,
+ ..VolumeSpec::managed_volume(&volume.id, "/workspace")
+ }],
+ ..Default::default()
+ };
+
+ let resolved = runtime
+ .local_volume_store
+ .resolve_for_boot(&options)
+ .expect("resolve a persisted volume for boot");
+ assert_eq!(resolved.len(), 1);
+ assert_eq!(resolved[0].volume_id, volume.id);
+ let expected_root = home
+ .path()
+ .canonicalize()
+ .unwrap()
+ .join("volumes")
+ .join(&volume.id)
+ .join(PAYLOAD_DIR);
+ assert_eq!(resolved[0].payload_root, expected_root);
+ assert_eq!(resolved[0].target, "/workspace");
+ assert!(resolved[0].read_only);
+ assert!(matches!(
+ resolved[0].payload,
+ ResolvedLocalMountPayload::WholeVolume
+ ));
+ assert!(resolved[0].payload_root.is_dir());
+ }
+
+ #[tokio::test]
+ async fn boot_resolution_without_managed_volumes_skips_registry_lock() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let store = runtime.local_volume_store.clone();
+ let (ready_sender, ready_receiver) = std::sync::mpsc::channel();
+ let (release_sender, release_receiver) = std::sync::mpsc::channel();
+ let lock_task = tokio::task::spawn_blocking(move || {
+ store.create_impl(Some("lock-holder"), move |_, _| {
+ ready_sender.send(()).unwrap();
+ release_receiver.recv().unwrap();
+ })
+ });
+ ready_receiver.recv().unwrap();
+
+ let store = runtime.local_volume_store.clone();
+ let mut resolve_task = tokio::task::spawn_blocking(move || {
+ store.resolve_for_boot(&BoxOptions {
+ volumes: vec![VolumeSpec::bind_mount("/tmp", "/data")],
+ ..Default::default()
+ })
+ });
+ let result =
+ tokio::time::timeout(std::time::Duration::from_secs(5), &mut resolve_task).await;
+ release_sender.send(()).unwrap();
+ lock_task.await.unwrap().unwrap();
+
+ let resolved = match result {
+ Ok(result) => result.unwrap().unwrap(),
+ Err(_) => {
+ resolve_task.await.unwrap().unwrap();
+ panic!("host-only boot resolution must not wait for the registry lock");
+ }
+ };
+ assert!(resolved.is_empty());
+ }
+
+ #[tokio::test]
+ async fn boot_resolution_validates_sub_path_without_changing_share_root() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ let payload = runtime
+ .layout
+ .volumes_dir()
+ .join(&volume.id)
+ .join(PAYLOAD_DIR);
+ std::fs::create_dir_all(payload.join("team/backend")).unwrap();
+ std::fs::create_dir_all(payload.join("sibling")).unwrap();
+ std::os::unix::fs::symlink("sibling", payload.join("team/link")).unwrap();
+ let options = |sub_path: &str| BoxOptions {
+ mounts: vec![MountSpec {
+ sub_path: Some(sub_path.to_owned()),
+ ..MountSpec::volume_mount(&volume.id, "/workspace")
+ }],
+ ..Default::default()
+ };
+
+ let resolved = runtime
+ .local_volume_store
+ .resolve_for_boot(&options("team/backend"))
+ .expect("accept an existing subdirectory");
+ assert!(matches!(
+ resolved[0].payload,
+ ResolvedLocalMountPayload::SubDirectory { ref path }
+ if path == "team/backend"
+ ));
+ assert!(resolved[0].payload_root.ends_with("_data"));
+
+ for invalid in [
+ "/etc",
+ "../escape",
+ "team//backend",
+ "team/./backend",
+ "team/link",
+ "team/\0backend",
+ ] {
+ let error = runtime
+ .local_volume_store
+ .resolve_for_boot(&options(invalid))
+ .err()
+ .unwrap_or_else(|| panic!("{invalid} must be rejected"));
+ assert!(
+ matches!(error, BoxliteError::InvalidArgument(_)),
+ "{invalid}: {error:?}"
+ );
+ }
+ let error = runtime
+ .local_volume_store
+ .resolve_for_boot(&options("team/missing"))
+ .expect_err("a missing subdirectory must fail");
+ assert!(matches!(error, BoxliteError::NotFound(_)), "{error:?}");
+ }
+
+ #[tokio::test]
+ async fn recovery_removes_only_hidden_operation_directories() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ for directory in [STAGING_DIR, TRASH_DIR] {
+ let operation = runtime
+ .layout
+ .volumes_dir()
+ .join(directory)
+ .join("operation");
+ std::fs::create_dir_all(operation.join("nested")).unwrap();
+ std::fs::write(operation.join("nested/file"), b"temporary").unwrap();
+ }
+
+ drop(runtime);
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .expect("runtime initialization must recover local volumes");
+
+ for directory in [STAGING_DIR, TRASH_DIR] {
+ assert!(
+ std::fs::read_dir(runtime.layout.volumes_dir().join(directory))
+ .unwrap()
+ .next()
+ .is_none()
+ );
+ }
+ assert_eq!(
+ runtime.local_volume_store.get(&volume.id).unwrap().name,
+ "workspace"
+ );
+ }
+
+ #[tokio::test]
+ async fn removal_succeeds_when_physical_trash_cleanup_fails() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ let payload = runtime
+ .layout
+ .volumes_dir()
+ .join(&volume.id)
+ .join(PAYLOAD_DIR);
+ std::fs::write(payload.join("keep"), b"payload").unwrap();
+
+ let result = runtime
+ .local_volume_store
+ .remove_impl(&volume.id, false, |_| {
+ Err(BoxliteError::Storage("injected cleanup failure".into()))
+ });
+ let trash_entry = std::fs::read_dir(runtime.layout.volumes_dir().join(TRASH_DIR))
+ .unwrap()
+ .next()
+ .unwrap()
+ .unwrap()
+ .path();
+
+ assert!(trash_entry.join(PAYLOAD_DIR).join("keep").exists());
+ result.expect("logical removal succeeds after the rename to trash");
+ assert!(matches!(
+ runtime.local_volume_store.get(&volume.id),
+ Err(BoxliteError::NotFound(_))
+ ));
+ }
+
+ #[tokio::test]
+ async fn physical_trash_cleanup_runs_outside_registry_lock() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ let store = runtime.local_volume_store.clone();
+ let volume_id = volume.id.clone();
+ let (ready_sender, ready_receiver) = std::sync::mpsc::channel();
+ let (release_sender, release_receiver) = std::sync::mpsc::channel();
+ let remove_task = tokio::task::spawn_blocking(move || {
+ store.remove_impl(&volume_id, false, move |_| {
+ ready_sender.send(()).unwrap();
+ release_receiver.recv().unwrap();
+ Ok(())
+ })
+ });
+ ready_receiver.recv().unwrap();
+
+ let store = runtime.local_volume_store.clone();
+ let mut create_task =
+ tokio::task::spawn_blocking(move || store.create(Some("after-rename")));
+ let result =
+ tokio::time::timeout(std::time::Duration::from_secs(5), &mut create_task).await;
+ release_sender.send(()).unwrap();
+ remove_task.await.unwrap().unwrap();
+
+ match result {
+ Ok(result) => {
+ result.unwrap().unwrap();
+ }
+ Err(_) => {
+ create_task.await.unwrap().unwrap();
+ panic!("physical trash cleanup must not hold the registry lock");
+ }
+ }
+ assert!(matches!(
+ runtime.local_volume_store.get(&volume.id),
+ Err(BoxliteError::NotFound(_))
+ ));
+ }
+
+ #[tokio::test]
+ async fn recovery_ignores_cleanup_failure_and_runtime_reopens() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let operation = runtime
+ .layout
+ .volumes_dir()
+ .join(TRASH_DIR)
+ .join("operation");
+ let nested = operation.join("nested");
+ std::fs::create_dir_all(&nested).unwrap();
+ std::fs::write(nested.join("keep"), b"payload").unwrap();
+
+ runtime
+ .local_volume_store
+ .recover_impl(|_| Err(BoxliteError::Storage("injected cleanup failure".into())))
+ .expect("physical cleanup failure must not block recovery");
+ assert!(operation.exists());
+
+ drop(runtime);
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .expect("runtime must reopen after cleanup failure");
+ runtime.local_volume_store.recover().unwrap();
+ assert!(!operation.exists());
+ }
+
+ #[tokio::test]
+ async fn public_errors_do_not_leak_internal_volume_paths() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ std::fs::remove_file(
+ runtime
+ .layout
+ .volumes_dir()
+ .join(&volume.id)
+ .join(METADATA_FILE),
+ )
+ .unwrap();
+
+ let error = runtime
+ .local_volume_store
+ .get(&volume.id)
+ .expect_err("missing metadata must fail");
+ assert!(
+ !error.to_string().contains(home.path().to_str().unwrap()),
+ "internal home path leaked in {error}"
+ );
+ assert!(
+ error.to_string().contains(&volume.id),
+ "the failing volume id is missing from {error}"
+ );
+ }
+
+ #[tokio::test]
+ async fn corrupted_metadata_is_isolated_and_removable() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let good = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ let bad_id = Uuid::new_v4().to_string();
+ let bad_path = runtime.layout.volumes_dir().join(&bad_id);
+ std::fs::create_dir_all(&bad_path).unwrap();
+ std::fs::write(bad_path.join(METADATA_FILE), b"not json").unwrap();
+
+ let listed = runtime.local_volume_store.list().unwrap();
+ assert_eq!(listed.len(), 1);
+ assert_eq!(listed[0].id, good.id);
+ let error = runtime
+ .local_volume_store
+ .get(&bad_id)
+ .expect_err("corrupt metadata must be diagnosable");
+ assert!(matches!(error, BoxliteError::MetadataError(_)), "{error:?}");
+ runtime.local_volume_store.remove(&bad_id, false).unwrap();
+ assert_eq!(runtime.local_volume_store.list().unwrap().len(), 1);
+ }
+
+ #[tokio::test]
+ async fn publish_failure_cleans_staging_without_overwriting_existing_entry() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let store = runtime.local_volume_store.clone();
+ let occupied_id = Arc::new(std::sync::Mutex::new(String::new()));
+ let occupied_id_for_hook = Arc::clone(&occupied_id);
+ let root_for_hook = store.root.clone();
+ let error = store
+ .create_impl(Some("workspace"), move |id, _staging| {
+ *occupied_id_for_hook.lock().unwrap() = id.to_owned();
+ let final_path = root_for_hook.join(id);
+ std::fs::create_dir_all(&final_path).unwrap();
+ std::fs::write(final_path.join("keep"), b"original").unwrap();
+ })
+ .expect_err("the occupied id must make publish fail");
+ assert!(matches!(error, BoxliteError::Storage(_)), "{error:?}");
+ let final_path = store.root.join(occupied_id.lock().unwrap().as_str());
+ assert_eq!(std::fs::read(final_path.join("keep")).unwrap(), b"original");
+ assert!(runtime.local_volume_store.list().unwrap().is_empty());
+ assert!(
+ std::fs::read_dir(store.root.join(STAGING_DIR))
+ .unwrap()
+ .next()
+ .is_none()
+ );
+ }
+
+ #[tokio::test]
+ async fn worker_completion_after_caller_drop_leaves_manageable_volume() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let store = runtime.local_volume_store.clone();
+ let (ready_sender, ready_receiver) = std::sync::mpsc::channel();
+ let (release_sender, release_receiver) = std::sync::mpsc::channel();
+ let task = tokio::task::spawn_blocking(move || {
+ store.create_impl(Some("workspace"), move |_, _| {
+ ready_sender.send(()).unwrap();
+ release_receiver.recv().unwrap();
+ })
+ });
+ ready_receiver.recv().unwrap();
+ drop(task);
+ release_sender.send(()).unwrap();
+
+ let mut volumes = Vec::new();
+ for _ in 0..100 {
+ volumes = runtime.local_volume_store.list().unwrap();
+ if !volumes.is_empty() {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ assert_eq!(volumes.len(), 1);
+ runtime.local_volume_store.get(&volumes[0].id).unwrap();
+ runtime
+ .local_volume_store
+ .remove(&volumes[0].id, false)
+ .unwrap();
+ }
+
+ #[tokio::test]
+ async fn box_commit_after_caller_drop_is_manageable_and_recovers_on_restart() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ let store = runtime.local_volume_store.clone();
+ let (ready_sender, ready_receiver) = std::sync::mpsc::channel();
+ let (release_sender, release_receiver) = std::sync::mpsc::channel();
+ let lock_task = tokio::task::spawn_blocking(move || {
+ store.create_impl(Some("lock-holder"), move |_, _| {
+ ready_sender.send(()).unwrap();
+ release_receiver.recv().unwrap();
+ })
+ });
+ ready_receiver.recv().unwrap();
+
+ let create_runtime = Arc::clone(&runtime);
+ let volume_id = volume.id.clone();
+ let create = create_runtime.create(
+ BoxOptions {
+ volumes: vec![VolumeSpec::managed_volume(&volume_id, "/workspace")],
+ auto_delete: Some(0),
+ ..Default::default()
+ },
+ Some("after-timeout".to_string()),
+ );
+ let result = tokio::time::timeout(std::time::Duration::from_secs(5), create).await;
+ assert!(result.is_err(), "the registry lock must delay creation");
+ drop(create_runtime);
+ release_sender.send(()).unwrap();
+ lock_task.await.unwrap().unwrap();
+
+ let mut created = None;
+ for _ in 0..100 {
+ created = runtime.get("after-timeout").await.unwrap();
+ if created.is_some() {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ let created = created.expect("the committed box remains discoverable");
+ let (config, _) = runtime
+ .box_manager
+ .box_by_id(created.id())
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ config.options.volumes[0].managed_volume.as_deref(),
+ Some(volume.id.as_str())
+ );
+ assert!(
+ runtime
+ .list_info()
+ .await
+ .unwrap()
+ .iter()
+ .any(|info| info.id == *created.id())
+ );
+
+ drop(created);
+ drop(runtime);
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .expect("restart recovers the committed box");
+ let recovered = runtime
+ .get("after-timeout")
+ .await
+ .unwrap()
+ .expect("the committed box survives restart");
+ assert_eq!(
+ recovered.info().await.unwrap().status,
+ crate::BoxStatus::Configured
+ );
+ assert_eq!(runtime.lock_manager.allocated_count().unwrap(), 1);
+ assert_eq!(runtime.disk_lock_manager.allocated_count().unwrap(), 1);
+
+ runtime.remove("after-timeout", false).unwrap();
+ runtime
+ .local_volume_store
+ .remove(&volume.id, false)
+ .expect("removing the box releases its volume holder");
+ }
+
+ #[tokio::test]
+ async fn background_persistence_retains_the_runtime_home_lock() {
+ let home = tempfile::tempdir().unwrap();
+ let home_dir = home.path().to_path_buf();
+ let options = || BoxliteOptions {
+ home_dir: home_dir.clone(),
+ ..Default::default()
+ };
+ let runtime = RuntimeImpl::new_for_test(options()).unwrap();
+ let blocker =
+ rusqlite::Connection::open(runtime.layout.db_dir().join("boxlite.db")).unwrap();
+ blocker.execute_batch("BEGIN EXCLUSIVE").unwrap();
+ let create_runtime = Arc::clone(&runtime);
+ let mut create = Box::pin(create_runtime.create(
+ BoxOptions {
+ auto_delete: Some(0),
+ ..Default::default()
+ },
+ Some("home-lock".to_string()),
+ ));
+ assert!(futures::poll!(&mut create).is_pending());
+
+ drop(create);
+ drop(create_runtime);
+ drop(runtime);
+ let reopen_home = home_dir.clone();
+ let mut reopen_task = tokio::task::spawn_blocking(move || {
+ RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: reopen_home,
+ ..Default::default()
+ })
+ });
+ let result =
+ tokio::time::timeout(std::time::Duration::from_millis(500), &mut reopen_task).await;
+ drop(blocker);
+ let reopened = match result {
+ Ok(result) => result.unwrap(),
+ Err(_) => reopen_task.await.unwrap(),
+ };
+ let reopen_succeeded = reopened.is_ok();
+ drop(reopened);
+
+ assert!(
+ !reopen_succeeded,
+ "another runtime must not clear the old worker's lock allocations"
+ );
+
+ for _ in 0..100 {
+ if let Ok(runtime) = RuntimeImpl::new_for_test(options()) {
+ drop(runtime);
+ return;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ panic!("the home lock must be released after background persistence finishes");
+ }
+
+ #[tokio::test]
+ async fn create_returns_the_committed_box_when_a_lookup_caches_it_first() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ let store = runtime.local_volume_store.clone();
+ let (ready_sender, ready_receiver) = std::sync::mpsc::channel();
+ let (release_sender, release_receiver) = std::sync::mpsc::channel();
+ let lock_task = tokio::task::spawn_blocking(move || {
+ store.create_impl(Some("lock-holder"), move |_, _| {
+ ready_sender.send(()).unwrap();
+ release_receiver.recv().unwrap();
+ })
+ });
+ ready_receiver.recv().unwrap();
+
+ let create_runtime = Arc::clone(&runtime);
+ let mut create = Box::pin(create_runtime.create(
+ BoxOptions {
+ volumes: vec![VolumeSpec::managed_volume(&volume.id, "/workspace")],
+ auto_delete: Some(0),
+ ..Default::default()
+ },
+ Some("race".to_string()),
+ ));
+ assert!(futures::poll!(&mut create).is_pending());
+ release_sender.send(()).unwrap();
+ lock_task.await.unwrap().unwrap();
+
+ let cached = loop {
+ if runtime.box_manager.lookup_box("race").unwrap().is_some() {
+ break runtime
+ .get("race")
+ .await
+ .unwrap()
+ .expect("a concurrent lookup sees the committed box");
+ }
+ assert!(futures::poll!(&mut create).is_pending());
+ tokio::time::sleep(std::time::Duration::from_millis(1)).await;
+ };
+
+ let created = create
+ .await
+ .expect("a same-ID cache hit is still the successful create");
+ assert_eq!(created.id(), cached.id());
+ }
+
+ #[tokio::test]
+ async fn cancelled_clone_keeps_source_admission_and_persists_base_dependency() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ let source = runtime
+ .create(
+ BoxOptions {
+ volumes: vec![VolumeSpec::managed_volume(&volume.id, "/workspace")],
+ auto_delete: Some(0),
+ ..Default::default()
+ },
+ Some("source".to_string()),
+ )
+ .await
+ .unwrap();
+ let source_id = source.id().clone();
+ let (source_config, source_state) =
+ runtime.box_manager.box_by_id(&source_id).unwrap().unwrap();
+ let source_disk = source_config.box_home.join("disks").join("disk.qcow2");
+ crate::disk::Qcow2Helper::create_disk(&source_disk, true)
+ .unwrap()
+ .leak();
+ let source_lock_id = source_state.lock_id.unwrap();
+
+ let store = runtime.local_volume_store.clone();
+ let (ready_sender, ready_receiver) = std::sync::mpsc::channel();
+ let (release_sender, release_receiver) = std::sync::mpsc::channel();
+ let lock_task = tokio::task::spawn_blocking(move || {
+ store.create_impl(Some("lock-holder"), move |_, _| {
+ ready_sender.send(()).unwrap();
+ release_receiver.recv().unwrap();
+ })
+ });
+ ready_receiver.recv().unwrap();
+
+ let mut clone = Box::pin(source.clone_box(Default::default(), Some("clone".to_string())));
+ for _ in 0..100 {
+ assert!(futures::poll!(&mut clone).is_pending());
+ if std::fs::read_dir(runtime.layout.boxes_dir())
+ .unwrap()
+ .count()
+ == 2
+ {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ assert_eq!(
+ std::fs::read_dir(runtime.layout.boxes_dir())
+ .unwrap()
+ .count(),
+ 2,
+ "the clone must reach persistence while the registry lock is held"
+ );
+ drop(clone);
+
+ let source_locker = runtime.disk_lock_manager.retrieve(source_lock_id).unwrap();
+ let admission_released = crate::lock::LockGuard::try_new(source_locker.as_ref()).is_some();
+ release_sender.send(()).unwrap();
+ lock_task.await.unwrap().unwrap();
+
+ let mut created = None;
+ for _ in 0..100 {
+ created = runtime.get("clone").await.unwrap();
+ if created.is_some() {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ let created = created.expect("the cancelled clone eventually commits");
+ let clone_id = created.id().clone();
+ let backing = crate::disk::read_backing_file_path(&source_disk)
+ .unwrap()
+ .unwrap();
+ let base = runtime
+ .base_disk_mgr
+ .store()
+ .find_by_base_path(&backing)
+ .unwrap()
+ .unwrap();
+ let base_id = base.id().clone();
+ let base_path = base.disk_info().as_path().to_path_buf();
+ assert!(
+ runtime
+ .base_disk_mgr
+ .store()
+ .dependent_boxes(&base_id)
+ .unwrap()
+ .contains(&clone_id.to_string()),
+ "a visible clone must have its base dependency"
+ );
+ assert!(
+ !admission_released,
+ "source admission must remain owned by background persistence"
+ );
+
+ drop(created);
+ drop(source);
+ drop(runtime);
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ runtime
+ .get("clone")
+ .await
+ .unwrap()
+ .expect("the clone remains manageable after restart");
+ assert!(
+ runtime
+ .base_disk_mgr
+ .store()
+ .dependent_boxes(&base_id)
+ .unwrap()
+ .contains(&clone_id.to_string())
+ );
+ let error = runtime
+ .remove(source_id.as_str(), false)
+ .expect_err("the clone dependency must protect the source");
+ assert!(matches!(error, BoxliteError::InvalidState(_)));
+ assert!(base_path.exists());
+
+ runtime.remove(clone_id.as_ref(), false).unwrap();
+ runtime.remove(source_id.as_str(), false).unwrap();
+ }
+
+ #[tokio::test]
+ async fn user_supplied_uuid_volume_names_are_rejected() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let existing = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+
+ for name in [existing.id, Uuid::new_v4().to_string()] {
+ let error = runtime
+ .local_volume_store
+ .create(Some(&name))
+ .expect_err("a user-supplied UUID must not become a volume name");
+ assert!(
+ matches!(error, BoxliteError::InvalidArgument(_)),
+ "{error:?}"
+ );
+ }
+ assert_eq!(runtime.local_volume_store.list().unwrap().len(), 1);
+
+ let unnamed = runtime.local_volume_store.create(None).unwrap();
+ assert_eq!(unnamed.name, unnamed.id);
+ }
+
+ fn seed_raw_volume(root: &Path, id: &str, name: &str) {
+ let path = root.join(id);
+ std::fs::create_dir_all(path.join(PAYLOAD_DIR)).unwrap();
+ let metadata = VolumeMetadata {
+ version: 1,
+ id: id.to_owned(),
+ name: name.to_owned(),
+ created_at: Utc::now(),
+ };
+ std::fs::write(
+ path.join(METADATA_FILE),
+ serde_json::to_vec_pretty(&metadata).unwrap(),
+ )
+ .unwrap();
+ }
+
+ #[tokio::test]
+ async fn duplicate_metadata_names_fail_closed() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let root = runtime.layout.volumes_dir();
+ for id in [Uuid::new_v4().to_string(), Uuid::new_v4().to_string()] {
+ seed_raw_volume(&root, &id, "duplicate");
+ }
+
+ let error = runtime
+ .local_volume_store
+ .create(Some("another"))
+ .expect_err("duplicate metadata names must fail creation");
+ assert!(matches!(error, BoxliteError::MetadataError(_)), "{error:?}");
+ let options = BoxOptions {
+ volumes: vec![VolumeSpec::managed_volume("duplicate", "/workspace")],
+ ..Default::default()
+ };
+ let local = crate::runtime::rt_impl::LocalRuntime(Arc::clone(&runtime));
+ let error = crate::runtime::backend::RuntimeBackend::create(&local, options, None)
+ .await
+ .err()
+ .expect("a duplicate name must not select an arbitrary volume");
+ assert!(matches!(error, BoxliteError::MetadataError(_)), "{error:?}");
+ }
+
+ #[tokio::test]
+ async fn name_audit_ignores_unrelated_payload_corruption() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let good = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ let root = runtime.layout.volumes_dir();
+ let bad_id = Uuid::new_v4().to_string();
+ seed_raw_volume(&root, &bad_id, "unrelated");
+ std::fs::remove_dir(root.join(&bad_id).join(PAYLOAD_DIR)).unwrap();
+
+ runtime
+ .local_volume_store
+ .create(Some("another"))
+ .expect("name audit should not require unrelated payload health");
+ let options = BoxOptions {
+ volumes: vec![VolumeSpec::managed_volume("workspace", "/workspace")],
+ ..Default::default()
+ };
+ let local = crate::runtime::rt_impl::LocalRuntime(Arc::clone(&runtime));
+ let box_handle = crate::runtime::backend::RuntimeBackend::create(&local, options, None)
+ .await
+ .expect("resolve a healthy volume by name");
+ let (config, _) = runtime
+ .box_manager
+ .box_by_id(box_handle.id())
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ config.options.volumes[0].managed_volume.as_deref(),
+ Some(good.id.as_str())
+ );
+ let error = runtime
+ .local_volume_store
+ .get(&bad_id)
+ .expect_err("the selected corrupt payload must still fail");
+ assert!(matches!(error, BoxliteError::MetadataError(_)), "{error:?}");
+ }
+
+ #[tokio::test]
+ async fn holder_registration_and_remove_share_one_linearization() {
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().to_path_buf(),
+ ..Default::default()
+ })
+ .unwrap();
+ let volume = runtime
+ .local_volume_store
+ .create(Some("workspace"))
+ .unwrap();
+ let box_id = crate::runtime::id::BoxIDMint::mint();
+ let mut config = BoxConfig {
+ id: box_id.clone(),
+ name: None,
+ created_at: Utc::now(),
+ container: crate::litebox::config::ContainerRuntimeConfig {
+ id: crate::runtime::types::ContainerID::new(),
+ },
+ options: BoxOptions {
+ volumes: vec![VolumeSpec::managed_volume("workspace", "/workspace")],
+ auto_delete: Some(0),
+ ..Default::default()
+ },
+ engine_kind: crate::vmm::VmmKind::Libkrun,
+ box_home: home.path().join("boxes").join(box_id.as_str()),
+ };
+ let state = BoxState::new();
+ let mut removed_config = config.clone();
+ let store = runtime.local_volume_store.clone();
+ let (ready_sender, ready_receiver) = std::sync::mpsc::channel();
+ let (release_sender, release_receiver) = std::sync::mpsc::channel();
+ let add_task = tokio::task::spawn_blocking(move || {
+ store.add_box_impl(
+ &mut config,
+ &state,
+ VolumeReferenceMode::Selector,
+ None,
+ || {
+ ready_sender.send(()).unwrap();
+ release_receiver.recv().unwrap();
+ },
+ )
+ });
+ ready_receiver.recv().unwrap();
+ let remove_task = tokio::task::spawn_blocking({
+ let store = runtime.local_volume_store.clone();
+ let id = volume.id.clone();
+ move || store.remove(&id, false)
+ });
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ assert!(
+ !remove_task.is_finished(),
+ "remove must wait for holder registration"
+ );
+ release_sender.send(()).unwrap();
+ add_task.await.unwrap().unwrap();
+ let error = remove_task
+ .await
+ .unwrap()
+ .expect_err("the committed holder must block removal");
+ assert!(matches!(error, BoxliteError::InvalidState(_)), "{error:?}");
+
+ runtime.box_manager.remove_box(&box_id).unwrap();
+ runtime
+ .local_volume_store
+ .remove(&volume.id, false)
+ .unwrap();
+ let error = runtime
+ .local_volume_store
+ .add_box_with_resolved_volumes(
+ &mut removed_config,
+ &BoxState::new(),
+ VolumeReferenceMode::Selector,
+ )
+ .expect_err("a removed volume cannot acquire a new holder");
+ assert!(matches!(error, BoxliteError::NotFound(_)), "{error:?}");
+ }
+
+ const CHILD_MODE: &str = "BOXLITE_VOLUME_TEST_CHILD";
+ const CHILD_HOME: &str = "BOXLITE_VOLUME_TEST_HOME";
+
+ #[test]
+ fn concurrent_create_same_name_across_processes() {
+ if std::env::var_os(CHILD_MODE).is_some() {
+ let home = std::env::var_os(CHILD_HOME).unwrap();
+ let database =
+ crate::db::Database::open(Path::new(&home).join("db").join("boxlite.db").as_path())
+ .unwrap();
+ let store = LocalVolumeStore::new(
+ Path::new(&home).join("volumes"),
+ BoxManager::new(crate::db::BoxStore::new(database)),
+ )
+ .unwrap();
+ match store.create(Some("workspace")) {
+ Ok(_) => std::process::exit(0),
+ Err(BoxliteError::AlreadyExists(_)) => std::process::exit(2),
+ Err(error) => {
+ eprintln!("unexpected create error: {error}");
+ std::process::exit(1);
+ }
+ }
+ }
+
+ let home = tempfile::tempdir().unwrap();
+ let _database = crate::db::Database::open(&home.path().join("db").join("boxlite.db"))
+ .expect("initialize the shared test database before spawning children");
+ let mut children = Vec::new();
+ for _ in 0..2 {
+ children.push(
+ std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "volumes::local_store::tests::concurrent_create_same_name_across_processes",
+ "--nocapture",
+ ])
+ .env(CHILD_MODE, "1")
+ .env(CHILD_HOME, home.path())
+ .spawn()
+ .unwrap(),
+ );
+ }
+ let mut successes = 0;
+ let mut conflicts = 0;
+ for child in &mut children {
+ let status = child.wait().unwrap();
+ match status.code() {
+ Some(0) => successes += 1,
+ Some(2) => conflicts += 1,
+ other => panic!("child failed: {other:?}"),
+ }
+ }
+ assert_eq!(successes, 1);
+ assert_eq!(conflicts, 1);
+ let database =
+ crate::db::Database::open(&home.path().join("db").join("boxlite.db")).unwrap();
+ let store = LocalVolumeStore::new(
+ home.path().join("volumes"),
+ BoxManager::new(crate::db::BoxStore::new(database)),
+ )
+ .unwrap();
+ assert_eq!(store.list().unwrap().len(), 1);
+ }
+}
diff --git a/src/boxlite/src/volumes/mod.rs b/src/boxlite/src/volumes/mod.rs
index 9c4f5f771..bb4dc1ea6 100644
--- a/src/boxlite/src/volumes/mod.rs
+++ b/src/boxlite/src/volumes/mod.rs
@@ -3,16 +3,21 @@
//! Provides:
//! - `GuestVolumeManager` for virtiofs shares and block devices
//! - `ContainerVolumeManager` for container bind mounts
-//! - `VolumeInfo` metadata for named volumes (backend not yet implemented)
+//! - `VolumeInfo` metadata for named volumes and the local filesystem backend
mod container_volume;
mod guest_volume;
+mod local_store;
mod share;
mod staging;
mod store;
+pub(crate) use container_volume::ContainerMountPayload;
pub use container_volume::{ContainerMount, ContainerVolumeManager};
pub use guest_volume::GuestVolumeManager;
+pub(crate) use local_store::{
+ LocalVolumeStore, ResolvedLocalMount, ResolvedLocalMountPayload, VolumeReferenceMode,
+};
pub use share::{VolumeShare, classify_volume_share};
pub use staging::stage_single_file;
pub use store::VolumeInfo;
diff --git a/src/boxlite/src/volumes/store.rs b/src/boxlite/src/volumes/store.rs
index a8c06df0c..66de79116 100644
--- a/src/boxlite/src/volumes/store.rs
+++ b/src/boxlite/src/volumes/store.rs
@@ -2,10 +2,8 @@
//!
//! [`VolumeInfo`] is the storage-agnostic view of a volume returned by the
//! [`VolumeBackend`](crate::runtime::volumes::VolumeBackend) trait and rendered
-//! by the CLI. Volumes are addressed by a server-assigned id (like boxes). The
-//! concrete backend that would populate it is not yet implemented — see
-//! `impl VolumeBackend for LocalRuntime`, which currently returns `Unsupported`
-//! until a managed volume backend is wired up.
+//! by the CLI. Volumes are addressed by a runtime-assigned id (like boxes).
+//! `LocalVolumeStore` persists this metadata beside each volume's payload.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
diff --git a/src/cli/README.md b/src/cli/README.md
index f92625c15..60bee42c9 100644
--- a/src/cli/README.md
+++ b/src/cli/README.md
@@ -530,6 +530,7 @@ as completed executions with status `126` or `127`.
| `--entrypoint EXEC` | | Override the image entrypoint |
| `--publish PORT` | `-p` | Publish a TCP box port locally (`80` = automatic host port, `8080:80` = fixed) |
| `--volume VOLUME` | `-v` | Mount a volume: `name:/box` for a managed volume, `./path:/box` for a host bind, `/box` for anonymous |
+| `--mount type=volume,source=NAME,target=PATH[,readonly][,sub_path=DIR]` | | Typed managed-volume mount; mutually exclusive with `-v` |
| `--cpus N` | | CPU allocation, e.g. `2` or `0.5`; fractional values require a Linux execution host |
| `--memory MiB` | | Memory limit (MiB) |
| `--disk-size GB` | | Sparse rootfs disk size; smaller values than the base image are ignored |
@@ -592,6 +593,7 @@ default, and `exec` still starts it on demand.
| `--entrypoint EXEC` | | Override the image entrypoint |
| `--publish PORT` | `-p` | Publish a TCP box port locally (`80` = automatic host port, `8080:80` = fixed) |
| `--volume VOLUME` | `-v` | Mount a volume: `name:/box` for a managed volume, `./path:/box` for a host bind, `/box` for anonymous |
+| `--mount type=volume,source=NAME,target=PATH[,readonly][,sub_path=DIR]` | | Typed managed-volume mount; mutually exclusive with `-v` |
| `--cpus N` | | CPU allocation, e.g. `2` or `0.5`; fractional values require a Linux execution host |
| `--memory MiB` | | Memory limit (MiB) |
| `--disk-size GB` | | Sparse rootfs disk size; smaller values than the base image are ignored |
diff --git a/src/cli/src/cli.rs b/src/cli/src/cli.rs
index e749e9804..e5b10b663 100644
--- a/src/cli/src/cli.rs
+++ b/src/cli/src/cli.rs
@@ -1615,6 +1615,10 @@ pub struct VolumeFlags {
/// BOX_PATH[:options] for an anonymous volume
#[arg(short = 'v', long = "volume", value_name = "VOLUME")]
pub volume: Vec<String>,
+
+ /// Mount a managed volume by explicit type, optionally read-only or below a sub_path
+ #[arg(long = "mount", value_name = "MOUNT", conflicts_with = "volume")]
+ pub mount: Vec<String>,
}
/// Resolve base directory for anonymous volumes: explicit home, or BOXLITE_HOME, or ~/.boxlite, or temp dir.
@@ -1668,14 +1672,6 @@ impl VolumeFlags {
let spec = match mount.origin {
// Held as written; the server resolves an id or a name.
crate::volumespec::MountOrigin::ManagedVolume(volume) => {
- // Neither the server nor the REST client accepts one yet;
- // saying so here beats a downgrade the caller never sees.
- if mount.read_only {
- anyhow::bail!(
- "read-only managed volumes are not supported yet; \
- mount {volume:?} read-write"
- );
- }
VolumeSpec::managed_volume(volume, mount.guest_path)
}
@@ -1700,6 +1696,9 @@ impl VolumeFlags {
..spec
});
}
+ for value in &self.mount {
+ opts.mounts.push(crate::mountspec::parse(value)?);
+ }
Ok(())
}
}
@@ -2824,6 +2823,7 @@ mod tests {
"/host/data:/guest/data".to_string(),
"/readonly:/ro:ro".to_string(),
],
+ mount: Vec::new(),
};
let mut opts = BoxOptions::default();
flags.apply_to(&mut opts, None).unwrap();
@@ -2843,6 +2843,7 @@ mod tests {
r"C:\host\data:/guest/data".to_string(),
r"D:\readonly:/ro:ro".to_string(),
],
+ mount: Vec::new(),
};
let mut opts = BoxOptions::default();
flags.apply_to(&mut opts, None).unwrap();
@@ -2865,6 +2866,7 @@ mod tests {
"my-data:/data".to_string(),
"vol_01K2EXAMPLE:/cache".to_string(),
],
+ mount: Vec::new(),
};
let mut opts = BoxOptions::default();
flags.apply_to(&mut opts, None).unwrap();
@@ -2881,24 +2883,37 @@ mod tests {
assert_eq!(opts.volumes[1].guest_path, "/cache");
}
- /// `:ro` on a managed volume is refused, not quietly downgraded. Neither
- /// the server nor the REST client accepts one, and a caller who believes a
- /// mount is protected when it is writable is the failure worth preventing.
#[test]
- fn test_volume_flags_reject_read_only_managed_volume() {
+ fn test_typed_mount_flags_apply_to() {
let flags = VolumeFlags {
- volume: vec!["my-data:/data:ro".to_string()],
+ volume: Vec::new(),
+ mount: vec![
+ "type=volume,source=workspace,target=/workspace,readonly,sub_path=team/backend"
+ .to_string(),
+ ],
};
let mut opts = BoxOptions::default();
+ flags.apply_to(&mut opts, None).unwrap();
- let error = flags
- .apply_to(&mut opts, None)
- .expect_err("read-only managed volumes must be refused")
- .to_string();
-
- assert!(error.contains("read-only"), "{error}");
- assert!(error.contains("my-data"), "{error}");
assert!(opts.volumes.is_empty());
+ assert_eq!(opts.mounts.len(), 1);
+ assert_eq!(opts.mounts[0].source.as_deref(), Some("workspace"));
+ assert!(opts.mounts[0].read_only);
+ assert_eq!(opts.mounts[0].sub_path.as_deref(), Some("team/backend"));
+ }
+
+ #[test]
+ fn test_volume_flags_allow_read_only_managed_volume() {
+ let flags = VolumeFlags {
+ volume: vec!["my-data:/data:ro".to_string()],
+ mount: Vec::new(),
+ };
+ let mut opts = BoxOptions::default();
+ flags.apply_to(&mut opts, None).unwrap();
+
+ assert_eq!(opts.volumes.len(), 1);
+ assert_eq!(opts.volumes[0].managed_volume.as_deref(), Some("my-data"));
+ assert!(opts.volumes[0].read_only);
}
/// A host bind may still be read-only — the restriction is specific to
@@ -2907,6 +2922,7 @@ mod tests {
fn test_volume_flags_still_allow_read_only_host_binds() {
let flags = VolumeFlags {
volume: vec!["/host/data:/data:ro".to_string()],
+ mount: Vec::new(),
};
let mut opts = BoxOptions::default();
flags.apply_to(&mut opts, None).unwrap();
@@ -2921,6 +2937,7 @@ mod tests {
fn test_volume_flags_apply_to_leaves_host_binds_unmanaged() {
let flags = VolumeFlags {
volume: vec!["/host/data:/guest/data".to_string()],
+ mount: Vec::new(),
};
let mut opts = BoxOptions::default();
flags.apply_to(&mut opts, None).unwrap();
@@ -2934,6 +2951,7 @@ mod tests {
let base = std::env::temp_dir();
let flags = VolumeFlags {
volume: vec!["/data".to_string(), "/cache:ro".to_string()],
+ mount: Vec::new(),
};
let mut opts = BoxOptions::default();
flags.apply_to(&mut opts, Some(&base)).unwrap();
diff --git a/src/cli/src/commands/volume/mod.rs b/src/cli/src/commands/volume/mod.rs
index 15bdaf85b..7d9efb53a 100644
--- a/src/cli/src/commands/volume/mod.rs
+++ b/src/cli/src/commands/volume/mod.rs
@@ -5,9 +5,8 @@
//! mountable in place of the id (`-v my-data:/data`).
//!
//! Each leaf module owns its own `Args` struct and `run()`; this module holds
-//! the subcommand enum and dispatches. Volumes are a REST-runtime capability:
-//! the local runtime has no volume backend and every command returns
-//! "not supported" against it.
+//! the subcommand enum and dispatches. LocalRuntime uses `LocalVolumeStore`;
+//! REST runtimes use the selected server's volume API.
use clap::{Args, Subcommand};
diff --git a/src/cli/src/main.rs b/src/cli/src/main.rs
index 0d2b7c896..7b084c9e1 100644
--- a/src/cli/src/main.rs
+++ b/src/cli/src/main.rs
@@ -5,6 +5,7 @@ mod contexts;
mod credentials;
mod defaults;
mod formatter;
+mod mountspec;
pub mod terminal;
pub mod util;
mod volumespec;
diff --git a/src/cli/src/mountspec.rs b/src/cli/src/mountspec.rs
new file mode 100644
index 000000000..90fe43075
--- /dev/null
+++ b/src/cli/src/mountspec.rs
@@ -0,0 +1,96 @@
+use boxlite::runtime::options::MountSpec;
+
+pub fn parse(spec: &str) -> anyhow::Result<MountSpec> {
+ let mut mount_type = None;
+ let mut source = None;
+ let mut target = None;
+ let mut sub_path = None;
+ let mut read_only = false;
+
+ for field in spec.split(',') {
+ if field.is_empty() {
+ anyhow::bail!("empty mount field in {spec:?}");
+ }
+ if field == "readonly" {
+ if read_only {
+ anyhow::bail!("duplicate readonly flag in {spec:?}");
+ }
+ read_only = true;
+ continue;
+ }
+ let (key, value) = field
+ .split_once('=')
+ .ok_or_else(|| anyhow::anyhow!("invalid mount field {field:?}"))?;
+ if value.is_empty() {
+ anyhow::bail!("mount field {key:?} cannot be empty");
+ }
+ match key {
+ "type" => {
+ if mount_type.replace(value.to_owned()).is_some() {
+ anyhow::bail!("duplicate mount type in {spec:?}");
+ }
+ }
+ "source" => {
+ if source.replace(value.to_owned()).is_some() {
+ anyhow::bail!("duplicate mount source in {spec:?}");
+ }
+ }
+ "target" => {
+ if target.replace(value.to_owned()).is_some() {
+ anyhow::bail!("duplicate mount target in {spec:?}");
+ }
+ }
+ "sub_path" => {
+ if sub_path.replace(value.to_owned()).is_some() {
+ anyhow::bail!("duplicate mount sub_path in {spec:?}");
+ }
+ }
+ _ => anyhow::bail!("unknown mount field {key:?}"),
+ }
+ }
+
+ if mount_type.as_deref() != Some("volume") {
+ anyhow::bail!("--mount currently requires type=volume");
+ }
+ let source = source.ok_or_else(|| anyhow::anyhow!("mount source is required"))?;
+ let target = target.ok_or_else(|| anyhow::anyhow!("mount target is required"))?;
+ let mut mount = MountSpec::volume_mount(source, target);
+ mount.read_only = read_only;
+ mount.sub_path = sub_path;
+ mount.validate()?;
+ Ok(mount)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use boxlite::runtime::options::MountType;
+
+ #[test]
+ fn parses_a_typed_volume_mount() {
+ let mount =
+ parse("type=volume,source=workspace,target=/workspace,readonly,sub_path=team/backend")
+ .expect("parse a read-only volume subdirectory");
+ assert_eq!(mount.mount_type, MountType::Volume);
+ assert_eq!(mount.source.as_deref(), Some("workspace"));
+ assert_eq!(mount.target, "/workspace");
+ assert!(mount.read_only);
+ assert_eq!(mount.sub_path.as_deref(), Some("team/backend"));
+ }
+
+ #[test]
+ fn rejects_invalid_or_unsupported_mounts() {
+ for invalid in [
+ "type=bind,source=/tmp,target=/data",
+ "type=volume,source=workspace",
+ "source=workspace,target=/workspace",
+ "type=volume,source=,target=/workspace",
+ "type=volume,source=workspace,target=/workspace,readonly=true",
+ "type=volume,source=workspace,target=/workspace,unknown=value",
+ "type=volume,source=workspace,target=/workspace,readonly,readonly",
+ "type=volume,source=workspace,target=/workspace,sub_path=a,b",
+ ] {
+ assert!(parse(invalid).is_err(), "{invalid} must be rejected");
+ }
+ }
+}
diff --git a/src/cli/tests/local_volume.rs b/src/cli/tests/local_volume.rs
new file mode 100644
index 000000000..ed84d35d2
--- /dev/null
+++ b/src/cli/tests/local_volume.rs
@@ -0,0 +1,109 @@
+use predicates::prelude::*;
+
+mod common;
+
+fn create_volume(ctx: &common::TestContext, name: &str) -> String {
+ let output = ctx
+ .new_cmd()
+ .args(["volume", "create", "--name", name])
+ .output()
+ .expect("run volume create");
+ assert!(output.status.success(), "volume create failed: {output:?}");
+ String::from_utf8(output.stdout)
+ .expect("volume id is UTF-8")
+ .trim()
+ .to_owned()
+}
+
+#[test]
+fn local_volume_complete_lifecycle() {
+ let ctx = common::boxlite_bare();
+ let id = create_volume(&ctx, "workspace");
+
+ ctx.new_cmd()
+ .args([
+ "run",
+ "--rm",
+ "-v",
+ "workspace:/workspace",
+ "alpine:latest",
+ "sh",
+ "-c",
+ "mkdir -p /workspace/team/backend /workspace/sibling; echo subdata > /workspace/team/backend/result.txt; echo secret > /workspace/sibling/secret.txt",
+ ])
+ .assert()
+ .success();
+
+ ctx.new_cmd()
+ .args([
+ "run",
+ "--rm",
+ "--mount",
+ "type=volume,source=workspace,target=/workspace,readonly,sub_path=team/backend",
+ "alpine:latest",
+ "sh",
+ "-c",
+ "cat /workspace/result.txt && test ! -e /workspace/sibling && test ! -e /workspace/team && ! echo change > /workspace/result.txt",
+ ])
+ .assert()
+ .success()
+ .stdout(predicate::str::contains("subdata"));
+
+ ctx.new_cmd()
+ .args(["list", "--quiet"])
+ .assert()
+ .success()
+ .stdout(predicate::str::is_empty());
+ ctx.new_cmd().args(["volume", "rm", &id]).assert().success();
+ ctx.new_cmd()
+ .args(["volume", "get", &id])
+ .assert()
+ .failure();
+}
+
+#[test]
+fn local_volume_rejects_duplicate_mounts() {
+ let ctx = common::boxlite_bare();
+ create_volume(&ctx, "workspace");
+
+ ctx.new_cmd()
+ .args([
+ "run",
+ "--rm",
+ "-v",
+ "workspace:/one",
+ "-v",
+ "workspace:/two",
+ "alpine:latest",
+ "true",
+ ])
+ .assert()
+ .failure()
+ .stderr(predicate::str::contains("mounted more than once"));
+}
+
+#[test]
+fn local_volume_remove_waits_for_last_holder() {
+ let ctx = common::boxlite_bare();
+ let id = create_volume(&ctx, "workspace");
+ ctx.new_cmd()
+ .args([
+ "create",
+ "--name",
+ "volume-holder",
+ "-v",
+ "workspace:/workspace",
+ "alpine:latest",
+ ])
+ .assert()
+ .success();
+
+ ctx.new_cmd()
+ .args(["volume", "rm", &id])
+ .assert()
+ .failure()
+ .stderr(predicate::str::contains("still referenced"));
+
+ ctx.cleanup_box("volume-holder");
+ ctx.new_cmd().args(["volume", "rm", &id]).assert().success();
+}
diff --git a/src/cli/tests/run.rs b/src/cli/tests/run.rs
index 787925216..28ab916db 100644
--- a/src/cli/tests/run.rs
+++ b/src/cli/tests/run.rs
@@ -559,6 +559,25 @@ fn test_run_with_volume_success() {
ctx.cmd.assert().success().stdout("hello-boxlite\n");
}
+#[test]
+fn test_run_with_single_file_volume() {
+ let dir = tempfile::tempdir().unwrap();
+ let file = dir.path().join("app.conf");
+ std::fs::write(&file, "single-file\n").unwrap();
+
+ let mut ctx = common::boxlite();
+ ctx.cmd.args([
+ "run",
+ "--rm",
+ "-v",
+ &format!("{}:/etc/app.conf", file.to_str().unwrap()),
+ "alpine:latest",
+ "cat",
+ "/etc/app.conf",
+ ]);
+ ctx.cmd.assert().success().stdout("single-file\n");
+}
+
#[test]
fn test_run_with_volume_short_flag() {
let dir = tempfile::tempdir().unwrap();
diff --git a/src/guest/src/service/container.rs b/src/guest/src/service/container.rs
index 150eac2e8..74472d603 100644
--- a/src/guest/src/service/container.rs
+++ b/src/guest/src/service/container.rs
@@ -7,12 +7,13 @@ use std::path::{Component, Path, PathBuf};
use crate::service::server::GuestServer;
use crate::storage::attach::{validate_destination, Target};
-use boxlite_shared::errors::BoxliteError;
+use boxlite_shared::errors::{BoxliteError, BoxliteResult};
use boxlite_shared::{
- container_init_response, container_start_response, rootfs_init, Container as ContainerService,
- ContainerInitError, ContainerInitErrorKind, ContainerInitRequest, ContainerInitResponse,
- ContainerInitSuccess, ContainerMountRequest, ContainerMountResponse, ContainerStartRequest,
- ContainerStartResponse, ContainerStartSuccess, Filesystem, RootfsInit,
+ container_init_response, container_start_response, rootfs_init, BindMount, BindMountKind,
+ Container as ContainerService, ContainerInitError, ContainerInitErrorKind,
+ ContainerInitRequest, ContainerInitResponse, ContainerInitSuccess, ContainerMountRequest,
+ ContainerMountResponse, ContainerStartRequest, ContainerStartResponse, ContainerStartSuccess,
+ Filesystem, RootfsInit,
};
use nix::mount::{mount, MsFlags};
use tonic::{Request, Response, Status};
@@ -37,6 +38,8 @@ fn internal_init_error(reason: impl Into<String>) -> ContainerInitError {
fn init_error(context: &str, error: &BoxliteError) -> ContainerInitError {
let kind = match error {
BoxliteError::Unsupported(_) => ContainerInitErrorKind::Unsupported,
+ BoxliteError::InvalidArgument(_) => ContainerInitErrorKind::InvalidArgument,
+ BoxliteError::NotFound(_) => ContainerInitErrorKind::NotFound,
_ => ContainerInitErrorKind::Internal,
};
ContainerInitError {
@@ -45,6 +48,42 @@ fn init_error(context: &str, error: &BoxliteError) -> ContainerInitError {
}
}
+#[derive(Debug, PartialEq)]
+enum BindMountSource<'a> {
+ WholeDirectory,
+ SingleFile { file_name: &'a str },
+ ManagedSubDirectory { sub_path: &'a str },
+}
+
+fn bind_mount_source(mount: &BindMount) -> BoxliteResult<BindMountSource<'_>> {
+ let kind = BindMountKind::try_from(mount.kind).map_err(|_| {
+ BoxliteError::Unsupported(format!("unknown bind mount kind {}", mount.kind))
+ })?;
+ match kind {
+ BindMountKind::Unspecified if mount.subpath.is_empty() => {
+ Ok(BindMountSource::WholeDirectory)
+ }
+ BindMountKind::Unspecified => Ok(BindMountSource::SingleFile {
+ file_name: &mount.subpath,
+ }),
+ BindMountKind::WholeDirectory if mount.subpath.is_empty() => {
+ Ok(BindMountSource::WholeDirectory)
+ }
+ BindMountKind::SingleFile if !mount.subpath.is_empty() => Ok(BindMountSource::SingleFile {
+ file_name: &mount.subpath,
+ }),
+ BindMountKind::ManagedSubDirectory if !mount.subpath.is_empty() => {
+ Ok(BindMountSource::ManagedSubDirectory {
+ sub_path: &mount.subpath,
+ })
+ }
+ _ => Err(BoxliteError::InvalidArgument(format!(
+ "subpath {:?} is invalid for {kind:?}",
+ mount.subpath
+ ))),
+ }
+}
+
/// Check a `Container.Mount` request: read-only, a source that is one share
/// folder name so it stays inside `containers/<id>/volumes/`, and a valid
/// container path. Returns the destination.
@@ -328,26 +367,57 @@ impl ContainerService for GuestServer {
// container's volume folder in the share: <shared>/containers/{id}/volumes/{name}
let container_layout = self.layout.shared().container(&container_id);
- let user_mounts: Vec<UserMount> = init_req
- .mounts
- .iter()
- .map(|m| {
- let volume_dir = container_layout.volume_dir(&m.volume_name);
- // Single-file mount: bind just the one file within the shared dir.
- let source = if m.subpath.is_empty() {
- volume_dir
- } else {
- volume_dir.join(&m.subpath)
- };
- UserMount {
- source: source.to_string_lossy().to_string(),
- destination: m.destination.clone(),
- read_only: m.read_only,
- owner_uid: m.owner_uid,
- owner_gid: m.owner_gid,
+ // Keep every resolved volume subpath mount alive until startup is done.
+ let mut resolved_mounts = Vec::new();
+ let mut user_mounts = Vec::with_capacity(init_req.mounts.len());
+ for m in &init_req.mounts {
+ let volume_dir = container_layout.volume_dir(&m.volume_name);
+ let selected = match bind_mount_source(m) {
+ Ok(selected) => selected,
+ Err(error) => {
+ return Ok(Response::new(ContainerInitResponse {
+ result: Some(container_init_response::Result::Error(init_error(
+ "resolve bind mount",
+ &error,
+ ))),
+ }));
}
- })
- .collect();
+ };
+ let source = match selected {
+ BindMountSource::WholeDirectory => volume_dir,
+ BindMountSource::SingleFile { file_name } => volume_dir.join(file_name),
+ BindMountSource::ManagedSubDirectory { sub_path } => {
+ // Pin the selected directory at its own mountpoint. A failed
+ // pin fails container init instead of exposing the whole volume.
+ match crate::storage::resolved_mount::ResolvedMount::pin(
+ &volume_dir,
+ sub_path,
+ m.read_only,
+ ) {
+ Ok(mount) => {
+ let path = mount.path().to_path_buf();
+ resolved_mounts.push(mount);
+ path
+ }
+ Err(error) => {
+ return Ok(Response::new(ContainerInitResponse {
+ result: Some(container_init_response::Result::Error(init_error(
+ "resolve managed volume sub_path",
+ &error,
+ ))),
+ }));
+ }
+ }
+ }
+ };
+ user_mounts.push(UserMount {
+ source: source.to_string_lossy().to_string(),
+ destination: m.destination.clone(),
+ read_only: m.read_only,
+ owner_uid: m.owner_uid,
+ owner_gid: m.owner_gid,
+ });
+ }
debug!(
entrypoint = ?config.entrypoint,
@@ -393,7 +463,7 @@ impl ContainerService for GuestServer {
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
- match Container::start(
+ let container_result = Container::start(
&container_id,
&bundle_rootfs,
config.entrypoint,
@@ -407,7 +477,12 @@ impl ContainerService for GuestServer {
mount_override,
devices,
cgroup,
- ) {
+ );
+ // Dropping now unmounts only the temporary host-side mountpoints;
+ // they must outlive container creation so the guest cannot unmount
+ // them while startup is still configuring mounts.
+ drop(resolved_mounts);
+ match container_result {
Ok(mut container) => {
// Init is created, not yet running — Init never runs it; the
// host calls Container.Start for that. That its pid and stdio
@@ -818,6 +893,88 @@ mod tests {
}
}
+ #[test]
+ fn legacy_bind_mounts_keep_their_original_subpath_semantics() {
+ let legacy_whole = BindMount::default();
+ let whole = bind_mount_source(&legacy_whole)
+ .expect("an old host's empty subpath selects the whole directory");
+ assert_eq!(whole, BindMountSource::WholeDirectory);
+
+ let file = BindMount {
+ subpath: "app.conf".to_string(),
+ ..Default::default()
+ };
+ let selected = bind_mount_source(&file)
+ .expect("an old host's non-empty subpath selects a single file");
+ assert_eq!(
+ selected,
+ BindMountSource::SingleFile {
+ file_name: "app.conf"
+ }
+ );
+ }
+
+ #[test]
+ fn explicit_bind_mount_kinds_select_the_requested_payload() {
+ let cases = [
+ (
+ BindMountKind::WholeDirectory,
+ "",
+ BindMountSource::WholeDirectory,
+ ),
+ (
+ BindMountKind::SingleFile,
+ "app.conf",
+ BindMountSource::SingleFile {
+ file_name: "app.conf",
+ },
+ ),
+ (
+ BindMountKind::ManagedSubDirectory,
+ "team/backend",
+ BindMountSource::ManagedSubDirectory {
+ sub_path: "team/backend",
+ },
+ ),
+ ];
+ for (kind, subpath, expected) in cases {
+ let mount = BindMount {
+ kind: kind as i32,
+ subpath: subpath.to_string(),
+ ..Default::default()
+ };
+ assert_eq!(bind_mount_source(&mount).unwrap(), expected);
+ }
+ }
+
+ #[test]
+ fn bind_mount_rejects_unknown_kinds_and_invalid_subpaths() {
+ let unknown = BindMount {
+ kind: 99,
+ ..Default::default()
+ };
+ assert!(matches!(
+ bind_mount_source(&unknown),
+ Err(BoxliteError::Unsupported(_))
+ ));
+
+ for (kind, subpath) in [
+ (BindMountKind::WholeDirectory, "unexpected"),
+ (BindMountKind::SingleFile, ""),
+ (BindMountKind::ManagedSubDirectory, ""),
+ ] {
+ let mount = BindMount {
+ kind: kind as i32,
+ subpath: subpath.to_string(),
+ ..Default::default()
+ };
+ assert!(matches!(
+ bind_mount_source(&mount),
+ Err(BoxliteError::InvalidArgument(_))
+ ));
+ }
+ }
+
#[test]
fn attach_failures_keep_their_grpc_codes() {
let cases = [
diff --git a/src/guest/src/service/guest.rs b/src/guest/src/service/guest.rs
index f8107b75a..afe290d1b 100644
--- a/src/guest/src/service/guest.rs
+++ b/src/guest/src/service/guest.rs
@@ -87,6 +87,7 @@ impl GuestService for GuestServer {
debug!("Received ping request");
Ok(Response::new(PingResponse {
version: env!("CARGO_PKG_VERSION").to_string(),
+ safe_managed_volume_sub_path: true,
}))
}
diff --git a/src/guest/src/storage/mod.rs b/src/guest/src/storage/mod.rs
index f609b7c22..a5b9a463a 100644
--- a/src/guest/src/storage/mod.rs
+++ b/src/guest/src/storage/mod.rs
@@ -11,6 +11,7 @@ pub mod block_device;
mod copy;
pub mod fsfreeze;
pub mod idmap;
+pub(crate) mod resolved_mount;
mod virtiofs;
mod volume;
diff --git a/src/guest/src/storage/resolved_mount.rs b/src/guest/src/storage/resolved_mount.rs
new file mode 100644
index 000000000..219d02b30
--- /dev/null
+++ b/src/guest/src/storage/resolved_mount.rs
@@ -0,0 +1,353 @@
+use std::ffi::CString;
+use std::path::{Path, PathBuf};
+
+use boxlite_shared::errors::{BoxliteError, BoxliteResult};
+use nix::fcntl::{open, openat2, OFlag, OpenHow, ResolveFlag};
+use nix::mount::{mount, umount, MsFlags};
+use nix::sys::stat::Mode;
+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
+use std::os::unix::ffi::OsStrExt;
+
+use super::idmap::sys;
+
+pub(crate) struct ResolvedMount {
+ path: PathBuf,
+}
+
+/// Owns a temporary mountpoint until the resolved mount is fully armed.
+struct MountpointGuard {
+ path: PathBuf,
+ mounted: bool,
+ armed: bool,
+}
+
+impl MountpointGuard {
+ fn new(path: PathBuf) -> Self {
+ Self {
+ path,
+ mounted: false,
+ armed: true,
+ }
+ }
+
+ /// Transfer the mountpoint to `ResolvedMount` without cleanup on drop.
+ fn disarm(mut self) -> PathBuf {
+ self.armed = false;
+ self.path.clone()
+ }
+}
+
+/// Remove partial setup when mounting fails before ownership is transferred.
+impl Drop for MountpointGuard {
+ fn drop(&mut self) {
+ if self.armed {
+ cleanup_mountpoint(&self.path, self.mounted);
+ }
+ }
+}
+
+impl ResolvedMount {
+ pub(crate) fn pin(payload_root: &Path, sub_path: &str, read_only: bool) -> BoxliteResult<Self> {
+ Self::pin_with_hook(payload_root, sub_path, read_only, || {})
+ }
+
+ /// Pin a volume subdirectory at a temporary mountpoint.
+ ///
+ /// Clone the resolved directory into a mountable tree, move that tree onto
+ /// a pre-created guarded directory, then remount the bind read-only when
+ /// requested. The guard removes the mountpoint if any step fails.
+ fn pin_with_hook(
+ payload_root: &Path,
+ sub_path: &str,
+ read_only: bool,
+ before_pin: impl FnOnce(),
+ ) -> BoxliteResult<Self> {
+ let directory = open_subdir(payload_root, sub_path)?;
+ before_pin();
+ // Pre-create a unique directory before mounting so the move target is
+ // private and can be removed deterministically on error.
+ let path = payload_root
+ .parent()
+ .unwrap_or(payload_root)
+ .join(format!(".resolved-{}", uuid::Uuid::new_v4().simple()));
+ std::fs::create_dir(&path).map_err(|error| {
+ BoxliteError::Storage(format!(
+ "create resolved mount point {}: {error}",
+ path.display()
+ ))
+ })?;
+ let mut guard = MountpointGuard::new(path);
+ let target = CString::new(guard.path.as_os_str().as_bytes()).map_err(|_| {
+ BoxliteError::InvalidArgument("resolved mount point contains NUL".into())
+ })?;
+ let empty = CString::new("").unwrap();
+ let tree = sys::open_tree(
+ directory.as_raw_fd(),
+ &empty,
+ sys::OPEN_TREE_CLONE | sys::OPEN_TREE_CLOEXEC | sys::AT_EMPTY_PATH,
+ )
+ .map_err(|error| {
+ BoxliteError::Unsupported(format!(
+ "open_tree is required for volume sub_path mounts: {error}"
+ ))
+ })?;
+ sys::move_mount(
+ tree.as_raw_fd(),
+ &empty,
+ nix::libc::AT_FDCWD,
+ &target,
+ sys::MOVE_MOUNT_F_EMPTY_PATH,
+ )
+ .map_err(|error| {
+ BoxliteError::Unsupported(format!(
+ "move_mount is required for volume sub_path mounts: {error}"
+ ))
+ })?;
+ guard.mounted = true;
+ if read_only {
+ mount(
+ None::<&str>,
+ &guard.path,
+ None::<&str>,
+ MsFlags::MS_BIND | MsFlags::MS_REMOUNT | MsFlags::MS_RDONLY,
+ None::<&str>,
+ )
+ .map_err(|error| {
+ BoxliteError::Storage(format!(
+ "failed to make resolved volume mount read-only at {}: {error}",
+ guard.path.display()
+ ))
+ })?;
+ }
+ Ok(Self {
+ path: guard.disarm(),
+ })
+ }
+
+ pub(crate) fn path(&self) -> &Path {
+ &self.path
+ }
+}
+
+/// Unmount and remove the mountpoint owned for the container's lifetime.
+impl Drop for ResolvedMount {
+ fn drop(&mut self) {
+ cleanup_mountpoint(&self.path, true);
+ }
+}
+
+/// Best-effort teardown; warnings do not mask the container outcome.
+fn cleanup_mountpoint(path: &Path, mounted: bool) {
+ if mounted {
+ if let Err(error) = umount(path) {
+ tracing::warn!(path = %path.display(), %error, "Failed to unmount resolved volume");
+ }
+ }
+ if let Err(error) = std::fs::remove_dir(path) {
+ tracing::warn!(path = %path.display(), %error, "Failed to remove resolved mount point");
+ }
+}
+
+/// Open a payload-relative directory without allowing path-based escape.
+///
+/// `RESOLVE_BENEATH` keeps resolution under the volume root, while refusing
+/// symlinks and magic links prevents a payload-controlled link from redirecting
+/// to a host path outside the volume.
+fn open_subdir(payload_root: &Path, sub_path: &str) -> BoxliteResult<OwnedFd> {
+ validate_sub_path(sub_path)?;
+ let root = open(
+ payload_root,
+ OFlag::O_PATH | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC,
+ Mode::empty(),
+ )
+ .map_err(|error| BoxliteError::Storage(format!("open volume payload: {error}")))?;
+ let how = OpenHow::new()
+ .flags(OFlag::O_PATH | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC)
+ .resolve(
+ ResolveFlag::RESOLVE_BENEATH
+ | ResolveFlag::RESOLVE_NO_SYMLINKS
+ | ResolveFlag::RESOLVE_NO_MAGICLINKS,
+ );
+ let fd = openat2(root.as_raw_fd(), sub_path, how)
+ .map_err(|error| sub_path_error(sub_path, error))?;
+ Ok(unsafe { OwnedFd::from_raw_fd(fd) })
+}
+
+fn sub_path_error(sub_path: &str, error: nix::errno::Errno) -> BoxliteError {
+ match error {
+ nix::errno::Errno::ENOENT => {
+ BoxliteError::NotFound(format!("volume sub_path {sub_path:?} does not exist"))
+ }
+ nix::errno::Errno::ELOOP | nix::errno::Errno::ENOTDIR => BoxliteError::InvalidArgument(
+ format!("volume sub_path {sub_path:?} contains a symlink or non-directory component"),
+ ),
+ nix::errno::Errno::ENOSYS => BoxliteError::Unsupported(format!(
+ "volume sub_path {sub_path:?} requires openat2 support: {error}"
+ )),
+ _ => BoxliteError::Storage(format!("resolve volume sub_path {sub_path:?}: {error}")),
+ }
+}
+
+fn validate_sub_path(sub_path: &str) -> BoxliteResult<()> {
+ if sub_path.is_empty()
+ || sub_path.contains('\0')
+ || sub_path.len() > 4096
+ || sub_path.starts_with('/')
+ || sub_path.ends_with('/')
+ || sub_path.split('/').count() > 64
+ || sub_path
+ .split('/')
+ .any(|part| part.is_empty() || part == "." || part == "..")
+ || sub_path.split('/').any(|part| part.len() > 255)
+ {
+ return Err(BoxliteError::InvalidArgument(format!(
+ "invalid volume sub_path {sub_path:?}"
+ )));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn resolved_mount_survives_path_replacement_and_stays_read_only() {
+ const CHILD: &str = "BOXLITE_RESOLVED_MOUNT_TEST_CHILD";
+ if std::env::var_os(CHILD).is_none() {
+ let status = std::process::Command::new("unshare")
+ .args(["--user", "--map-root-user", "--mount"])
+ .arg(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "storage::resolved_mount::tests::resolved_mount_survives_path_replacement_and_stays_read_only",
+ "--nocapture",
+ ])
+ .env(CHILD, "1")
+ .status()
+ .expect("start isolated resolved-mount test");
+ assert!(status.success(), "resolved-mount test failed: {status}");
+ return;
+ }
+ mount(
+ None::<&str>,
+ Path::new("/"),
+ None::<&str>,
+ MsFlags::MS_REC | MsFlags::MS_PRIVATE,
+ None::<&str>,
+ )
+ .unwrap();
+ let root = tempfile::tempdir().unwrap();
+ let backend = root.path().join("team/backend");
+ let moved = root.path().join("team/moved");
+ let sibling = root.path().join("sibling");
+ std::fs::create_dir_all(&backend).unwrap();
+ std::fs::create_dir(&sibling).unwrap();
+ std::fs::write(backend.join("result"), b"original").unwrap();
+ std::fs::write(sibling.join("secret"), b"secret").unwrap();
+
+ let resolved = ResolvedMount::pin_with_hook(root.path(), "team/backend", true, || {
+ std::fs::rename(&backend, &moved).unwrap();
+ std::os::unix::fs::symlink(&sibling, &backend).unwrap();
+ });
+ let resolved = resolved.expect("pin the original directory");
+ assert_eq!(
+ std::fs::read(resolved.path().join("result")).unwrap(),
+ b"original"
+ );
+ assert!(!resolved.path().join("secret").exists());
+ assert_eq!(
+ std::fs::write(resolved.path().join("result"), b"changed")
+ .unwrap_err()
+ .raw_os_error(),
+ Some(nix::libc::EROFS)
+ );
+ drop(resolved);
+ assert_eq!(std::fs::read(moved.join("result")).unwrap(), b"original");
+ }
+
+ #[test]
+ fn missing_openat2_is_unsupported() {
+ let error = sub_path_error("workspace", nix::errno::Errno::ENOSYS);
+ assert!(matches!(error, BoxliteError::Unsupported(_)), "{error:?}");
+ }
+
+ #[test]
+ fn pin_cleans_mountpoint_on_success_and_failure() {
+ const CHILD: &str = "BOXLITE_RESOLVED_MOUNT_CLEANUP_TEST_CHILD";
+ if std::env::var_os(CHILD).is_none() {
+ let status = std::process::Command::new("unshare")
+ .args(["--user", "--map-root-user", "--mount"])
+ .arg(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "storage::resolved_mount::tests::pin_cleans_mountpoint_on_success_and_failure",
+ "--nocapture",
+ ])
+ .env(CHILD, "1")
+ .status()
+ .expect("start isolated resolved-mount cleanup test");
+ assert!(
+ status.success(),
+ "resolved-mount cleanup test failed: {status}"
+ );
+ return;
+ }
+ mount(
+ None::<&str>,
+ Path::new("/"),
+ None::<&str>,
+ MsFlags::MS_REC | MsFlags::MS_PRIVATE,
+ None::<&str>,
+ )
+ .unwrap();
+ let parent = tempfile::tempdir().unwrap();
+ let payload = parent.path().join("payload");
+ std::fs::create_dir_all(payload.join("subdir")).unwrap();
+
+ let resolved = ResolvedMount::pin(&payload, "subdir", false)
+ .expect("pin must succeed before testing cleanup");
+ let mountpoint = resolved.path().to_path_buf();
+ assert!(mountpoint.exists());
+ drop(resolved);
+
+ assert!(
+ !mountpoint.exists(),
+ "pin must remove the mountpoint directory"
+ );
+ let leftovers = std::fs::read_dir(parent.path())
+ .unwrap()
+ .map(|entry| entry.unwrap().file_name())
+ .filter(|name| name.to_string_lossy().starts_with(".resolved-"))
+ .count();
+ assert_eq!(leftovers, 0, "pin must not leave mountpoint directories");
+ }
+
+ #[test]
+ fn subdir_resolution_rejects_escape_and_symlink() {
+ let directory = tempfile::tempdir().unwrap();
+ std::fs::create_dir_all(directory.path().join("team/backend")).unwrap();
+ std::os::unix::fs::symlink("backend", directory.path().join("team/link")).unwrap();
+
+ open_subdir(directory.path(), "team/backend").expect("real directory");
+ for invalid in [
+ "/etc",
+ "../escape",
+ "team//backend",
+ "team/./backend",
+ "team/link",
+ "team/\0backend",
+ ] {
+ let error = open_subdir(directory.path(), invalid)
+ .err()
+ .unwrap_or_else(|| panic!("{invalid} must be rejected"));
+ assert!(
+ matches!(error, BoxliteError::InvalidArgument(_)),
+ "{invalid}: {error:?}"
+ );
+ }
+ let error =
+ open_subdir(directory.path(), "team/missing").expect_err("missing subdirectory");
+ assert!(matches!(error, BoxliteError::NotFound(_)), "{error:?}");
+ }
+}
diff --git a/src/shared/proto/boxlite/v1/service.proto b/src/shared/proto/boxlite/v1/service.proto
index 954a5bbf1..f3d0fa35e 100644
--- a/src/shared/proto/boxlite/v1/service.proto
+++ b/src/shared/proto/boxlite/v1/service.proto
@@ -218,6 +218,7 @@ message PingRequest {}
message PingResponse {
string version = 1; // Guest agent version
+ bool safe_managed_volume_sub_path = 2; // Supports pinned managed-volume subdirectories
}
message ShutdownRequest {}
@@ -374,6 +375,31 @@ message CACert {
string pem = 1; // PEM-encoded X.509 certificate
}
+enum BindMountKind {
+ // Compatibility mode for requests from hosts predating the kind field.
+ // The guest uses the legacy rule: empty subpath means a whole directory,
+ // while non-empty subpath means a single file. New hosts must set an explicit kind.
+ // Example: an old host sends subpath="app.conf" without kind to mount one file.
+ BIND_MOUNT_KIND_UNSPECIFIED = 0;
+
+ // Mount an entire host directory or a whole managed-volume payload.
+ // subpath must be empty.
+ // Examples: -v /host/data:/data or -v workspace:/workspace.
+ BIND_MOUNT_KIND_WHOLE_DIRECTORY = 1;
+
+ // Mount one host file staged in its own shared directory.
+ // subpath contains the file name within that directory.
+ // Example: -v /host/app.conf:/etc/app.conf sends subpath="app.conf".
+ BIND_MOUNT_KIND_SINGLE_FILE = 2;
+
+ // Mount one existing relative directory inside a managed-volume payload.
+ // subpath contains the relative directory path. The guest resolves and pins
+ // it without following symlinks; older guests must be rejected by the version gate.
+ // Example: source=workspace,target=/workspace,sub_path=team/backend sends
+ // subpath="team/backend".
+ BIND_MOUNT_KIND_MANAGED_SUB_DIRECTORY = 3;
+}
+
// Bind mount from guest volume to container path
// Uses convention-based paths: /run/boxlite/shared/containers/{container_id}/volumes/{volume_name}
message BindMount {
@@ -389,10 +415,12 @@ message BindMount {
// guest applies mount_setattr(MOUNT_ATTR_IDMAP) to remap transparently.
uint32 owner_uid = 4;
uint32 owner_gid = 5;
- // For a single-file mount, the file name within the shared volume dir; the
- // guest bind-mounts {volume_dir}/{subpath} rather than the whole dir. Empty
- // for a whole-directory mount.
+ // SINGLE_FILE: file name within the staged share directory.
+ // MANAGED_SUB_DIRECTORY: relative directory inside the volume payload.
+ // Empty for WHOLE_DIRECTORY. UNSPECIFIED retains the legacy interpretation.
string subpath = 6;
+ // Explicit payload interpretation. Old hosts omit this field.
+ BindMountKind kind = 7;
}
message ContainerInitResponse {
@@ -410,6 +438,8 @@ enum ContainerInitErrorKind {
// Zero keeps errors from older guests, which omit this field, internal.
CONTAINER_INIT_ERROR_KIND_INTERNAL = 0;
CONTAINER_INIT_ERROR_KIND_UNSUPPORTED = 1;
+ CONTAINER_INIT_ERROR_KIND_INVALID_ARGUMENT = 2;
+ CONTAINER_INIT_ERROR_KIND_NOT_FOUND = 3;
}
message ContainerInitError {
diff --git a/src/shared/src/lib.rs b/src/shared/src/lib.rs
index acaf528ea..e13055371 100644
--- a/src/shared/src/lib.rs
+++ b/src/shared/src/lib.rs
@@ -98,6 +98,41 @@ mod tests {
// Legacy string fields: listen_address (1), ca_public_key (2), principal (3).
const LEGACY_SSH_CONFIGURATION: &[u8] = b"\x0a\x0e127.0.0.1:2222\x12\x08test-key\x1a\x04root";
+ #[test]
+ fn legacy_bind_mount_wire_decodes_with_unspecified_kind() {
+ use prost::Message;
+ for (wire, subpath) in [(&[][..], ""), (&b"\x32\x08app.conf"[..], "app.conf")] {
+ let decoded = super::BindMount::decode(wire).expect("decode old host request");
+ assert_eq!(decoded.subpath, subpath);
+ assert_eq!(decoded.kind, super::BindMountKind::Unspecified as i32);
+ }
+ }
+
+ #[test]
+ fn bind_mount_kind_is_additive_for_legacy_guests() {
+ use prost::Message;
+
+ #[derive(prost::Message)]
+ struct LegacyBindMount {
+ #[prost(string, tag = "6")]
+ subpath: String,
+ }
+
+ for (kind, subpath) in [
+ (super::BindMountKind::WholeDirectory, ""),
+ (super::BindMountKind::SingleFile, "app.conf"),
+ ] {
+ let mount = super::BindMount {
+ kind: kind as i32,
+ subpath: subpath.to_string(),
+ ..Default::default()
+ };
+ let legacy = LegacyBindMount::decode(mount.encode_to_vec().as_slice())
+ .expect("old guest decodes the mount and ignores kind");
+ assert_eq!(legacy.subpath, subpath);
+ }
+ }
+
#[test]
fn ssh_configuration_legacy_fields_decode_without_config() {
use prost::Message;