The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(mounts): persist host directory mounts behind bx.mount() (#3060)
Vitus39c3b008101d
diff --git a/docs/reference/rust/README.md b/docs/reference/rust/README.mdindex cf78ed7a3..a1ac58998 100644--- a/docs/reference/rust/README.md+++ b/docs/reference/rust/README.md@@ -449,6 +449,7 @@ HTTP contract, reconfiguration, disable, and generation semantics.| `metrics` | `async fn metrics(&self) -> BoxliteResult<BoxMetrics>` | Get box metrics || `stop` | `async fn stop(&self) -> BoxliteResult<()>` | Stop the box || `executions` | `fn executions(&self) -> ExecutionsHandle` | Live session inventory and control recovery; never boots a box |+| `mount` | `fn mount(&self) -> MountHandle` | Manage persistent host directory mounts on a local native box || `attach` | `async fn attach(&self, options: AttachOptions) -> BoxliteResult<Execution>` | Attach to init or a named live session; only one output reader is allowed |#### Online disk growth@@ -542,6 +543,95 @@ To recover streams after a client process exits, call`attach(AttachOptions::execution(id))`; an existing reader is reported as aconflict rather than silently returning no output.+#### MountHandle++`LiteBox::mount()` returns an owned, cloneable `MountHandle`. Directory mounts+require the `native-vmm` experimental feature and the local Linux x86_64 native+engine. Changes require a container configured without `CAP_SYS_ADMIN`.++| Method | Signature | Description |+|--------|-----------|-------------|+| `add` | `async fn add(&self, request: MountRequest) -> BoxliteResult<MountInfo>` | Save a directory and deliver it immediately if the container is running |+| `remove` | `async fn remove(&self, target: impl AsRef<Path>) -> BoxliteResult<()>` | Remove a declaration and lazily detach its live mount |+| `list` | `async fn list(&self) -> BoxliteResult<Vec<MountInfo>>` | Read saved directories and current delivery progress |+| `get` | `async fn get(&self, target: impl AsRef<Path>) -> BoxliteResult<Option<MountInfo>>` | Read one entry by normalized container path, or `None` if absent |++A `MountRequest` takes an absolute host directory, a UTF-8 target below `/`,+and `read_only`. The target may omit intermediate directories and must exclude+`..`. A directory added at runtime, and a saved one at its next start, lands+on a target the guest creates when missing; a target with entries, or one+reached through a symbolic link, is refused. Adding at an occupied target+returns `InvalidState`, and so does a target with another mount below it: the+new mount would cover that one. A target below an existing mount is allowed.+A target at, below or above `/proc`, `/dev`, `/sys` or `/tmp` returns+`InvalidArgument`: the container mounts those itself. A source that is, holds+or lies inside a delivered directory returns `InvalidState`: the next start+delivers each directory as its own share, and refuses overlapping ones.++On a stopped or newly created box, `add` returns `Configured` and leaves the+box idle. The next start delivers each saved directory before the first user+process runs. A delivery failure identifies the target, and so does a start+that finds a saved directory which would cover a mount applied before it or+which a mount applied after it would cover, or which shares a mount with+another directory through an image link or two spellings of one target. You+can remove its declaration even if the host directory has disappeared; the+target is then free for good. Directory binds from either creation format,+`BoxOptions.volumes` or `BoxOptions.mounts`, can also be queried and removed on+a supported box. A clone or an export carries every committed `add` and+`remove`.++A guest agent or kernel that cannot record mounts still starts a box whose+directories were all created with it: they stay plain binds, so `remove` asks+for a stop. A box with a directory added at runtime does not start there+until that declaration is removed while the box is stopped.++On a running box, `add` returns `Mounted` after guest confirmation and the+SQLite commit. `remove` returns `()` after the guest detaches the mount, the+shim retires its export and the runtime commits the removal. Open file and+directory descriptors stay usable. Remove nested mounts deepest first: while+one sits below the target, `remove` returns `InvalidState` and the entry is+again what the removal found: `Mounted`, or `Preparing` for an interrupted+add. A mount the box was created with below the target, such as a file bind,+keeps the directory mounted until the box stops. After success `get(target)`+returns `None` and a second `remove(target)` returns `NotFound`.++`list` and `get` read the last SQLite commit while delivery is in flight.+`Preparing` identifies a pending add and `Detaching` identifies pending cleanup.+You can retry incomplete cleanup by target while the same VM is running.++An admitted running change finishes independently of its caller's wait.+Dropping its future neither undoes a commit nor proves that an unconfirmed+guest operation was cancelled.++Once that VM stops, only committed declarations determine the next boot. If a+reply was lost, a fresh handle's `get` returns `Configured` for a committed+add or an uncommitted removal. It returns `None` for an uncommitted add or a+committed removal. Each new VM confirms the mounts it actually delivered.++A running change starts the container first, as any live operation does. A+paused box returns `InvalidState` on a change.++#### Example++With an existing host directory `/srv/project` and a newly created native box+configured with `auto_delete: Some(0)`, save a read-only workspace and start it.++```rust+let mounts = litebox.mount();+let info = mounts+ .add(MountRequest {+ source: "/srv/project".into(),+ target: "/workspace".into(),+ read_only: true,+ })+ .await?;+assert_eq!(info.state, MountState::Configured);+litebox.start().await?;+assert_eq!(mounts.get("/workspace").await?.unwrap().state, MountState::Mounted);+mounts.remove("/workspace").await?;+assert!(mounts.get("/workspace").await?.is_none());+```+#### Lifecycle- `start()` initializes VM for `Configured` or `Stopped` boxesdiff --git a/src/boxlite/src/db/boxes.rs b/src/boxlite/src/db/boxes.rsindex d2a509984..1036be384 100644--- a/src/boxlite/src/db/boxes.rs+++ b/src/boxlite/src/db/boxes.rs@@ -6,6 +6,8 @@//!//! Each table has queryable columns for filtering + JSON blob for full struct.+pub(crate) mod mounts;+use chrono::Utc;use rusqlite::{OptionalExtension, params};#[cfg(any(test, feature = "test-support"))]@@ -143,8 +145,19 @@ impl BoxStore {/// Updates queryable columns and JSON while preserving runtime overrides from the row./// Returns error if box doesn't exist (Podman pattern: verify RowsAffected).pub fn update_state(&self, box_id: &str, state: &BoxState) -> BoxliteResult<()> {- let conn = self.db.conn();+ Self::write_state(&self.db.conn(), box_id, state, None)+ }+ /// Write the lifecycle state, keeping what the row holds besides it: the+ /// runtime overrides, and the directory mounts unless `mounts` replaces+ /// them. A handle that read an older state cannot replace them with its+ /// copy.+ fn write_state(+ conn: &rusqlite::Connection,+ box_id: &str,+ state: &BoxState,+ mounts: Option<&str>,+ ) -> BoxliteResult<()> {let json = serde_json::to_string(state).map_err(|e| BoxliteError::Database(format!("Failed to serialize state: {}", e)))?;@@ -152,9 +165,10 @@ impl BoxStore {"UPDATE box_state SET status = ?1, pid = ?2, \json = json_set(?3, \'$.outbound_policy', json_extract(json, '$.outbound_policy'), \- '$.disk_size_gb', json_extract(json, '$.disk_size_gb')) \+ '$.disk_size_gb', json_extract(json, '$.disk_size_gb'), \+ '$.mounts', coalesce(json(?5), json(coalesce(json_extract(json, '$.mounts'), '{}')))) \WHERE id = ?4",- params![state.status.as_str(), state.pid, json, box_id],+ params![state.status.as_str(), state.pid, json, box_id, mounts],))?;// Podman pattern: verify rows were actually updated@@ -466,6 +480,138 @@ mod tests {use std::path::PathBuf;use tempfile::tempdir;+ #[test]+ fn stale_lifecycle_writer_preserves_directory_mounts() {+ let (store, dir) = create_test_db();+ store+ .save(&create_test_config(TEST_ID_1), &BoxState::new())+ .unwrap();+ let path = dir.path().join("test.db");+ let mut stale = store.load_state(TEST_ID_1).unwrap().unwrap();+ let other = BoxStore::new(Database::open(&path).unwrap());+ // Two clients, two targets, one row: each write lands.+ for (client, target) in [(&store, "/work"), (&other, "/second")] {+ client+ .update_mounts(TEST_ID_1, |mounts| {+ mounts.declare(crate::MountRequest {+ source: "/srv/data".into(),+ target: target.into(),+ read_only: true,+ });+ Ok(())+ })+ .unwrap();+ }++ // The handle stops the box with the state it read before both writes.+ stale.status = BoxStatus::Stopped;+ store.update_state(TEST_ID_1, &stale).unwrap();+ let mounts = BoxStore::new(Database::open(&path).unwrap())+ .mounts(TEST_ID_1)+ .unwrap();+ let declared: Vec<_> = mounts+ .visible()+ .into_iter()+ .map(|mount| (mount.target.to_string_lossy().into_owned(), mount.read_only))+ .collect();+ assert_eq!(+ declared,+ [("/second".to_owned(), true), ("/work".to_owned(), true)]+ );+ assert_eq!(mounts.state.status, BoxStatus::Stopped);+ }++ #[test]+ fn creation_binds_merge_with_committed_changes_across_reopen() {+ use crate::runtime::options::{MountSpec, VolumeSpec};++ for typed in [false, true] {+ let (store, dir) = create_test_db();+ let path = dir.path().join("test.db");+ let mut config = create_test_config(TEST_ID_1);+ let file = dir.path().join("a-file");+ std::fs::write(&file, b"static").unwrap();+ if typed {+ let mut mount = MountSpec::bind_mount(dir.path().to_str().unwrap(), "//work/./");+ mount.read_only = true;+ config.options.mounts = vec![+ mount,+ MountSpec::bind_mount(file.to_str().unwrap(), "/file"),+ MountSpec::volume_mount("volume-id", "/managed"),+ ];+ } else {+ let mut volume = VolumeSpec::bind_mount(dir.path().to_str().unwrap(), "//work/./");+ volume.read_only = true;+ config.options.volumes = vec![+ volume,+ VolumeSpec::bind_mount(file.to_str().unwrap(), "/file"),+ VolumeSpec::managed_volume("volume-id", "/managed"),+ ];+ }+ store.save(&config, &BoxState::new()).unwrap();++ // A row without the mounts field reads as its creation options.+ let reopened = BoxStore::new(Database::open(&path).unwrap());+ let mounts = reopened.mounts(TEST_ID_1).unwrap();+ assert_eq!(+ mounts.visible(),+ vec![crate::MountInfo {+ source: dir.path().into(),+ target: "/work".into(),+ read_only: true,+ state: crate::MountState::Configured,+ }]+ );+ assert!(mounts.occupied("/managed") && mounts.occupied("/file"));+ reopened+ .update_mounts(TEST_ID_1, |mounts| {+ mounts.forget("/work");+ mounts.declare(crate::MountRequest {+ source: "/srv/data".into(),+ target: "/late".into(),+ read_only: false,+ });+ Ok(())+ })+ .unwrap();++ let reopened = BoxStore::new(Database::open(&path).unwrap());+ let mounts = reopened.mounts(TEST_ID_1).unwrap();+ let mut options = reopened.load_config(TEST_ID_1).unwrap().unwrap().options;+ mounts.apply_to_boot(&mut options);+ let targets: Vec<_> = options+ .volumes+ .iter()+ .map(|volume| volume.guest_path.as_str())+ .chain(options.mounts.iter().map(|mount| mount.target.as_str()))+ .collect();+ assert_eq!(targets, ["/file", "/managed", "/late"]);+ assert!(!mounts.occupied("/work") && mounts.is_added("/late"));++ // A file bind whose file is gone reads as a directory, so the box+ // can be made bootable again by removing it.+ std::fs::remove_file(&file).unwrap();+ assert!(+ reopened+ .mounts(TEST_ID_1)+ .unwrap()+ .lookup("/file")+ .is_some()+ );+ // A removed file bind stays removed: its target is free again+ // when the file comes back.+ reopened+ .update_mounts(TEST_ID_1, |mounts| {+ mounts.forget("/file");+ Ok(())+ })+ .unwrap();+ std::fs::write(&file, b"static").unwrap();+ let mounts = reopened.mounts(TEST_ID_1).unwrap();+ assert!(!mounts.occupied("/file") && mounts.lookup("/file").is_none());+ }+ }+fn create_test_db() -> (BoxStore, tempfile::TempDir) {let dir = tempdir().unwrap();let db_path = dir.path().join("test.db");diff --git a/src/boxlite/src/db/boxes/mounts.rs b/src/boxlite/src/db/boxes/mounts.rsnew file mode 100644index 000000000..16d8922dd--- /dev/null+++ b/src/boxlite/src/db/boxes/mounts.rs@@ -0,0 +1,427 @@+//! A directory declaration belongs to the box; delivery progress belongs to+//! one VM run. Both live in the `mounts` object of the box's state row, next to+//! the outbound policy, and every write is one short transaction.+//!+//! Only the native engine reads or changes them: its mount operations, a+//! start, a clone or an export.+#![cfg_attr(+ not(all(feature = "native", target_os = "linux", target_arch = "x86_64")),+ allow(dead_code)+)]++use std::collections::{BTreeMap, BTreeSet};++use boxlite_shared::constants::{normalize_target, path_is_below};+use boxlite_shared::errors::{BoxliteError, BoxliteResult};+use chrono::{DateTime, Utc};+use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};+use serde::{Deserialize, Serialize};+use std::fmt::Display;++use super::BoxStore;+use crate::db::db_err;+use crate::litebox::mounts::{MountInfo, MountProgress, MountRequest, MountState};+use crate::runtime::advanced_options::AdvancedBoxOptions;+use crate::runtime::options::{BoxOptions, MountSpec, MountType, VolumeSpec};+use crate::runtime::types::BoxState;+use crate::volumes::{ContainerMount, ContainerMountPayload};++/// What the row keeps besides the creation options.+#[derive(Default, Serialize, Deserialize)]+struct Saved {+ /// Added directories, and `None` where a directory was removed.+ #[serde(default)]+ changes: BTreeMap<String, Option<MountRequest>>,+ /// The progress of the run that last wrote one. No other run shows it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ run: Option<Run>,+}++#[derive(Serialize, Deserialize)]+struct Run {+ pid: u32,+ started_at: Option<DateTime<Utc>>,+ targets: BTreeMap<String, MountProgress>,+}++/// The directory declarations of a box, with the progress of its current VM run.+#[derive(Debug)]+pub(crate) struct Mounts {+ /// The state the declarations were read with. A start stores its live+ /// state again together with the mounts it confirmed.+ pub state: BoxState,+ /// The directories the box boots with, by normalized target: the ones it+ /// was created with, with every committed change applied.+ pub declarations: BTreeMap<String, MountRequest>,+ /// Last committed progress of the current VM run, by target.+ pub progress: BTreeMap<String, MountProgress>,+ /// Creation targets that are no directory declaration: files and managed volumes.+ pub(crate) unmanaged: BTreeSet<String>,+ /// Creation targets whose source is a file: no directory can sit below one.+ pub(crate) files: BTreeSet<String>,+ changes: BTreeMap<String, Option<MountRequest>>,+}++/// The mounts of the creation formats, split by what their sources are on the+/// host.+struct Creation {+ directories: BTreeMap<String, MountRequest>,+ unmanaged: BTreeSet<String>,+ files: BTreeSet<String>,+}++impl Creation {+ /// No write changes the creation options after create, so they are read+ /// apart from the state row. The split inspects the host filesystem, so+ /// callers take the connection for this read alone and open no transaction+ /// around it.+ fn read(conn: &Connection, id: &str) -> BoxliteResult<Self> {+ let (volumes, mounts): (String, String) = db_err!(+ conn.query_row(+ "SELECT coalesce(json ->> '$.options.volumes', '[]'),+ coalesce(json ->> '$.options.mounts', '[]') FROM box_config WHERE id = ?1",+ params![id],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .optional()+ )?+ .ok_or_else(|| BoxliteError::NotFound(id.to_owned()))?;+ let volumes: Vec<VolumeSpec> = db_err!(serde_json::from_str(&volumes))?;+ let mounts: Vec<MountSpec> = db_err!(serde_json::from_str(&mounts))?;+ let mut this = Self {+ unmanaged: volumes+ .iter()+ .filter(|volume| volume.managed_volume.is_some())+ .map(|volume| volume.guest_path.as_str())+ .chain(+ mounts+ .iter()+ .filter(|mount| mount.mount_type != MountType::Bind)+ .map(|mount| mount.target.as_str()),+ )+ .filter_map(normalize_target)+ .collect(),+ directories: BTreeMap::new(),+ files: BTreeSet::new(),+ };+ let directories = volumes+ .iter()+ .filter(|volume| volume.managed_volume.is_none())+ .map(|volume| {+ (+ volume.host_path.as_str(),+ volume.guest_path.as_str(),+ volume.read_only,+ )+ })+ .chain(+ mounts+ .iter()+ .filter(|mount| mount.mount_type == MountType::Bind)+ .filter_map(|mount| {+ Some((+ mount.source.as_deref()?,+ mount.target.as_str(),+ mount.read_only,+ ))+ }),+ );+ for (source, target, read_only) in directories {+ let Some(key) = normalize_target(target) else {+ continue;+ };+ // Both creation formats take a file in the same field. A bind whose+ // source is gone still counts as a directory, so it stays removable.+ if this.unmanaged.contains(&key) {+ this.unmanaged.insert(key);+ } else if std::fs::metadata(source).is_ok_and(|metadata| !metadata.is_dir()) {+ this.unmanaged.insert(key.clone());+ this.files.insert(key);+ } else {+ this.directories.insert(+ key.clone(),+ MountRequest {+ source: source.into(),+ target: key.into(),+ read_only,+ },+ );+ }+ }+ Ok(this)+ }+}++impl Mounts {+ fn load(conn: &Connection, id: &str, creation: Creation) -> BoxliteResult<Self> {+ // One statement, so the state and the mounts come from the same WAL snapshot.+ let row: Option<(String, Option<String>)> = db_err!(+ conn.query_row(+ "SELECT json, json ->> '$.mounts' FROM box_state WHERE id = ?1",+ params![id],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .optional()+ )?;+ let (state, saved) = row.ok_or_else(|| BoxliteError::NotFound(id.to_owned()))?;+ let state: BoxState = db_err!(serde_json::from_str(&state))?;+ let saved: Saved = match saved {+ Some(json) => db_err!(serde_json::from_str(&json))?,+ None => Saved::default(),+ };+ let mut this = Self {+ // Progress belongs to one run. A stopped box, or a later run, has none.+ progress: saved+ .run+ .filter(|run| Some(run.pid) == state.pid && run.started_at == state.started_at)+ .map(|run| run.targets)+ .unwrap_or_default(),+ state,+ declarations: creation.directories,+ unmanaged: creation.unmanaged,+ files: creation.files,+ changes: BTreeMap::new(),+ };+ for (target, change) in saved.changes {+ this.apply(&target, change);+ }+ Ok(this)+ }++ /// Refuse a progress write once the box no longer runs the given VM.+ pub(crate) fn ensure_run(+ &self,+ pid: u32,+ started_at: Option<DateTime<Utc>>,+ ) -> BoxliteResult<()> {+ if Some(pid) == self.state.pid && self.state.started_at == started_at {+ Ok(())+ } else {+ Err(BoxliteError::Stopped(+ "the box's VM run ended; use runtime.get() for its next run".into(),+ ))+ }+ }++ /// Whether a target has a mount on record.+ pub(crate) fn occupied(&self, target: &str) -> bool {+ self.declarations.contains_key(target)+ || self.unmanaged.contains(target)+ || self.progress.contains_key(target)+ }++ /// A mount on record below `target`. A mount applied at `target` after it+ /// would cover it, and a lazy detach of `target` would take it along.+ pub(crate) fn below(&self, target: &str) -> Option<&str> {+ self.declarations+ .keys()+ .chain(self.unmanaged.iter())+ .chain(self.progress.keys())+ .find(|other| path_is_below(other, target))+ .map(String::as_str)+ }++ /// Whether `target` was added through `mount()`, not created with the box.+ pub(crate) fn is_added(&self, target: &str) -> bool {+ self.changes.get(target).is_some_and(Option::is_some)+ }++ /// Record what a change did to the target: a directory is declared there,+ /// or the target is free again, whatever its source is now.+ fn apply(&mut self, target: &str, change: Option<MountRequest>) {+ self.changes.insert(target.to_owned(), change.clone());+ match change {+ Some(request) => {+ self.declarations.insert(target.to_owned(), request);+ }+ None => {+ self.declarations.remove(target);+ self.unmanaged.remove(target);+ self.files.remove(target);+ }+ }+ }++ /// Save a declaration for the next start.+ pub(crate) fn declare(&mut self, request: MountRequest) {+ let target = request.target.to_string_lossy().into_owned();+ self.apply(&target, Some(request));+ }++ /// Drop the declaration at `target`.+ pub(crate) fn forget(&mut self, target: &str) {+ self.apply(target, None);+ }++ pub(crate) fn lookup(&self, target: &str) -> Option<MountInfo> {+ self.progress+ .get(target)+ .map(|entry| entry.request.info(entry.state))+ .or_else(|| {+ self.declarations+ .get(target)+ .map(|request| request.info(MountState::Configured))+ })+ }++ pub(crate) fn visible(&self) -> Vec<MountInfo> {+ self.progress+ .values()+ .map(|entry| entry.request.info(entry.state))+ .chain(+ self.declarations+ .iter()+ .filter(|(target, _)| !self.progress.contains_key(*target))+ .map(|(_, request)| request.info(MountState::Configured)),+ )+ .collect()+ }++ /// Write the committed changes into the options a box boots under: removed+ /// targets go, added directories join in the box's own creation format.+ pub(crate) fn apply_to_boot(&self, options: &mut BoxOptions) {+ if self.changes.is_empty() {+ return;+ }+ let changed = |target: &str| {+ normalize_target(target).is_some_and(|key| self.changes.contains_key(&key))+ };+ options+ .volumes+ .retain(|volume| !changed(&volume.guest_path));+ options.mounts.retain(|mount| !changed(&mount.target));+ // The volume resolver rejects a mixture of the two formats.+ let legacy = !options.volumes.is_empty();+ for request in self.changes.values().flatten() {+ // A declaration always comes from a checked request.+ let bind = (+ request.source.to_string_lossy(),+ request.target.to_string_lossy(),+ );+ if legacy {+ options.volumes.push(VolumeSpec {+ read_only: request.read_only,+ ..VolumeSpec::bind_mount(bind.0, bind.1)+ });+ } else {+ options.mounts.push(MountSpec {+ read_only: request.read_only,+ ..MountSpec::bind_mount(bind.0, bind.1)+ });+ }+ }+ }++ /// Refuse a declared source that is no longer a directory, before the+ /// volume resolver runs: it would mount a file in the directory's place,+ /// or fail without naming the target. A directory added through `mount()`+ /// also refuses a link, as it did when it was added.+ pub(crate) fn check_sources(&self) -> BoxliteResult<()> {+ for (target, request) in &self.declarations {+ let added = self.is_added(target);+ let metadata = if added {+ // A trailing separator or dot would make the kernel follow a final link.+ std::fs::symlink_metadata(request.source.components().as_path())+ } else {+ std::fs::metadata(&request.source)+ };+ let problem = match metadata {+ Ok(metadata) if metadata.is_dir() => continue,+ Ok(_) => "is not a directory anymore".to_owned(),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ "does not exist".to_owned()+ }+ Err(error) => format!("cannot be inspected: {error}"),+ };+ return Err(undeliverable(request, problem));+ }+ Ok(())+ }++ /// Have the guest record the mount the container runtime makes for each+ /// declared directory, so an online removal can select it. Returns the+ /// progress the start confirms for them.+ pub(crate) fn record(+ &self,+ mounts: &mut [ContainerMount],+ advanced: &AdvancedBoxOptions,+ ) -> BTreeMap<String, MountProgress> {+ let permits = advanced.permits_aggregate_mounts();+ let mut confirmed = BTreeMap::new();+ for mount in mounts {+ let Some((target, request)) = normalize_target(&mount.destination).and_then(|target| {+ self.declarations+ .get(&target)+ .map(|request| (target, request))+ }) else {+ continue;+ };+ let added = self.is_added(&target);+ // A directory created with the box keeps its static delivery+ // unless the container may detach it.+ if !added && !permits {+ continue;+ }+ let key = uuid::Uuid::new_v4();+ mount.payload = ContainerMountPayload::RecordedDirectory {+ key: key.to_string(),+ added,+ };+ confirmed.insert(+ target,+ MountProgress {+ request: request.clone(),+ state: MountState::Mounted,+ request_id: key.into_bytes(),+ export: None,+ delivered_at_start: true,+ },+ );+ }+ confirmed+ }+}++/// A start cannot use a declared directory. The target leads the message: it+/// is what the caller can query, and remove, while the box is stopped.+fn undeliverable(request: &MountRequest, cause: impl Display) -> BoxliteError {+ BoxliteError::InvalidState(format!(+ "cannot deliver the directory declared at {}: source {} {cause}",+ request.target.display(),+ request.source.display()+ ))+}+impl BoxStore {+ /// The declarations of box `id` and the progress of its current VM run.+ pub(crate) fn mounts(&self, id: &str) -> BoxliteResult<Mounts> {+ let creation = Creation::read(&self.db.conn(), id)?;+ Mounts::load(&self.db.conn(), id, creation)+ }++ /// Apply `change` to the declarations and progress of box `id`, with the+ /// state they were read with, in one write transaction.+ pub(crate) fn update_mounts<T>(+ &self,+ id: &str,+ change: impl FnOnce(&mut Mounts) -> BoxliteResult<T>,+ ) -> BoxliteResult<T> {+ // Before the transaction, so that the inspection in `Creation::read`+ // holds neither the connection nor the database write lock.+ let creation = Creation::read(&self.db.conn(), id)?;+ let mut conn = self.db.conn();+ let tx = db_err!(conn.transaction_with_behavior(TransactionBehavior::Immediate))?;+ let mut mounts = Mounts::load(&tx, id, creation)?;+ let result = change(&mut mounts)?;+ let saved = db_err!(serde_json::to_string(&Saved {+ changes: mounts.changes,+ run: (!mounts.progress.is_empty()).then(|| Run {+ pid: mounts.state.pid.unwrap_or_default(),+ started_at: mounts.state.started_at,+ targets: mounts.progress,+ }),+ }))?;+ Self::write_state(&tx, id, &mounts.state, Some(&saved))?;+ db_err!(tx.commit())?;+ Ok(result)+ }+}diff --git a/src/boxlite/src/db/mod.rs b/src/boxlite/src/db/mod.rsindex 340fdc0c7..34c2ade28 100644--- a/src/boxlite/src/db/mod.rs+++ b/src/boxlite/src/db/mod.rs@@ -24,6 +24,7 @@ use boxlite_shared::errors::{BoxliteError, BoxliteResult};pub(crate) use base_disk::BaseDiskStore;pub use boxes::BoxStore;+pub(crate) use boxes::mounts::Mounts;pub use images::{CachedImage, ImageIndexStore};pub(crate) use snapshot::SnapshotStore;diff --git a/src/boxlite/src/lib.rs b/src/boxlite/src/lib.rsindex 5d24e3547..f41cd17a3 100644--- a/src/boxlite/src/lib.rs+++ b/src/boxlite/src/lib.rs@@ -60,6 +60,7 @@ pub use litebox::snapshot_mgr::SnapshotInfo;pub use litebox::{AttachOptions, BoxCommand, CopyOptions, ExecResult, ExecStderr, ExecStdin, ExecStdout,Execution, ExecutionId, ExecutionInfo, ExecutionsHandle, HealthState, HealthStatus,+ MountHandle, MountInfo, MountRequest, MountState,};pub use litebox::{SshAccount, SshCaConfig, SshConfig, SshHandle, SshStatus};pub use metrics::{BoxMetrics, RuntimeMetrics};diff --git a/src/boxlite/src/litebox/box_impl.rs b/src/boxlite/src/litebox/box_impl.rsindex cbea5be7b..39db834e6 100644--- a/src/boxlite/src/litebox/box_impl.rs+++ b/src/boxlite/src/litebox/box_impl.rs@@ -36,6 +36,8 @@ use crate::runtime::types::BoxStatus;use crate::vmm::controller::VmmHandler;use crate::{BoxID, BoxInfo};+#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+pub(super) mod mounts;mod operations;pub(crate) use operations::{BoxEvent, BoxRun};use operations::{StopCommit, StopReason};@@ -1475,6 +1477,7 @@ impl BoxImpl {live: live_state,guard: mut cleanup_guard,resolved_image,+ mounts,} = builder.build().await?;// The box is up. If we adopted one whose init was already running, that@@ -1553,8 +1556,21 @@ impl BoxImpl {state.init_health_status();}- // Save to DB (cache for queries and recovery)- self.runtime.box_manager.save_box(&self.config.id, &state)?;+ // Save to DB (cache for queries and recovery). A new native VM+ // writes the mounts its start confirmed in the same transaction;+ // every other start only saves the state.+ if adopting_running || self.config.engine_kind != crate::vmm::VmmKind::Native {+ self.runtime.box_manager.save_box(&self.config.id, &state)?;+ } else {+ self.runtime.box_manager.store().update_mounts(+ self.config.id.as_str(),+ |recorded| {+ recorded.state = state.clone();+ recorded.progress = mounts;+ Ok(())+ },+ )?;+ }// Arm the watcher under the *same* lock that publishes Running+pid.// A concurrent handout runs `arm_watcher(None)`, which reads the state@@ -1819,6 +1835,32 @@ impl crate::runtime::backend::BoxBackend for BoxImpl {self.attach(options).await}+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ async fn mount_add(+ &self,+ request: crate::litebox::mounts::MountRequest,+ ) -> BoxliteResult<crate::litebox::mounts::MountInfo> {+ BoxImpl::mount_add(self, request).await+ }++ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ async fn mount_remove(&self, target: &std::path::Path) -> BoxliteResult<()> {+ BoxImpl::mount_remove(self, target).await+ }++ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ async fn mount_list(&self) -> BoxliteResult<Vec<crate::litebox::mounts::MountInfo>> {+ BoxImpl::mount_list(self).await+ }++ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ async fn mount_get(+ &self,+ target: &std::path::Path,+ ) -> BoxliteResult<Option<crate::litebox::mounts::MountInfo>> {+ BoxImpl::mount_get(self, target).await+ }+async fn metrics(&self) -> BoxliteResult<BoxMetrics> {self.metrics().await}diff --git a/src/boxlite/src/litebox/box_impl/mounts.rs b/src/boxlite/src/litebox/box_impl/mounts.rsnew file mode 100644index 000000000..f08b7d05d--- /dev/null+++ b/src/boxlite/src/litebox/box_impl/mounts.rs@@ -0,0 +1,879 @@+//! Persistent host directory mounts of a box: admission, then the change.+//!+//! Every operation first requires the `native-vmm` experimental opt-in and+//! the native engine, so an unsupported box is refused before anything is+//! opened or registered. A change then runs against the lifecycle it is+//! admitted to: a stopped box only commits a declaration for its next start;+//! a running one records `Preparing` or `Detaching`, delivers through the shim+//! and the guest, and commits the confirmation. Queries only read the store,+//! on the blocking pool: no lifecycle lock, no shim or guest exchange.+//! Nothing here starts or restarts the box.++use std::fs::File;+use std::future::Future;+use std::io;+use std::os::fd::AsRawFd;+use std::os::unix::fs::OpenOptionsExt;+use std::path::{Path, PathBuf};+use std::time::Duration;++use boxlite_shared::constants::{mount_tags::AGGREGATE, path_is_below, reserved_mount_target};+use boxlite_shared::errors::{BoxliteError, BoxliteResult};++use super::{BoxImpl, BoxRun};+use crate::db::{BoxStore, Mounts};+use crate::experimental::ExperimentalFeature;+use crate::litebox::mounts::{MountInfo, MountProgress, MountRequest, MountState, target_key};+use crate::lock::OwnedLockGuard;+use crate::portal::interfaces::ContainerInterface;+use crate::runtime::id::BoxID;+use crate::runtime::types::BoxStatus;+use crate::vmm::VmmKind;+use crate::vmm::controller::mount_control::{MountControlClient, MountRequestId};++/// How long one guest mount or detach may take before its outcome is unknown.+const GUEST_STEP_TIMEOUT: Duration = Duration::from_secs(30);++/// The running VM a change acts on, with the store that tracks its progress.+struct Running {+ store: BoxStore,+ id: BoxID,+ /// The run every store write must still name.+ run: BoxRun,+ /// Where the shim takes mount control.+ control: PathBuf,+ guest: ContainerInterface,+ container_id: String,+ /// The box's lifecycle lock, held until the change ends: no start or stop+ /// can replace the VM under it. Only its drop matters.+ _lifecycle: OwnedLockGuard,+}++impl Running {+ /// Run `change` inside one write transaction. The write is refused unless+ /// the box still runs the admitted run.+ fn update<T>(&self, change: impl FnOnce(&mut Mounts) -> BoxliteResult<T>) -> BoxliteResult<T> {+ let run = self.run;+ self.store.update_mounts(self.id.as_str(), |mounts| {+ mounts.ensure_run(run.pid, run.started_at)?;+ change(mounts)+ })+ }++ /// One blocking shim exchange, on the blocking pool.+ async fn control<T: Send + 'static>(+ &self,+ step: &'static str,+ request: impl FnOnce(&MountControlClient) -> io::Result<T> + Send + 'static,+ ) -> BoxliteResult<T> {+ let client = MountControlClient::new(&self.control);+ tokio::task::spawn_blocking(move || request(&client))+ .await+ .map_err(|error| BoxliteError::Internal(format!("{step} task: {error}")))?+ .map_err(|error| shim_error(step, error))+ }++ /// Retire the export at the shim. One that is already gone stays gone.+ async fn retire(&self, export: &str) -> BoxliteResult<()> {+ let export = export.to_owned();+ self.control("retire the export", move |client| client.remove(&export))+ .await+ }++ /// Have the guest bind the export at `target`. A refusal, see [`refusal`],+ /// means the guest refused before touching the container.+ async fn mount(&mut self, export: &str, target: &str, read_only: bool) -> BoxliteResult<()> {+ guest_step(+ "mount",+ target,+ self.guest+ .mount_aggregate(&self.container_id, export, AGGREGATE, target, read_only),+ )+ .await+ }++ /// Have the guest lazily detach the mount identity `export`.+ async fn detach(&mut self, export: &str, target: &str) -> BoxliteResult<()> {+ guest_step(+ "detach",+ target,+ self.guest.detach(&self.container_id, target, export),+ )+ .await+ }++ /// The export the shim registered for `request_id`, if any.+ async fn registered_export(&self, request_id: MountRequestId) -> BoxliteResult<Option<String>> {+ let record = self+ .control("find the registration", move |client| {+ client.find_registered(request_id)+ })+ .await?;+ Ok(record.map(|record| record.export))+ }++ /// Drop the reservation of a request that left nothing behind. A later+ /// request's entry at the target stays.+ fn release(&self, target: &str, request_id: MountRequestId) -> BoxliteResult<()> {+ self.update(|mounts| {+ if owned(mounts, target, request_id).is_some() {+ mounts.progress.remove(target);+ }+ Ok(())+ })+ }++ /// Commit the end of a removal: drop the declaration together with this+ /// request's entry. A later request's entry at the target stays.+ fn end(&self, target: &str, request_id: MountRequestId) -> BoxliteResult<()> {+ self.update(|mounts| {+ if owned(mounts, target, request_id).is_some() {+ mounts.forget(target);+ mounts.progress.remove(target);+ }+ Ok(())+ })+ }++ /// Report a refusal to detach this request's mount. The guest touched+ /// nothing, so its entry returns to `found`, the state the removal found.+ /// An outcome the guest did not report leaves the entry `Detaching` for a+ /// retry.+ fn refused(+ &self,+ target: &str,+ request_id: MountRequestId,+ found: MountState,+ error: BoxliteError,+ ) -> BoxliteError {+ if !refusal(&error) {+ return error;+ }+ let restored = self.update(|mounts| {+ if let Some(entry) = owned(mounts, target, request_id) {+ entry.state = found;+ }+ Ok(())+ });+ match restored {+ Err(stopped @ BoxliteError::Stopped(_)) => stopped,+ _ => error,+ }+ }++ /// End a failed change that left nothing behind: release its reservation+ /// and report why it failed.+ fn settle(self, target: &str, request_id: MountRequestId, error: BoxliteError) -> BoxliteError {+ match self.release(target, request_id) {+ Ok(()) => error,+ Err(release) => unconverged(error, release),+ }+ }++ /// Undo a failed add: bring its export to "no mount, no export", then+ /// release the entry. The entry leaves the store only once the cleanup is+ /// confirmed; otherwise it stays listed for a remove, and the original+ /// error is kept.+ async fn undo(+ mut self,+ target: &str,+ request_id: MountRequestId,+ export: &str,+ error: BoxliteError,+ detach: bool,+ ) -> BoxliteError {+ let cleanup = async {+ if detach {+ self.detach(export, target).await?;+ }+ self.retire(export).await+ }+ .await;+ match cleanup {+ Ok(()) => self.settle(target, request_id, error),+ Err(cleanup) => unconverged(error, cleanup),+ }+ }+}++/// One guest step under its deadline. An outcome the guest does not report in+/// time is unknown, the guest may have acted, so it is no refusal.+async fn guest_step<T>(+ step: &'static str,+ target: &str,+ call: impl Future<Output = BoxliteResult<T>>,+) -> BoxliteResult<T> {+ tokio::time::timeout(GUEST_STEP_TIMEOUT, call)+ .await+ .unwrap_or_else(|_| {+ Err(BoxliteError::Rpc(format!(+ "guest {step} of {target} did not finish within {GUEST_STEP_TIMEOUT:?}"+ )))+ })+}++/// The entry of `request_id` at `target`. Another request's entry, or none,+/// is not this request's to change.+fn owned<'a>(+ mounts: &'a mut Mounts,+ target: &str,+ request_id: MountRequestId,+) -> Option<&'a mut MountProgress> {+ mounts+ .progress+ .get_mut(target)+ .filter(|entry| entry.request_id == request_id)+}++/// A request as the shim, the guest and the store take it: an absolute UTF-8+/// source, and the target as every plane records it.+#[derive(Clone)]+struct CheckedRequest {+ source: String,+ target: String,+ read_only: bool,+}++impl CheckedRequest {+ /// The request to keep as a declaration and as progress.+ fn request(&self) -> MountRequest {+ MountRequest {+ source: PathBuf::from(&self.source),+ target: PathBuf::from(&self.target),+ read_only: self.read_only,+ }+ }++ /// The request as callers see it in `state`.+ fn info(&self, state: MountState) -> MountInfo {+ self.request().info(state)+ }+}++/// Validate a request. Invalid input stops here, before any descriptor, record+/// or declaration exists.+fn checked_request(request: &MountRequest) -> BoxliteResult<CheckedRequest> {+ if !request.source.is_absolute() {+ return Err(BoxliteError::InvalidArgument(format!(+ "source must be an absolute host path: {:?}",+ request.source+ )));+ }+ let source = request.source.to_str().ok_or_else(|| {+ BoxliteError::InvalidArgument(format!("source must be valid UTF-8: {:?}", request.source))+ })?;+ let target = target_key(&request.target)?;+ // The runtime mounts its own filesystems before any user mount applies,+ // so a directory there, above or below one would hide it.+ if let Some(root) = reserved_mount_target(&target) {+ return Err(BoxliteError::InvalidArgument(format!(+ "mount target {target} is reserved for the container's own mount at {root}"+ )));+ }+ Ok(CheckedRequest {+ source: source.to_owned(),+ target,+ read_only: request.read_only,+ })+}++/// Open a directory without following a symbolic link in its final component,+/// and report where it really is.+fn open_source(source: &Path) -> BoxliteResult<(File, PathBuf)> {+ // A trailing slash or dot makes Linux follow the preceding component even+ // with O_NOFOLLOW. Strip that spelling while preserving `..` resolution.+ let directory = std::fs::OpenOptions::new()+ .read(true)+ .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)+ .open(source.components().as_path())+ .map_err(|error| match error.raw_os_error() {+ Some(libc::ENOENT) => {+ BoxliteError::NotFound(format!("source {} does not exist", source.display()))+ }+ Some(libc::ENOTDIR | libc::ELOOP) => BoxliteError::InvalidArgument(format!(+ "source {} is not a directory",+ source.display()+ )),+ _ => BoxliteError::Storage(format!("open source {}: {error}", source.display())),+ })?;+ // The descriptor names the directory the kernel opened, whichever way the+ // path spells it.+ let root = std::fs::canonicalize(format!("/proc/self/fd/{}", directory.as_raw_fd())).map_err(+ |error| BoxliteError::Storage(format!("resolve source {}: {error}", source.display())),+ )?;+ Ok((directory, root))+}++/// Refuse a target that already has a mount on any plane, one with a mount+/// below it, or one below a file the box was created with: a directory applied+/// last would cover that mount, and a file's mount leaves no path to mount at.+fn require_free(mounts: &Mounts, target: &str) -> BoxliteResult<()> {+ if mounts.occupied(target) {+ return Err(BoxliteError::InvalidState(format!(+ "a mount already exists at {target}"+ )));+ }+ if let Some(below) = mounts.below(target) {+ return Err(BoxliteError::InvalidState(format!(+ "a mount at {below} sits below {target} and would be covered"+ )));+ }+ if let Some(file) = mounts.files.iter().find(|file| path_is_below(target, file)) {+ return Err(BoxliteError::InvalidState(format!(+ "a file the box was created with is mounted at {file}; no directory can sit below it"+ )));+ }+ Ok(())+}++/// A target that has no mount to remove.+fn missing(target: &str) -> BoxliteError {+ BoxliteError::NotFound(format!("no mount at {target}"))+}++/// Whether the guest refused a step before it touched the container. The guest+/// reports each such refusal with its own code; anything else, a deadline+/// included, leaves the outcome unknown.+fn refusal(error: &BoxliteError) -> bool {+ matches!(+ error,+ BoxliteError::InvalidState(_)+ | BoxliteError::InvalidArgument(_)+ | BoxliteError::Unsupported(_)+ )+}++/// A failed shim exchange. Refusals keep their category; everything else is a+/// transport failure, whose outcome may be unknown.+fn shim_error(step: &str, error: io::Error) -> BoxliteError {+ let message = format!("{step}: {error}");+ match error.raw_os_error() {+ Some(libc::EBUSY) => BoxliteError::InvalidState(message),+ Some(libc::EINVAL) => BoxliteError::InvalidArgument(message),+ Some(libc::ENOSPC) => BoxliteError::ResourceExhausted(message),+ None => match error.kind() {+ io::ErrorKind::Unsupported => BoxliteError::Unsupported(message),+ io::ErrorKind::InvalidInput => BoxliteError::InvalidArgument(message),+ _ => BoxliteError::Storage(message),+ },+ _ => BoxliteError::Storage(message),+ }+}++/// The change's own error, plus what an unfinished cleanup leaves behind.+fn unconverged(error: BoxliteError, cleanup: BoxliteError) -> BoxliteError {+ match cleanup {+ stopped @ BoxliteError::Stopped(_) => stopped,+ cleanup => BoxliteError::InvalidState(format!(+ "{error}; removal is unconfirmed ({cleanup}), the record stays listed: retry remove"+ )),+ }+}++/// Run `work` against the store of box `id` on the blocking pool: the store+/// reads and writes SQLite, and its declarations name host paths.+async fn on_mount_store<T: Send + 'static>(+ store: &BoxStore,+ id: &str,+ work: impl FnOnce(&BoxStore, &str) -> BoxliteResult<T> + Send + 'static,+) -> BoxliteResult<T> {+ let (store, id) = (store.clone(), id.to_owned());+ tokio::task::spawn_blocking(move || work(&store, &id))+ .await+ .map_err(|error| BoxliteError::Internal(format!("mount store task: {error}")))?+}++/// Refuse a source that is, holds or lies inside the directory of another+/// mount on record. The next start delivers every declaration as its own+/// share, and refuses two shares whose roots overlap. The record at `target`+/// itself is left to the target's own check.+fn require_disjoint_source(+ mounts: &Mounts,+ target: &str,+ source: &str,+ root: &Path,+) -> BoxliteResult<()> {+ let on_record = mounts.declarations.iter().chain(+ mounts+ .progress+ .iter()+ .map(|(other, entry)| (other, &entry.request)),+ );+ for (other, request) in on_record {+ if other == target {+ continue;+ }+ // A source that cannot be resolved is named by the next start.+ let Ok(resolved) = request.source.canonicalize() else {+ continue;+ };+ if resolved.starts_with(root) || root.starts_with(&resolved) {+ return Err(BoxliteError::InvalidState(format!(+ "source {source} overlaps the directory mounted at {other}; a start could not \+ deliver both"+ )));+ }+ }+ Ok(())+}++impl BoxImpl {+ /// Admission shared by every mount operation: the `native-vmm`+ /// experimental opt-in and the native engine. Neither starts the box.+ fn require_runtime_mounts(&self) -> BoxliteResult<()> {+ self.runtime+ .experimental_features+ .require(ExperimentalFeature::NativeVmm)?;+ if self.config.engine_kind != VmmKind::Native {+ return Err(BoxliteError::Unsupported(format!(+ "runtime directory mounts need the native VMM; box {} runs {:?}",+ self.id(),+ self.config.engine_kind+ )));+ }+ Ok(())+ }++ /// Aggregate delivery needs a mount namespace the workload cannot modify.+ /// A stopped change follows the same admission: a declaration saved for a+ /// box that cannot deliver it could never take effect.+ fn require_aggregate_mounts(&self) -> BoxliteResult<()> {+ if self.config.options.advanced.permits_aggregate_mounts() {+ Ok(())+ } else {+ Err(BoxliteError::Unsupported(format!(+ "runtime directory mounts need a container without CAP_SYS_ADMIN; box {} keeps \+ its configured capabilities",+ self.id()+ )))+ }+ }++ /// Deliver a host directory into the container, or save it for the next+ /// start of a stopped box.+ pub(crate) async fn mount_add(&self, request: MountRequest) -> BoxliteResult<MountInfo> {+ self.require_runtime_mounts()?;+ self.require_aggregate_mounts()?;+ let request = checked_request(&request)?;+ // The host filesystem may sit on slow storage.+ let source = request.source.clone();+ let (directory, root) =+ tokio::task::spawn_blocking(move || open_source(Path::new(&source)))+ .await+ .map_err(|error| BoxliteError::Internal(format!("open source task: {error}")))??;+ self.mount_change(+ || self.add_while_stopped(&request, &root),+ |run| Self::add_while_running(run, request.clone(), directory, root.clone()),+ )+ .await+ }++ /// Remove the mount at `target`: a running box detaches it first, a+ /// stopped one only drops the declaration.+ pub(crate) async fn mount_remove(&self, target: &Path) -> BoxliteResult<()> {+ self.require_runtime_mounts()?;+ self.require_aggregate_mounts()?;+ let target = target_key(target)?;+ self.mount_change(+ || self.remove_while_stopped(&target),+ |run| Self::remove_while_running(run, target.clone()),+ )+ .await+ }++ /// Effective declarations and the current run's committed progress, from+ /// the store.+ pub(crate) async fn mount_list(&self) -> BoxliteResult<Vec<MountInfo>> {+ self.require_runtime_mounts()?;+ Ok(self.mounts().await?.visible())+ }++ /// The entry at `target`, or `None` when nothing is declared or in+ /// progress there.+ pub(crate) async fn mount_get(&self, target: &Path) -> BoxliteResult<Option<MountInfo>> {+ self.require_runtime_mounts()?;+ let target = target_key(target)?;+ Ok(self.mounts().await?.lookup(&target))+ }++ /// The declarations and progress from the store.+ async fn mounts(&self) -> BoxliteResult<Mounts> {+ on_mount_store(+ self.runtime.box_manager.store(),+ self.id().as_str(),+ |store, id| store.mounts(id),+ )+ .await+ }++ /// Run a change under the box's lifecycle lock, from the admission to the+ /// end: a stopped box commits under it, so a start cannot pass a write in+ /// flight, and a running one keeps its VM for the whole change.+ async fn mount_change<T, S, F, R>(+ &self,+ stopped: S,+ running: impl FnOnce(Running) -> R,+ ) -> BoxliteResult<T>+ where+ S: FnOnce() -> F,+ F: Future<Output = BoxliteResult<T>>,+ R: Future<Output = BoxliteResult<T>> + Send + 'static,+ T: Send + 'static,+ {+ let lock_id = self.state.read().lock_id.ok_or_else(|| {+ BoxliteError::Internal(format!("box {} is missing lock_id", self.id()))+ })?;+ let lifecycle =+ OwnedLockGuard::new_async(self.runtime.lock_manager.retrieve(lock_id)?).await;+ let current = self.refresh_state()?;+ match current.status {+ BoxStatus::Paused => Err(BoxliteError::InvalidState(format!(+ "Box {} is paused; its mounts stay in place until it resumes or stops",+ self.id()+ ))),+ BoxStatus::Running => {+ let Some(pid) = current.pid else {+ return Err(BoxliteError::Internal(format!(+ "box {} is running without a pid",+ self.id()+ )));+ };+ let run = self+ .running(+ lifecycle,+ BoxRun {+ pid,+ started_at: current.started_at,+ },+ )+ .await?;+ self.owned_mount(running(run)).await+ }+ BoxStatus::Configured | BoxStatus::Stopped | BoxStatus::Failed => stopped().await,+ status => Err(BoxliteError::InvalidState(format!(+ "Cannot change mounts of box {} while it is {status}",+ self.id()+ ))),+ }+ }++ /// The running VM of a change. The caller holds the box's lifecycle lock+ /// until the change ends, so no start or stop can replace the VM under it.+ async fn running(&self, lifecycle: OwnedLockGuard, run: BoxRun) -> BoxliteResult<Running> {+ if self.shutdown_token.is_cancelled() {+ return Err(BoxliteError::Stopped(+ "Mount cancelled during shutdown".into(),+ ));+ }+ // The guest mounts into the namespace of the container's init, so the+ // container runs first. The caller holds the lifecycle lock, so an+ // adopted VM is initialized under it.+ let live = self.existing_live_state_locked().await?;+ self.ensure_container_started(live).await?;+ let guest = live.guest_session.container().await?;+ Ok(Running {+ store: self.runtime.box_manager.store().clone(),+ id: self.id().clone(),+ run,+ control: self.layout.sockets().vmm_sock(),+ _lifecycle: lifecycle,+ guest,+ container_id: self.container_id().to_owned(),+ })+ }++ /// Save the declaration for the next start. The source only has to be a+ /// directory now: every delivery opens it again.+ async fn add_while_stopped(+ &self,+ request: &CheckedRequest,+ root: &Path,+ ) -> BoxliteResult<MountInfo> {+ let (source, target, root) = (+ request.source.clone(),+ request.target.clone(),+ root.to_owned(),+ );+ let stored = request.request();+ // The overlap check reads the store before the transaction: two stopped+ // adds that pass it together are named by the next start.+ on_mount_store(+ self.runtime.box_manager.store(),+ self.id().as_str(),+ move |store, id| {+ require_disjoint_source(&store.mounts(id)?, &target, &source, &root)?;+ store.update_mounts(id, |mounts| {+ require_free(mounts, &target)?;+ mounts.declare(stored);+ Ok(())+ })+ },+ )+ .await?;+ Ok(request.info(MountState::Configured))+ }++ /// Drop the declaration at `target`. The host source plays no part, so a+ /// declaration whose source is gone still goes.+ async fn remove_while_stopped(&self, target: &str) -> BoxliteResult<()> {+ let target = target.to_owned();+ on_mount_store(+ self.runtime.box_manager.store(),+ self.id().as_str(),+ move |store, id| {+ store.update_mounts(id, |mounts| {+ if !mounts.declarations.contains_key(&target) {+ return Err(missing(&target));+ }+ mounts.forget(&target);+ Ok(())+ })+ },+ )+ .await+ }++ /// Keep a running change running after its caller gives up: a cancelled+ /// add could leave the guest holding a mount the store does not know+ /// about. The box's own shutdown still ends it.+ async fn owned_mount<T: Send + 'static>(+ &self,+ operation: impl Future<Output = BoxliteResult<T>> + Send + 'static,+ ) -> BoxliteResult<T> {+ let shutdown = self.shutdown_token.clone();+ let task = tokio::spawn(async move {+ tokio::select! {+ biased;+ _ = shutdown.cancelled() => Err(BoxliteError::Stopped(+ "the box stopped during a mount operation".into(),+ )),+ result = operation => result,+ }+ });+ task.await.unwrap_or_else(|error| {+ Err(BoxliteError::Internal(format!(+ "mount operation failed: {error}"+ )))+ })+ }++ /// Deliver `directory` at the request's target in the admitted run.+ /// Succeeds only once the guest confirmed the mount and the declaration+ /// with its `Mounted` progress are committed.+ async fn add_while_running(+ mut run: Running,+ request: CheckedRequest,+ directory: File,+ root: PathBuf,+ ) -> BoxliteResult<MountInfo> {+ let target = request.target.clone();+ let stored = request.request();+ // The lifecycle lock is held, so every earlier add of this run has+ // committed its declaration.+ let (source, checked) = (request.source.clone(), target.clone());+ on_mount_store(&run.store, run.id.as_str(), move |store, id| {+ require_disjoint_source(&store.mounts(id)?, &checked, &source, &root)+ })+ .await?;+ let request_id: MountRequestId = uuid::Uuid::new_v4().into_bytes();+ // Reserve the target and publish `Preparing` before anything is registered.+ run.update(|mounts| {+ require_free(mounts, &target)?;+ mounts.progress.insert(+ target.clone(),+ MountProgress {+ request: stored.clone(),+ state: MountState::Preparing,+ request_id,+ export: None,+ delivered_at_start: false,+ },+ );+ Ok(())+ })?;+ let registered = run+ .control("register the directory", {+ let (target, source) = (target.clone(), request.source.clone());+ move |client| {+ client.register(source, target, directory, request.read_only, request_id)+ }+ })+ .await;+ let export = match registered {+ Ok(record) => record.export,+ // A transport failure can hide either a registration or a refusal.+ // Only this request's ID finds a registration whose reply was lost.+ Err(error @ (BoxliteError::Storage(_) | BoxliteError::Internal(_))) => {+ match run.registered_export(request_id).await {+ Ok(Some(export)) => export,+ // Nothing was registered, so nothing is mounted.+ Ok(None) => return Err(run.settle(&target, request_id, error)),+ // The shim cannot say: the entry stays listed for a remove.+ Err(_) => return Err(error),+ }+ }+ // The run ended; the entry ends with it.+ Err(error @ BoxliteError::Stopped(_)) => return Err(error),+ // Refused, so nothing was registered: an invalid source or target,+ // a repeated request, or a full record list.+ Err(error) => return Err(run.settle(&target, request_id, error)),+ };++ if let Err(error) = run.mount(&export, &target, request.read_only).await {+ // A refusal means the guest refused before touching the container,+ // so nothing needs detaching. Any other outcome is unknown: the+ // guest may have mounted without reporting it.+ let detach = !refusal(&error);+ return Err(run.undo(&target, request_id, &export, error, detach).await);+ }+ let committed = run.update(|mounts| {+ // Another request's entry, a removed one, or one a removal is+ // detaching means the mount is no longer the add's.+ let entry = owned(mounts, &target, request_id)+ .filter(|entry| entry.state == MountState::Preparing)+ .ok_or_else(|| {+ BoxliteError::InvalidState(format!(+ "the mount at {target} was removed while being added"+ ))+ })?;+ entry.state = MountState::Mounted;+ entry.export = Some(export.clone());+ mounts.declare(stored);+ Ok(())+ });+ match committed {+ Ok(()) => Ok(request.info(MountState::Mounted)),+ // The guest holds a mount that is not on record. Only undoing it+ // keeps the store truthful.+ Err(stopped @ BoxliteError::Stopped(_)) => Err(stopped),+ Err(error) => Err(run.undo(&target, request_id, &export, error, true).await),+ }+ }++ /// Remove this run's mount at `target`: detach its identity in the guest,+ /// retire its export, then commit the removal of the declaration.+ async fn remove_while_running(mut run: Running, target: String) -> BoxliteResult<()> {+ // Refuse what could not be detached, then publish `Detaching`, both+ // before anything changes in the guest.+ let (request_id, named, delivered, found) = run.update(|mounts| {+ // A mount below the target would leave the container with it.+ if let Some(below) = mounts.below(&target) {+ return Err(BoxliteError::InvalidState(format!(+ "remove the mount at {below} first; one the box was created with needs a stop"+ )));+ }+ let entry = mounts.progress.get_mut(&target).ok_or_else(|| {+ if mounts.declarations.contains_key(&target) {+ BoxliteError::InvalidState(format!(+ "the mount at {target} has no committed identity in this VM run; stop the box before removing its declaration"+ ))+ } else {+ missing(&target)+ }+ })?;+ let delivered = entry.delivered_at_start;+ let found = entry.state;+ entry.state = MountState::Detaching;+ Ok((entry.request_id, entry.export.clone(), delivered, found))+ })?;+ let (key, exported) = match named {+ Some(export) => (export, true),+ None if delivered => (uuid::Uuid::from_bytes(request_id).to_string(), false),+ // An add whose export was never committed: its registration names it.+ None => match run.registered_export(request_id).await? {+ Some(export) => (export, true),+ // Nothing was registered, so nothing is mounted.+ None => return run.end(&target, request_id),+ },+ };+ if let Err(error) = run.detach(&key, &target).await {+ return Err(run.refused(&target, request_id, found, error));+ }+ if exported {+ run.retire(&key).await?;+ }+ run.end(&target, request_id)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::litebox::mounts::tests::Fixture;+ use crate::litebox::state::{BoxState, BoxStatus};+ use tonic::transport::Endpoint;++ const WORK: &str = "/work";++ /// A change on a running box whose shim and guest are never reached.+ async fn running(fx: &Fixture, state: &BoxState) -> Running {+ let endpoint = Endpoint::from_shared("http://127.0.0.1:1")+ .unwrap()+ .connect_lazy();+ Running {+ store: fx.runtime.box_manager.store().clone(),+ id: fx.id.clone(),+ run: BoxRun {+ pid: state.pid.expect("the fixture gives a running box a pid"),+ started_at: state.started_at,+ },+ control: PathBuf::new(),+ guest: ContainerInterface::new(endpoint),+ container_id: fx.config.container.id.to_string(),+ _lifecycle: OwnedLockGuard::new_async(+ fx.runtime+ .lock_manager+ .retrieve(state.lock_id.unwrap())+ .unwrap(),+ )+ .await,+ }+ }++ #[tokio::test]+ async fn a_refused_removal_leaves_the_entry_as_it_found_it() {+ let fx = Fixture::new(BoxStatus::Running);+ let state = fx.runtime.box_manager.update_box(&fx.id).unwrap();+ let store = fx.runtime.box_manager.store().clone();+ // An add interrupted before its commit, then a committed mount.+ for (found, left) in [+ (MountState::Preparing, MountState::Preparing),+ (MountState::Mounted, MountState::Mounted),+ ] {+ let request_id: MountRequestId = [7; 16];+ store+ .update_mounts(fx.id.as_str(), |mounts| {+ mounts.progress.insert(+ WORK.into(),+ MountProgress {+ request: fx.request(),+ state: found,+ request_id,+ export: None,+ delivered_at_start: false,+ },+ );+ Ok(())+ })+ .unwrap();+ let run = running(&fx, &state).await;+ let refused = run.refused(+ WORK,+ request_id,+ found,+ BoxliteError::InvalidState("detach descendant mounts first".into()),+ );+ drop(run);++ assert!(+ matches!(refused, BoxliteError::InvalidState(_)),+ "the caller still reports the refusal: {refused}"+ );+ assert_eq!(+ store.mounts(fx.id.as_str()).unwrap().progress[WORK].state,+ left,+ "an entry the removal found {found:?}"+ );+ }+ }+}diff --git a/src/boxlite/src/litebox/box_impl/operations.rs b/src/boxlite/src/litebox/box_impl/operations.rsindex 61086d379..d8f7a69b6 100644--- a/src/boxlite/src/litebox/box_impl/operations.rs+++ b/src/boxlite/src/litebox/box_impl/operations.rs@@ -35,6 +35,14 @@ impl BoxImpl {})?;let locker = self.runtime.lock_manager.retrieve(lock_id)?;let _guard = LockGuard::new_async(locker.as_ref()).await;+ self.refresh_state()?;+ operation.await+ }++ /// Bring this handle's state in line with the persisted one. The caller+ /// holds the box's lifecycle lock, so nothing can move the lifecycle on+ /// between this read and the operation that follows it.+ pub(super) fn refresh_state(&self) -> BoxliteResult<crate::runtime::types::BoxState> {let current = self.runtime.box_manager.update_box(self.id())?;{let mut state = self.state.write();@@ -48,9 +56,9 @@ impl BoxImpl {"Box handle belongs to an earlier VM; use runtime.get()".into(),));}- *state = current;+ *state = current.clone();}- operation.await+ Ok(current)}pub(crate) fn try_with_operation<F, R>(diff --git a/src/boxlite/src/litebox/clone_export.rs b/src/boxlite/src/litebox/clone_export.rsindex 921ba027d..54517b2d0 100644--- a/src/boxlite/src/litebox/clone_export.rs+++ b/src/boxlite/src/litebox/clone_export.rs@@ -16,14 +16,31 @@ use crate::runtime::types::BoxStatus;// ============================================================================impl BoxImpl {- fn options_for_copy(&self) -> BoxliteResult<crate::runtime::options::BoxOptions> {+ /// The options a copy of this box boots with: the ones it was created+ /// with, the state's overrides, and its committed mount changes. The store+ /// reads SQLite and the host filesystem.+ async fn options_for_copy(&self) -> BoxliteResult<crate::runtime::options::BoxOptions> {+ let runtime = Arc::clone(&self.runtime);+ let id = self.id().clone();let mut options = self.config.options.clone();- let state = self.runtime.box_manager.update_box(self.id())?;- options.disk_size_gb = state.disk_size_gb.or(options.disk_size_gb);- if let Some(policy) = state.outbound_policy {- options.network = policy.try_into()?;- }- Ok(options)+ let native = self.config.engine_kind == crate::vmm::VmmKind::Native;+ tokio::task::spawn_blocking(move || {+ let state = runtime.box_manager.update_box(&id)?;+ options.disk_size_gb = state.disk_size_gb.or(options.disk_size_gb);+ if let Some(policy) = state.outbound_policy {+ options.network = policy.try_into()?;+ }+ if native {+ runtime+ .box_manager+ .store()+ .mounts(id.as_str())?+ .apply_to_boot(&mut options);+ }+ Ok(options)+ })+ .await+ .map_err(|error| BoxliteError::Internal(format!("copy options task: {error}")))?}pub(crate) async fn clone_box(@@ -103,6 +120,10 @@ impl BoxImpl {// Read virtual size from the shared base for overlay creation.let container_vsize = Qcow2Helper::qcow2_virtual_size(&shared_container)?;+ // Before any staging directory exists: once one does, a caller that+ // gives up must still get its clone, so nothing may await between+ // staging and provisioning.+ let copy_options = self.options_for_copy().await?;// Phase B: Create N container overlay headers (VM is resumed, fast).// Guest rootfs is NOT cloned — each clone creates its own on first start.@@ -134,7 +155,6 @@ impl BoxImpl {// Each clone's disk is a copy of this one, so it runs the same build.// 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);for (i, staging) in staging_dirs.into_iter().enumerate() {// Keep the TempDir alive until provisioning moves it to the final box home.@@ -223,7 +243,7 @@ impl BoxImpl {// Phase 2: Checksum + manifest + archive run with VM resumed.// These only read static temp files, no disk consistency needed.let config_name = self.config.name.clone();- let config_options = self.options_for_copy()?;+ let config_options = self.options_for_copy().await?;let box_id_str = self.id().to_string();let dest = dest.to_path_buf();@@ -360,3 +380,55 @@ fn do_export_finalize(Ok(crate::runtime::options::BoxArchive::new(output_path))}++#[cfg(all(test, feature = "native", target_os = "linux", target_arch = "x86_64"))]+mod tests {+ use crate::litebox::mounts::MountRequest;+ use crate::litebox::mounts::tests::Fixture;+ use crate::litebox::state::BoxStatus;+ use crate::runtime::options::MountSpec;++ #[tokio::test]+ async fn a_copy_boots_with_the_mounts_the_box_boots_with() {+ let (orig, added) = (+ tempfile::tempdir_in("/tmp").unwrap(),+ tempfile::tempdir_in("/tmp").unwrap(),+ );+ let fx = Fixture::with_mounts(+ BoxStatus::Stopped,+ vec![MountSpec::bind_mount(+ orig.path().to_str().unwrap(),+ "/orig",+ )],+ );+ let bx = fx.handle();+ fx.runtime+ .box_manager+ .store()+ .update_mounts(fx.id.as_str(), |mounts| {+ mounts.forget("/orig");+ mounts.declare(MountRequest {+ source: added.path().into(),+ target: "/added".into(),+ read_only: true,+ });+ Ok(())+ })+ .unwrap();++ let copied = bx.options_for_copy().await.unwrap();+ assert_eq!(+ copied+ .mounts+ .iter()+ .map(|mount| mount.target.as_str())+ .collect::<Vec<_>>(),+ ["/added"]+ );+ assert_eq!(+ bx.config.options.mounts.len(),+ 1,+ "the box's own configuration stays as created"+ );+ }+}diff --git a/src/boxlite/src/litebox/init/mod.rs b/src/boxlite/src/litebox/init/mod.rsindex 9cb5aa1d2..e35e33a10 100644--- a/src/boxlite/src/litebox/init/mod.rs+++ b/src/boxlite/src/litebox/init/mod.rs@@ -49,6 +49,8 @@ pub(crate) struct BuiltBox {/// Present when this build made a new disk from a registry image; see/// [`crate::litebox::state::BoxState::resolved_image`].pub(crate) resolved_image: Option<crate::images::ResolvedImage>,+ /// The directory mounts a new VM confirmed at start.+ pub(crate) mounts: std::collections::BTreeMap<String, crate::litebox::mounts::MountProgress>,}use crate::litebox::BoxStatus;@@ -232,13 +234,24 @@ impl BoxBuilder {let BoxBuilder {runtime,- config,+ mut config,state,} = self;let status = state.status;let reuse_rootfs = status == BoxStatus::Stopped;let skip_guest_wait = status == BoxStatus::Running;+ // A new VM boots under the effective directory declarations. They are+ // read here, under the lifecycle admission of this start, and every+ // task of the pipeline then sees the same options.+ let declared =+ if status != BoxStatus::Running && config.engine_kind == crate::vmm::VmmKind::Native {+ let declared = runtime.box_manager.store().mounts(config.id.as_str())?;+ declared.apply_to_boot(&mut config.options);+ Some(declared)+ } else {+ None+ };let mut ctx = InitPipelineContext::new(config,@@ -247,6 +260,7 @@ impl BoxBuilder {skip_guest_wait,state.resolved_image.clone(),);+ ctx.declared = declared;if status == BoxStatus::Running {// Adoption borrows an existing VM; a reconnect failure must not stop it// or replace its Running state with an initialization failure.@@ -337,6 +351,7 @@ impl BoxBuilder {live: live_state,guard,resolved_image: ctx.resolved_image.take(),+ mounts: std::mem::take(&mut ctx.confirmed),})};diff --git a/src/boxlite/src/litebox/init/tasks/guest_init.rs b/src/boxlite/src/litebox/init/tasks/guest_init.rsindex 8d7fec3fc..b01c3f6fd 100644--- a/src/boxlite/src/litebox/init/tasks/guest_init.rs+++ b/src/boxlite/src/litebox/init/tasks/guest_init.rs@@ -122,11 +122,16 @@ impl PipelineTask<InitCtx> for GuestInitTask {)};- run_guest_init(guest_session.clone(), bootstrap)+ let records = run_guest_init(guest_session.clone(), bootstrap).await.inspect_err(|e| log_task_error(&box_id, task_name, e))?;let mut ctx = ctx.lock().await;+ if !records {+ // The guest got plain binds, so no directory of this run has an+ // identity an online removal could select.+ ctx.confirmed.clear();+ }ctx.guest_session = Some(guest_session);ctx.volume_mgr = Some(volume_mgr);ctx.rootfs_init = Some(rootfs_init);@@ -149,11 +154,25 @@ fn requires_safe_volume_sub_path(mounts: &[crate::volumes::ContainerMount]) -> b})}+/// Deliver each declared directory as the plain bind it was created as: the+/// guest cannot record it, so an online removal cannot select it.+fn unrecord(mounts: &mut [crate::volumes::ContainerMount]) {+ for mount in mounts {+ if matches!(+ mount.payload,+ crate::volumes::ContainerMountPayload::RecordedDirectory { .. }+ ) {+ mount.payload = crate::volumes::ContainerMountPayload::WholeDirectory;+ }+ }+}+/// Initialize the guest and create the container (init is *not* run here).+/// Returns whether the guest records the mounts of declared directories.async fn run_guest_init(guest_session: GuestSession,- bootstrap: GuestBootstrapConfig,-) -> BoxliteResult<()> {+ mut bootstrap: GuestBootstrapConfig,+) -> BoxliteResult<bool> {// Step 1: Guest Init (volumes + network)tracing::info!("Sending guest initialization request");let mut guest_interface = guest_session.guest().await?;@@ -181,6 +200,43 @@ async fn run_guest_init(if requires_safe_volume_sub_path(&bootstrap.container.mounts) {guest_interface.require_safe_volume_sub_path().await?;}+ // The guest records the mounts of declared directories while it creates+ // the container, which is what lets an online removal select them.+ let recorded = |mount: &crate::volumes::ContainerMount| {+ matches!(+ mount.payload,+ crate::volumes::ContainerMountPayload::RecordedDirectory { .. }+ )+ };+ let records = if !bootstrap.container.mounts.iter().any(recorded) {+ true+ } else {+ match guest_interface.require_boot_mount_records().await {+ Ok(()) => true,+ // Only a guest without the capability gets plain binds. Any other+ // failure is reported, so a retry keeps the records.+ Err(error) if !matches!(error, BoxliteError::Unsupported(_)) => return Err(error),+ Err(error) => {+ // A directory added at runtime needs its record.+ let added = |mount: &crate::volumes::ContainerMount| {+ matches!(+ mount.payload,+ crate::volumes::ContainerMountPayload::RecordedDirectory {+ added: true,+ ..+ }+ )+ };+ if bootstrap.container.mounts.iter().any(added) {+ return Err(error);+ }+ // One created with the box keeps its plain delivery instead: it+ // then leaves only with the box.+ unrecord(&mut bootstrap.container.mounts);+ false+ }+ }+ };guest_interface.init(bootstrap.guest).await?;tracing::info!("Guest initialized successfully");@@ -195,7 +251,7 @@ async fn run_guest_init(// left standing at the gate; the host runs it with `Container.Start` after a// client has attached, so nothing it prints can be missed however fast it is.- Ok(())+ Ok(records)}/// The box limits the container reads in its cgroup, from the values the VM@@ -304,8 +360,10 @@ mod tests {struct VersionedGuest {version: &'static str,safe_managed_volume_sub_path: bool,+ records_boot_mounts: bool,guest_init_calls: Arc<std::sync::Mutex<usize>>,container_init_calls: Arc<std::sync::Mutex<usize>>,+ container_mounts: Arc<std::sync::Mutex<Vec<boxlite_shared::BindMount>>>,}#[tonic::async_trait]@@ -329,6 +387,7 @@ mod tests {Ok(tonic::Response::new(boxlite_shared::PingResponse {version: self.version.to_string(),safe_managed_volume_sub_path: self.safe_managed_volume_sub_path,+ records_boot_mounts: self.records_boot_mounts,}))}@@ -380,7 +439,9 @@ mod tests {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;+ let request = request.into_inner();+ *self.container_mounts.lock().unwrap() = request.mounts;+ let container_id = request.container_id;Ok(tonic::Response::new(boxlite_shared::ContainerInitResponse {result: Some(boxlite_shared::container_init_response::Result::Success(@@ -444,18 +505,22 @@ mod tests {}}- 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 {+ fn guest_that(version: &'static str, safe_managed_volume_sub_path: bool) -> VersionedGuest {+ VersionedGuest {version,safe_managed_volume_sub_path,- guest_init_calls: Arc::clone(&guest_init_calls),- container_init_calls: Arc::clone(&container_init_calls),- };+ records_boot_mounts: true,+ guest_init_calls: Arc::new(std::sync::Mutex::new(0)),+ container_init_calls: Arc::new(std::sync::Mutex::new(0)),+ container_mounts: Arc::new(std::sync::Mutex::new(Vec::new())),+ }+ }++ async fn run_with_guest(+ guest: VersionedGuest,+ bootstrap: GuestBootstrapConfig,+ ) -> (BoxliteResult<bool>, VersionedGuest) {+ let served = guest.clone();let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();let addr = listener.local_addr().unwrap();drop(listener);@@ -476,12 +541,23 @@ mod tests {let result = run_guest_init(crate::portal::GuestSession::new(boxlite_shared::BoxTransport::tcp(addr.port())),- bootstrap_for_version_gate(),+ bootstrap,).await;- let guest_calls = *guest_init_calls.lock().unwrap();- let container_calls = *container_init_calls.lock().unwrap();- (result, guest_calls, container_calls)+ (result, served)+ }++ async fn run_with_guest_version(+ version: &'static str,+ safe_managed_volume_sub_path: bool,+ ) -> (BoxliteResult<bool>, usize, usize) {+ let guest = guest_that(version, safe_managed_volume_sub_path);+ let (result, guest) = run_with_guest(guest, bootstrap_for_version_gate()).await;+ let calls = (+ *guest.guest_init_calls.lock().unwrap(),+ *guest.container_init_calls.lock().unwrap(),+ );+ (result, calls.0, calls.1)}#[tokio::test(flavor = "multi_thread", worker_threads = 2)]@@ -494,4 +570,59 @@ mod tests {result.unwrap();assert_eq!((guest_calls, container_calls), (1, 1));}++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn only_a_directory_added_at_runtime_needs_a_guest_that_records_mounts() {+ let recorded = |added| 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::RecordedDirectory {+ key: "delivery-1".to_string(),+ added,+ },+ };+ let mut creation = bootstrap_for_version_gate();+ creation.container.mounts = vec![recorded(false)];+ let mut added = bootstrap_for_version_gate();+ added.container.mounts = vec![recorded(true)];++ // A directory created with the box is delivered as the plain bind it is.+ let silent = || {+ let mut guest = guest_that("0.15.0", false);+ guest.records_boot_mounts = false;+ guest+ };+ let (result, served) = run_with_guest(silent(), creation).await;+ assert!(!result.unwrap());+ assert_eq!(+ (+ *served.guest_init_calls.lock().unwrap(),+ *served.container_init_calls.lock().unwrap()+ ),+ (1, 1)+ );+ assert!(+ served+ .container_mounts+ .lock()+ .unwrap()+ .iter()+ .all(|mount| mount.record_key.is_empty()),+ "a directory created with the box reached the guest as a recorded mount"+ );++ // One added at runtime has no identity without its record.+ let (result, served) = run_with_guest(silent(), added).await;+ assert!(matches!(result, Err(BoxliteError::Unsupported(_))));+ assert_eq!(+ (+ *served.guest_init_calls.lock().unwrap(),+ *served.container_init_calls.lock().unwrap()+ ),+ (0, 0)+ );+ }}diff --git a/src/boxlite/src/litebox/init/tasks/vmm_spawn.rs b/src/boxlite/src/litebox/init/tasks/vmm_spawn.rsindex 645580f5a..5f1dc7174 100644--- a/src/boxlite/src/litebox/init/tasks/vmm_spawn.rs+++ b/src/boxlite/src/litebox/init/tasks/vmm_spawn.rs@@ -87,15 +87,15 @@ impl PipelineTask<InitCtx> for VmmSpawnTask {let task_name = self.name();let box_id = task_start(&ctx, task_name).await;- // Gather all inputs from previous tasks- let inputs = {- let ctx = ctx.lock().await;- VmmSpawnInputs::from_context(&ctx)?+ // Gather all inputs from previous tasks, and the declared directories of this start+ let (inputs, declared) = {+ let mut ctx = ctx.lock().await;+ (VmmSpawnInputs::from_context(&ctx)?, ctx.declared.take())};// Build config and get outputs- let (instance_spec, volume_mgr, rootfs_init, container_mounts, network_backend) =- build_config(&box_id, &inputs)+ let (instance_spec, volume_mgr, rootfs_init, container_mounts, network_backend, confirmed) =+ build_config(&box_id, &inputs, declared).await.inspect_err(|e| log_task_error(&box_id, task_name, e))?;@@ -109,6 +109,8 @@ impl PipelineTask<InitCtx> for VmmSpawnTask {ctx.volume_mgr = Some(volume_mgr);ctx.rootfs_init = Some(rootfs_init);ctx.container_mounts = Some(container_mounts);+ // What the guest records for the declared directories, published once the box is up.+ ctx.confirmed = confirmed;// Hand the box's one network backend to LiveState assembly (init/mod.rs).ctx.network_backend = network_backend;// Store CA cert PEM for Container.Init gRPC (passed as CACert proto field)@@ -128,12 +130,14 @@ impl PipelineTask<InitCtx> for VmmSpawnTask {async fn build_config(box_id: &BoxID,inputs: &VmmSpawnInputs,+ declared: Option<crate::db::Mounts>,) -> BoxliteResult<(InstanceSpec,GuestVolumeManager,crate::portal::interfaces::ContainerRootfsInitConfig,Vec<ContainerMount>,Option<Box<dyn NetworkBackend>>,+ std::collections::BTreeMap<String, crate::litebox::mounts::MountProgress>,)> {let VmmSpawnInputs {outbound_policy,@@ -154,14 +158,20 @@ async fn build_config(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 || {+ // Declared sources are checked before the resolver runs: it would mount a+ // file where a declared directory used to be, or fail without naming the+ // target. Both read the host filesystem, and the resolution takes+ // filesystem locks, so keep them off Tokio's async worker threads.+ let (declared, user_volumes) = tokio::task::spawn_blocking(move || {+ if let Some(declared) = &declared {+ declared.check_sources()?;+ }resolve_user_volumes(&volume_options.volumes,&volume_options.mounts,&local_volume_store,)+ .map(|volumes| (declared, volumes))}).await.map_err(|error| BoxliteError::Internal(format!("volume resolution task failed: {error}")))??;@@ -245,7 +255,11 @@ async fn build_config(payload,);}- let container_mounts = container_mgr.build_container_mounts();+ let mut container_mounts = container_mgr.build_container_mounts();+ let confirmed = declared+ .as_ref()+ .map(|declared| declared.record(&mut container_mounts, &options.advanced))+ .unwrap_or_default();// Get guest rootfs from runtime cache and configure with disklet guest_rootfs = runtime@@ -321,6 +335,7 @@ async fn build_config(rootfs_init,container_mounts,network_backend,+ confirmed,))}diff --git a/src/boxlite/src/litebox/init/types.rs b/src/boxlite/src/litebox/init/types.rsindex 5bdb6fc7d..7e5b9b405 100644--- a/src/boxlite/src/litebox/init/types.rs+++ b/src/boxlite/src/litebox/init/types.rs@@ -425,6 +425,11 @@ pub struct InitPipelineContext {pub volume_mgr: Option<GuestVolumeManager>,pub rootfs_init: Option<ContainerRootfsInitConfig>,pub container_mounts: Option<Vec<ContainerMount>>,+ /// The effective directory declarations of a new VM, read under the+ /// lifecycle admission of its start.+ pub declared: Option<crate::db::Mounts>,+ /// The mounts a new VM confirmed at start, published with its live state.+ pub confirmed: std::collections::BTreeMap<String, crate::litebox::mounts::MountProgress>,pub guest_session: Option<GuestSession>,/// The box's one network backend (set by vmm_spawn on first start/restart, or/// by vmm_attach on reattach; moved into LiveState for runtime control).@@ -466,6 +471,8 @@ impl InitPipelineContext {volume_mgr: None,rootfs_init: None,container_mounts: None,+ declared: None,+ confirmed: std::collections::BTreeMap::new(),guest_session: None,network_backend: None,published_ports: None,diff --git a/src/boxlite/src/litebox/manager.rs b/src/boxlite/src/litebox/manager.rsindex 47fc2a24e..e4f8d2ae1 100644--- a/src/boxlite/src/litebox/manager.rs+++ b/src/boxlite/src/litebox/manager.rs@@ -35,7 +35,6 @@ impl BoxManager {}}- #[cfg(test)]pub(crate) fn store(&self) -> &BoxStore {&self.store}diff --git a/src/boxlite/src/litebox/mod.rs b/src/boxlite/src/litebox/mod.rsindex 2fd87f44a..7a2e4d709 100644--- a/src/boxlite/src/litebox/mod.rs+++ b/src/boxlite/src/litebox/mod.rs@@ -14,6 +14,7 @@ mod executions;mod init;pub(crate) mod local_snapshot;mod manager;+pub(crate) mod mounts;mod network;pub(crate) mod ports;mod resize;@@ -32,6 +33,7 @@ pub use exec::{};pub use executions::ExecutionsHandle;pub(crate) use manager::BoxManager;+pub use mounts::{MountHandle, MountInfo, MountRequest, MountState};pub use network::{BoxConnection, BoxReader, BoxTunnel, BoxWriter, NetworkHandle, SocketAddress, TunnelForwarder,TunnelOptions,@@ -141,6 +143,11 @@ impl LiteBox {ExecutionsHandle::new(Arc::clone(&self.box_backend))}+ /// Manage persistent host directories without starting the box. See [`MountHandle`].+ pub fn mount(&self) -> MountHandle {+ MountHandle::new(Arc::clone(&self.box_backend))+ }+/// Attach to a session in the box.////// [`AttachOptions::main`] follows the box's main command session (`rundiff --git a/src/boxlite/src/litebox/mounts.rs b/src/boxlite/src/litebox/mounts.rsnew file mode 100644index 000000000..768d96445--- /dev/null+++ b/src/boxlite/src/litebox/mounts.rs@@ -0,0 +1,145 @@+//! Persistent host directory mounts for local Linux x86_64 native boxes.+//!+//! SQLite holds the declarations a box boots with and the last committed+//! progress of its current VM. A running change also coordinates a shim export+//! with a guest mount. Mount operations require the `native-vmm` experimental+//! feature.+//!+//! Only the native engine changes mounts; other builds carry the public types.+#![cfg_attr(+ not(all(feature = "native", target_os = "linux", target_arch = "x86_64")),+ allow(dead_code)+)]++use std::fmt;+use std::path::{Path, PathBuf};+use std::sync::Arc;++use boxlite_shared::constants::normalize_target;+use boxlite_shared::errors::{BoxliteError, BoxliteResult};++use serde::{Deserialize, Serialize};++use crate::runtime::backend::BoxBackend;+#[cfg(all(test, feature = "native", target_os = "linux", target_arch = "x86_64"))]+pub(crate) mod tests;++/// A host directory and its destination in the container.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct MountRequest {+ /// Host directory to deliver. A symbolic link is refused at open.+ pub source: PathBuf,+ /// Absolute container path below `/`, without `..`. Missing directories+ /// are created; a path that has entries, or one reached through a symbolic+ /// link, is refused.+ pub target: PathBuf,+ /// Whether the container sees the directory read-only.+ pub read_only: bool,+}++/// Last committed state of a directory mount.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub enum MountState {+ /// Saved for delivery when the box starts.+ Configured,+ /// Reserved for delivery in the current VM run.+ Preparing,+ /// Visible in the container at the target path.+ Mounted,+ /// Removal is incomplete; repeating the removal finishes it.+ Detaching,+}++/// A mount as callers see it. The identities the shim and the guest record stay internal.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct MountInfo {+ /// Host directory the content comes from.+ pub source: PathBuf,+ /// Container path the directory is visible at.+ pub target: PathBuf,+ /// Whether the container sees the directory read-only.+ pub read_only: bool,+ /// Where the mount is in its lifecycle.+ pub state: MountState,+}++/// Last committed progress of one mount in one VM run.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub(crate) struct MountProgress {+ pub request: MountRequest,+ pub state: MountState,+ /// The request that owns the entry. A step of any other request leaves it alone.+ pub request_id: [u8; 16],+ /// The shim export of a runtime add, once its registration replied.+ pub export: Option<String>,+ /// Whether a start delivered the mount. The guest then recorded it under+ /// `request_id`, and the shim holds no export for it.+ pub delivered_at_start: bool,+}++impl MountRequest {+ /// The request as callers see it in `state`.+ pub(crate) fn info(&self, state: MountState) -> MountInfo {+ MountInfo {+ source: self.source.clone(),+ target: self.target.clone(),+ read_only: self.read_only,+ state,+ }+ }+}++/// A caller's target, checked and normalized.+pub(crate) fn target_key(target: &Path) -> BoxliteResult<String> {+ let target = target.to_str().ok_or_else(|| {+ BoxliteError::InvalidArgument(format!("mount target must be valid UTF-8: {target:?}"))+ })?;+ normalize_target(target).ok_or_else(|| {+ BoxliteError::InvalidArgument(format!(+ "mount target must be an absolute path below `/`, without `..`: {target:?}"+ ))+ })+}++/// Persistent directory mounts of a box, reached through [`LiteBox::mount`](super::LiteBox::mount).+#[derive(Clone)]+pub struct MountHandle {+ backend: Arc<dyn BoxBackend>,+}++impl fmt::Debug for MountHandle {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("MountHandle")+ .field("box_id", self.backend.id())+ .finish()+ }+}++impl MountHandle {+ /// Retain the backend without starting it; the backend decides support.+ pub(super) fn new(backend: Arc<dyn BoxBackend>) -> Self {+ Self { backend }+ }++ /// Save a directory declaration. A stopped box returns [`MountState::Configured`].+ /// A running box returns [`MountState::Mounted`] after guest confirmation and commit.+ pub async fn add(&self, request: MountRequest) -> BoxliteResult<MountInfo> {+ self.backend.mount_add(request).await+ }++ /// Remove the declaration at `target`. On a running box the guest detaches the+ /// mount lazily, preserving open descriptors. A missing target returns `NotFound`.+ pub async fn remove(&self, target: impl AsRef<Path>) -> BoxliteResult<()> {+ self.backend.mount_remove(target.as_ref()).await+ }++ /// Read effective declarations and current delivery progress from the store.+ pub async fn list(&self) -> BoxliteResult<Vec<MountInfo>> {+ self.backend.mount_list().await+ }++ /// Read the latest committed entry at `target`, or `None` if it is absent.+ pub async fn get(&self, target: impl AsRef<Path>) -> BoxliteResult<Option<MountInfo>> {+ self.backend.mount_get(target.as_ref()).await+ }+}diff --git a/src/boxlite/src/litebox/mounts/tests.rs b/src/boxlite/src/litebox/mounts/tests.rsnew file mode 100644index 000000000..0980b6a82--- /dev/null+++ b/src/boxlite/src/litebox/mounts/tests.rs@@ -0,0 +1,371 @@+//! OpenSpec PR-3: stopped changes against real admission and SQLite. The+//! running paths are verified on KVM in `tests/runtime_mounts.rs`.++use std::path::{Path, PathBuf};++use boxlite_shared::errors::BoxliteError;+use chrono::Utc;++use crate::BoxID;+use crate::db::{BoxStore, Database, Mounts};+use crate::experimental::ExperimentalFeatures;+use crate::litebox::box_impl::BoxImpl;+use crate::litebox::config::{BoxConfig, ContainerRuntimeConfig};+use crate::litebox::state::{BoxState, BoxStatus};+use crate::runtime::id::BoxIDMint;+use crate::runtime::options::{BoxOptions, BoxliteOptions, MountSpec, RootfsSpec};+use crate::runtime::rt_impl::{RuntimeImpl, SharedRuntimeImpl};+use crate::runtime::types::ContainerID;+use crate::vmm::VmmKind;++use super::{MountRequest, MountState};++const WORK: &str = "/work";++pub(crate) struct Fixture {+ /// Keeps the runtime's home alive.+ _home: tempfile::TempDir,+ pub(crate) runtime: SharedRuntimeImpl,+ pub(crate) id: BoxID,+ pub(crate) config: BoxConfig,+ pub(crate) source: PathBuf,+}++impl Fixture {+ pub(crate) fn new(status: BoxStatus) -> Self {+ Self::with_mounts(status, Vec::new())+ }++ /// A native box with its locks allocated, created with `mounts`.+ pub(crate) fn with_mounts(status: BoxStatus, mounts: Vec<MountSpec>) -> Self {+ let home = tempfile::tempdir_in("/tmp").unwrap();+ let runtime = RuntimeImpl::new_for_test_with_features(+ BoxliteOptions {+ home_dir: home.path().into(),+ image_registries: vec![],+ ..Default::default()+ },+ ExperimentalFeatures::parse("native-vmm").unwrap(),+ )+ .unwrap();+ let source = home.path().join("data");+ std::fs::create_dir(&source).unwrap();+ let lock_id = runtime.lock_manager.allocate().unwrap();+ runtime+ .disk_lock_manager+ .allocate_and_retrieve(lock_id)+ .unwrap();+ let mut state = BoxState::new();+ state.set_lock_id(lock_id);+ state.status = status;+ if matches!(status, BoxStatus::Paused | BoxStatus::Running) {+ state.set_pid(Some(4242));+ }+ let id = BoxIDMint::mint();+ let config = BoxConfig {+ id: id.clone(),+ name: None,+ created_at: Utc::now(),+ container: ContainerRuntimeConfig {+ id: ContainerID::new(),+ },+ options: BoxOptions {+ rootfs: RootfsSpec::Image("alpine:latest".into()),+ mounts,+ ..Default::default()+ },+ engine_kind: VmmKind::Native,+ box_home: runtime.layout.boxes_dir().join(id.as_str()),+ };+ runtime.box_manager.add_box(&config, &state).unwrap();+ Self {+ _home: home,+ runtime,+ id,+ config,+ source,+ }+ }++ /// The store as another process opens it.+ fn reopened(&self) -> BoxStore {+ BoxStore::new(Database::open(&self.runtime.layout.db_dir().join("boxlite.db")).unwrap())+ }++ pub(crate) fn handle(&self) -> BoxImpl {+ BoxImpl::new(+ self.config.clone(),+ self.runtime.box_manager.update_box(&self.id).unwrap(),+ self.runtime.clone(),+ self.runtime.shutdown_token.child_token(),+ )+ }++ pub(crate) fn request(&self) -> MountRequest {+ MountRequest {+ source: self.source.clone(),+ target: WORK.into(),+ read_only: false,+ }+ }++ /// Whether the options of the next start carry a declaration at `WORK`.+ fn boots_with(&self, mounts: &Mounts) -> bool {+ let mut options = self.config.options.clone();+ mounts.apply_to_boot(&mut options);+ options.mounts.iter().any(|mount| mount.target == WORK)+ || options+ .volumes+ .iter()+ .any(|volume| volume.guest_path == WORK)+ }+}++#[tokio::test]+async fn stopped_changes_are_persistent_and_do_not_start_a_vm() {+ for status in [BoxStatus::Configured, BoxStatus::Stopped] {+ let fx = Fixture::new(status);+ let bx = fx.handle();+ assert!(bx.mount_get(Path::new(WORK)).await.unwrap().is_none());+ let added = bx.mount_add(fx.request()).await.unwrap();+ assert_eq!(added.state, MountState::Configured);+ assert_eq!(+ bx.mount_list().await.unwrap().as_slice(),+ std::slice::from_ref(&added)+ );+ assert_eq!(+ fx.reopened().mounts(fx.id.as_str()).unwrap().lookup(WORK),+ Some(added)+ );+ assert!(fx.boots_with(&fx.reopened().mounts(fx.id.as_str()).unwrap()));+ let state = fx.runtime.box_manager.update_box(&fx.id).unwrap();+ assert_eq!((state.status, state.pid), (status, None));+ assert!(matches!(+ bx.mount_add(fx.request()).await,+ Err(BoxliteError::InvalidState(_))+ ));++ // A declaration whose source is gone still goes.+ std::fs::remove_dir(&fx.source).unwrap();+ bx.mount_remove(Path::new(WORK)).await.unwrap();+ assert!(bx.mount_get(Path::new(WORK)).await.unwrap().is_none());+ let mounts = fx.reopened().mounts(fx.id.as_str()).unwrap();+ assert!(mounts.lookup(WORK).is_none() && !fx.boots_with(&mounts));+ assert!(matches!(+ bx.mount_remove(Path::new(WORK)).await,+ Err(BoxliteError::NotFound(_))+ ));+ }+}++#[tokio::test]+async fn paused_unsupported_and_unsafe_changes_are_refused() {+ let fx = Fixture::new(BoxStatus::Paused);+ let refused = [+ fx.handle().mount_add(fx.request()).await.map(|_| ()),+ fx.handle().mount_remove(Path::new(WORK)).await,+ ];+ assert!(+ refused+ .iter()+ .all(|result| matches!(result, Err(BoxliteError::InvalidState(_))))+ );++ let mut fx = Fixture::new(BoxStatus::Stopped);+ for target in ["/", "relative", "/a/../b"] {+ let request = MountRequest {+ target: target.into(),+ ..fx.request()+ };+ assert!(matches!(+ fx.handle().mount_add(request).await,+ Err(BoxliteError::InvalidArgument(_))+ ));+ }+ let request = MountRequest {+ source: fx.source.join("missing"),+ ..fx.request()+ };+ assert!(matches!(+ fx.handle().mount_add(request).await,+ Err(BoxliteError::NotFound(_))+ ));+ fx.config.engine_kind = VmmKind::Libkrun;+ assert!(matches!(+ fx.handle().mount_add(fx.request()).await,+ Err(BoxliteError::Unsupported(_))+ ));+ fx.config.engine_kind = VmmKind::Native;+ fx.config.options.advanced.set_privileged(true);+ assert!(matches!(+ fx.handle().mount_add(fx.request()).await,+ Err(BoxliteError::Unsupported(_))+ ));+ assert!(+ fx.reopened()+ .mounts(fx.id.as_str())+ .unwrap()+ .visible()+ .is_empty()+ );+}++#[tokio::test]+async fn an_added_source_is_refused_once_it_is_a_link_in_any_spelling() {+ for slash in ["", "/"] {+ let fx = Fixture::new(BoxStatus::Stopped);+ let real = fx._home.path().join("real");+ std::fs::create_dir(&real).unwrap();+ let request = MountRequest {+ source: PathBuf::from(format!("{}{slash}", fx.source.display())),+ ..fx.request()+ };+ fx.handle().mount_add(request).await.unwrap();+ std::fs::remove_dir(&fx.source).unwrap();+ std::os::unix::fs::symlink(&real, &fx.source).unwrap();+ let error = fx+ .reopened()+ .mounts(fx.id.as_str())+ .unwrap()+ .check_sources()+ .unwrap_err();+ assert!(matches!(error, BoxliteError::InvalidState(_)), "{error}");+ }+}++#[tokio::test]+async fn a_source_that_overlaps_a_delivered_directory_is_refused() {+ let fx = Fixture::new(BoxStatus::Stopped);+ let bx = fx.handle();+ let (parent, sibling) = (fx.source.join("parent"), fx.source.join("sibling"));+ let child = parent.join("child");+ for directory in [&parent, &child, &sibling] {+ std::fs::create_dir_all(directory).unwrap();+ }+ let add = |source: &Path, target: &str| MountRequest {+ source: source.into(),+ target: target.into(),+ read_only: false,+ };+ bx.mount_add(add(&parent, "/parent")).await.unwrap();++ // The same directory, below it, and above it: the next start could not+ // deliver the two as separate shares.+ std::os::unix::fs::symlink(&parent, fx.source.join("alias")).unwrap();+ for (source, target) in [+ (parent.clone(), "/again"),+ (child.clone(), "/child"),+ (fx.source.join("alias/child"), "/alias"),+ (fx.source.clone(), "/above"),+ ] {+ let error = bx.mount_add(add(&source, target)).await.unwrap_err();+ assert!(+ matches!(error, BoxliteError::InvalidState(_)) && error.to_string().contains("/parent"),+ "{target}: {error}"+ );+ assert_eq!(bx.mount_get(Path::new(target)).await.unwrap(), None);+ }++ // A directory beside it is delivered on its own.+ let sibling = bx.mount_add(add(&sibling, "/sibling")).await.unwrap();+ assert_eq!(sibling.state, MountState::Configured);+ assert_eq!(bx.mount_list().await.unwrap().len(), 2);+}++#[tokio::test]+async fn a_target_at_or_around_the_containers_own_mounts_is_refused() {+ let fx = Fixture::new(BoxStatus::Stopped);+ let bx = fx.handle();+ // The target is normalized first; the full matrix lives with the shared helper.+ for target in ["/dev/", "/tmp/work"] {+ let request = MountRequest {+ target: target.into(),+ ..fx.request()+ };+ let error = bx.mount_add(request).await.unwrap_err();+ assert!(+ matches!(error, BoxliteError::InvalidArgument(_)),+ "{target}: {error}"+ );+ }++ // A path that only shares the spelling is another directory.+ let beside = MountRequest {+ target: "/tmpwork".into(),+ ..fx.request()+ };+ assert_eq!(+ bx.mount_add(beside).await.unwrap().state,+ MountState::Configured+ );+ assert_eq!(bx.mount_list().await.unwrap().len(), 1);+}++#[tokio::test]+async fn a_target_with_a_mount_below_it_is_refused() {+ let data = tempfile::tempdir_in("/tmp").unwrap();+ let fx = Fixture::with_mounts(+ BoxStatus::Stopped,+ vec![MountSpec::bind_mount(+ data.path().to_str().unwrap(),+ "/work/inner",+ )],+ );+ let bx = fx.handle();+ // Applied after the box's own mounts, the directory would cover this one.+ let request = MountRequest {+ target: "/work".into(),+ ..fx.request()+ };+ let error = bx.mount_add(request).await.unwrap_err();+ assert!(+ matches!(error, BoxliteError::InvalidState(_)) && error.to_string().contains("/work/inner"),+ "{error}"+ );+ assert_eq!(bx.mount_get(Path::new("/work")).await.unwrap(), None);++ // Below that mount, nothing is covered.+ let request = MountRequest {+ target: "/work/inner/deeper".into(),+ ..fx.request()+ };+ assert_eq!(+ bx.mount_add(request).await.unwrap().state,+ MountState::Configured+ );+}++#[tokio::test]+async fn a_target_below_a_file_the_box_was_created_with_is_refused() {+ let home = tempfile::tempdir_in("/tmp").unwrap();+ let file = home.path().join("config");+ std::fs::write(&file, b"static").unwrap();+ let fx = Fixture::with_mounts(+ BoxStatus::Stopped,+ vec![MountSpec::bind_mount(file.to_str().unwrap(), "/config")],+ );+ let bx = fx.handle();+ // The file's mount leaves no path to mount a directory at.+ for target in ["/config/cache", "/config/deeper/still"] {+ let request = MountRequest {+ target: target.into(),+ ..fx.request()+ };+ let error = bx.mount_add(request).await.unwrap_err();+ assert!(+ matches!(error, BoxliteError::InvalidState(_)) && error.to_string().contains("/config"),+ "{target}: {error}"+ );+ assert_eq!(bx.mount_get(Path::new(target)).await.unwrap(), None);+ }++ // A path that only shares the spelling is another directory.+ let request = MountRequest {+ target: "/config-cache".into(),+ ..fx.request()+ };+ assert_eq!(+ bx.mount_add(request).await.unwrap().state,+ MountState::Configured+ );+}diff --git a/src/boxlite/src/portal/interfaces/container.rs b/src/boxlite/src/portal/interfaces/container.rsindex 488d0d9db..fd1236558 100644--- a/src/boxlite/src/portal/interfaces/container.rs+++ b/src/boxlite/src/portal/interfaces/container.rs@@ -174,16 +174,23 @@ impl ContainerInterface {let proto_mounts: Vec<BindMount> = mounts.into_iter().map(|m| {- let (kind, subpath) = match m.payload {+ let (kind, subpath, record) = match m.payload {crate::volumes::ContainerMountPayload::WholeDirectory => {- (BindMountKind::WholeDirectory, String::new())+ (BindMountKind::WholeDirectory, String::new(), None)}crate::volumes::ContainerMountPayload::SingleFile { file_name } => {- (BindMountKind::SingleFile, file_name)+ (BindMountKind::SingleFile, file_name, None)}crate::volumes::ContainerMountPayload::ManagedSubDirectory { sub_path } => {- (BindMountKind::ManagedSubDirectory, sub_path)+ (BindMountKind::ManagedSubDirectory, sub_path, None)}+ // The runtime mounts the directory as it mounts a whole+ // directory; the guest records that mount under the key.+ crate::volumes::ContainerMountPayload::RecordedDirectory { key, added } => (+ BindMountKind::WholeDirectory,+ String::new(),+ Some((key, added)),+ ),};BindMount {volume_name: m.volume_name,@@ -193,6 +200,11 @@ impl ContainerInterface {owner_gid: m.owner_gid,kind: kind as i32,subpath,+ record_key: record+ .as_ref()+ .map(|(key, _)| key.clone())+ .unwrap_or_default(),+ added: record.is_some_and(|(_, added)| added),}}).collect();@@ -387,11 +399,15 @@ fn map_container_init_status(status: tonic::Status) -> BoxliteError {status.into()}+/// Keep the categories the guest refuses a mount or a detach with. Anything+/// else is a transport or guest failure, whose outcome is unknown.fn map_mount_status(status: tonic::Status) -> BoxliteError {- if status.code() == tonic::Code::Unimplemented {- return BoxliteError::Unsupported(status.message().to_owned());+ match status.code() {+ tonic::Code::Unimplemented => BoxliteError::Unsupported(status.message().to_owned()),+ tonic::Code::FailedPrecondition => BoxliteError::InvalidState(status.message().to_owned()),+ tonic::Code::InvalidArgument => BoxliteError::InvalidArgument(status.message().to_owned()),+ _ => status.into(),}- status.into()}#[cfg(test)]@@ -408,15 +424,28 @@ mod tests {use tonic::{Request, Response, Status};#[test]- fn unsupported_mounts_preserve_the_capability_error_category() {+ fn guest_refusals_keep_their_error_category() {assert!(matches!(map_mount_status(tonic::Status::unimplemented("CAP_SYS_ADMIN")),BoxliteError::Unsupported(message) if message == "CAP_SYS_ADMIN"));+ assert!(matches!(+ map_mount_status(Status::failed_precondition("detach runtime descendants first")),+ BoxliteError::InvalidState(message) if message == "detach runtime descendants first"+ ));+ assert!(matches!(+ map_mount_status(Status::invalid_argument("destination mismatch")),+ BoxliteError::InvalidArgument(_)+ ));assert!(matches!(map_mount_status(tonic::Status::unavailable("guest disconnected")),BoxliteError::Rpc(_)));+ // A check the guest ran after it acted: the caller undoes the mount, it does not skip it.+ assert!(matches!(+ map_mount_status(Status::internal("the mount was attached, but unverified")),+ BoxliteError::Rpc(_)+ ));}#[test]diff --git a/src/boxlite/src/portal/interfaces/guest.rs b/src/boxlite/src/portal/interfaces/guest.rsindex c3cd6d8d0..62ab5dca5 100644--- a/src/boxlite/src/portal/interfaces/guest.rs+++ b/src/boxlite/src/portal/interfaces/guest.rs@@ -91,6 +91,21 @@ impl GuestInterface {))}+ /// Fail before initialization if the guest cannot record the mounts the+ /// container runtime makes for declared directories. A directory added at+ /// runtime needs its record, or an online removal could not select it.+ pub async fn require_boot_mount_records(&mut self) -> BoxliteResult<()> {+ let response = self.client.ping(PingRequest {}).await?.into_inner();+ if response.records_boot_mounts {+ return Ok(());+ }+ Err(BoxliteError::Unsupported(+ "the guest cannot record the mounts of declared directories, which a directory added at runtime \+ needs; update the box's guest agent and kernel, or remove those directories"+ .into(),+ ))+ }+/// Shutdown the guest agent.pub async fn shutdown(&mut self) -> BoxliteResult<()> {let _response = self.client.shutdown(ShutdownRequest {}).await?;diff --git a/src/boxlite/src/runtime/advanced_options.rs b/src/boxlite/src/runtime/advanced_options.rsindex b0586ed33..ed3271d12 100644--- a/src/boxlite/src/runtime/advanced_options.rs+++ b/src/boxlite/src/runtime/advanced_options.rs@@ -971,6 +971,22 @@ impl AdvancedBoxOptions {}}+ /// Aggregate delivery needs a mount namespace the workload cannot modify.+ /// Match the guest's capability resolution: with `add=ALL`, named drops win.+ pub(crate) fn permits_aggregate_mounts(&self) -> bool {+ let caps = self.effective_capabilities();+ let has = |names: &[String], capability: &str| {+ names+ .iter()+ .any(|name| canonical_capability_name(name) == capability)+ };+ if has(&caps.add, "ALL") {+ has(&caps.drop, "SYS_ADMIN")+ } else {+ !has(&caps.add, "SYS_ADMIN")+ }+ }+/// Resolve the container security request before it crosses into the guest.////// The host owns the public option semantics *and* the literal OCI valuesdiff --git a/src/boxlite/src/runtime/backend.rs b/src/boxlite/src/runtime/backend.rsindex d358ab6a0..50af3e37a 100644--- a/src/boxlite/src/runtime/backend.rs+++ b/src/boxlite/src/runtime/backend.rs@@ -10,7 +10,8 @@ use async_trait::async_trait;use crate::litebox::copy::CopyOptions;use crate::litebox::snapshot_mgr::SnapshotInfo;use crate::litebox::{- AttachOptions, BoxCommand, BoxTunnel, Execution, LiteBox, SshConfig, SshStatus,+ AttachOptions, BoxCommand, BoxTunnel, Execution, LiteBox, MountInfo, MountRequest, SshConfig,+ SshStatus,};use crate::metrics::{BoxMetrics, RuntimeMetrics};use crate::runtime::options::{@@ -72,6 +73,10 @@ pub(crate) trait RuntimeBackend: Send + Sync {fn shutdown_sync(&self) {}}+fn unsupported_mounts() -> BoxliteError {+ BoxliteError::Unsupported("runtime directory mounts need a local Linux x86_64 native VM".into())+}+/// Backend abstraction for individual box operations.////// Local backend is implemented directly by `BoxImpl`.@@ -135,6 +140,26 @@ pub(crate) trait BoxBackend: Send + Sync + Any {))}+ /// Save a directory declaration and deliver it if the box is running.+ async fn mount_add(&self, _request: MountRequest) -> BoxliteResult<MountInfo> {+ Err(unsupported_mounts())+ }++ /// Remove a declaration, detaching a live mount before committing the removal.+ async fn mount_remove(&self, _target: &Path) -> BoxliteResult<()> {+ Err(unsupported_mounts())+ }++ /// List effective declarations and current delivery progress.+ async fn mount_list(&self) -> BoxliteResult<Vec<MountInfo>> {+ Err(unsupported_mounts())+ }++ /// Read the latest mount entry at `target`.+ async fn mount_get(&self, _target: &Path) -> BoxliteResult<Option<MountInfo>> {+ Err(unsupported_mounts())+ }+async fn metrics(&self) -> BoxliteResult<BoxMetrics>;async fn stop(&self) -> BoxliteResult<()>;diff --git a/src/boxlite/src/runtime/rt_impl.rs b/src/boxlite/src/runtime/rt_impl.rsindex 07c7996ec..d0a6059a9 100644--- a/src/boxlite/src/runtime/rt_impl.rs+++ b/src/boxlite/src/runtime/rt_impl.rs@@ -253,6 +253,15 @@ impl RuntimeImpl {Self::initialize(options, ExperimentalFeatures::default())}+ /// Like [`Self::new_for_test`], with explicit experimental opt-ins.+ #[cfg(all(test, feature = "native", target_os = "linux", target_arch = "x86_64"))]+ pub(crate) fn new_for_test_with_features(+ options: BoxliteOptions,+ experimental_features: ExperimentalFeatures,+ ) -> BoxliteResult<SharedRuntimeImpl> {+ Self::initialize(options, experimental_features)+ }+pub(super) fn initialize(options: BoxliteOptions,experimental_features: ExperimentalFeatures,diff --git a/src/boxlite/src/vmm/controller/mount_control.rs b/src/boxlite/src/vmm/controller/mount_control.rsindex b04072633..72b8cf25b 100644--- a/src/boxlite/src/vmm/controller/mount_control.rs+++ b/src/boxlite/src/vmm/controller/mount_control.rs@@ -1,7 +1,7 @@//! Host directory delivery to a single VM through its `vmm.sock`.//!-//! Registration publishes `Preparing` before replying. A lost reply can be-//! reconciled with `list`. The caller owns guest acknowledgment and recovery.+//! The shim keeps exports, not state. Registration publishes an export before+//! replying; a client whose reply was lost finds it again by request ID.use crate::vmm::vmm_socket::{self, ControlError, ControlOp, ControlReply};use serde::{Deserialize, Serialize};@@ -16,12 +16,7 @@ pub(crate) use registry::Registry;// Include time queued behind an online disk resize in the exchange budget.const CONTROL_TIMEOUT: Duration = Duration::from_secs(15);-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-pub enum MountState {- Preparing,- Mounted,- Detaching,-}+pub(crate) type MountRequestId = [u8; 16];#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct ControlMount {@@ -29,7 +24,6 @@ pub struct ControlMount {pub source: String,pub target: String,pub read_only: bool,- pub state: MountState,}/// Blocking client. Each operation opens a connection for one exchange.@@ -57,18 +51,22 @@ impl MountControlClient {}}+ /// Publish `file` as one export. A request ID names at most one export,+ /// so a retry or a lost reply never publishes a second.pub fn register(&self,source: String,target: String,file: File,read_only: bool,+ request_id: MountRequestId,) -> io::Result<ControlMount> {match self.exchange(ControlOp::RegisterMount {source,target,read_only,+ request_id,},Some(&file),)? {@@ -77,22 +75,20 @@ impl MountControlClient {}}- pub fn list(&self) -> io::Result<Vec<ControlMount>> {- match self.exchange(ControlOp::ListMounts, None)? {- ControlReply::Mounts(mounts) => Ok(mounts),+ /// The export registered under `request_id`, if any.+ pub(crate) fn find_registered(+ &self,+ request_id: MountRequestId,+ ) -> io::Result<Option<ControlMount>> {+ match self.exchange(ControlOp::FindRegisteredMount { request_id }, None)? {+ ControlReply::RegisteredMount(mount) => Ok(mount),_ => Err(unexpected_reply()),}}- pub fn set_state(&self, export: &str, state: MountState) -> io::Result<()> {- match self.exchange(- ControlOp::SetMountState {- export: export.into(),- state,- },- None,- )? {- ControlReply::MountUpdated => Ok(()),+ pub fn list(&self) -> io::Result<Vec<ControlMount>> {+ match self.exchange(ControlOp::ListMounts, None)? {+ ControlReply::Mounts(mounts) => Ok(mounts),_ => Err(unexpected_reply()),}}diff --git a/src/boxlite/src/vmm/controller/mount_control/registry.rs b/src/boxlite/src/vmm/controller/mount_control/registry.rsindex 97f19c377..6a4e4c126 100644--- a/src/boxlite/src/vmm/controller/mount_control/registry.rs+++ b/src/boxlite/src/vmm/controller/mount_control/registry.rs@@ -1,20 +1,31 @@-use super::{ControlMount, MountState};+use super::{ControlMount, MountRequestId};use crate::vmm::vmm_socket::{ControlOp, ControlReply, MAX_MOUNT_BODY};+use boxlite_shared::constants::normalize_target;use boxlite_vmm::lookup_aggregate;use std::fs::File;use std::io;-use std::path::{Component, Path};/// Maximum length in bytes of a source or target path in a mount request.const MAX_PATH_BYTES: usize = 4096;+/// The exports of one VM. Each names a directory descriptor the aggregate+/// device serves. Nothing here outlives the VM.#[derive(Default)]pub(crate) struct Registry {next: u64,- mounts: Vec<ControlMount>,+ mounts: Vec<RegisteredMount>,list_bytes: usize,}+/// One registered export. The request that registered it lets a client whose+/// reply was lost find the export again.+struct RegisteredMount {+ mount: ControlMount,+ request_id: MountRequestId,+ /// The bytes the record takes in a `ListMounts` reply, JSON escaping included.+ cost: usize,+}+fn errno(code: i32) -> io::Error {io::Error::from_raw_os_error(code)}@@ -32,31 +43,10 @@ fn record_cost(mount: &ControlMount) -> io::Result<usize> {}let mut counter = Counter(0);serde_json::to_writer(&mut counter, mount)?;- // Reserve a comma per record (one extra is harmless). `Preparing` is as- // long as the record ever serializes: `Detaching` matches it, `Mounted` is shorter.+ // Reserve a comma per record (one extra is harmless).Ok(counter.0 + 1)}-fn normalize_target(target: &str) -> io::Result<String> {- if target.len() > MAX_PATH_BYTES || target.contains('\0') || !target.starts_with('/') {- return Err(errno(libc::EINVAL));- }- let mut components = Vec::new();- for component in Path::new(target).components() {- match component {- Component::RootDir | Component::CurDir => (),- Component::Normal(name) => {- components.push(name.to_str().ok_or_else(|| errno(libc::EINVAL))?)- }- _ => return Err(errno(libc::EINVAL)),- }- }- if components.is_empty() {- return Err(errno(libc::EINVAL));- }- Ok(format!("/{}", components.join("/")))-}-impl Registry {pub(crate) fn request(&mut self,@@ -70,13 +60,26 @@ impl Registry {source,target,read_only,+ request_id,} => {let directory = directory.ok_or_else(|| errno(libc::EINVAL))?;if source.is_empty() || source.len() > MAX_PATH_BYTES || source.contains('\0') {return Err(errno(libc::EINVAL));}- let target = normalize_target(&target)?;- if self.mounts.iter().any(|mount| mount.target == target) {+ if target.len() > MAX_PATH_BYTES {+ return Err(errno(libc::EINVAL));+ }+ let target = normalize_target(&target).ok_or_else(|| errno(libc::EINVAL))?;+ // One request registers one export: a retry must not publish a second.+ if self+ .mounts+ .iter()+ .any(|entry| entry.request_id == request_id)+ {+ return Err(errno(libc::EBUSY));+ }+ // One export per target: the guest would mount a second over the first.+ if self.mounts.iter().any(|entry| entry.mount.target == target) {return Err(errno(libc::EBUSY));}let next = self@@ -88,10 +91,8 @@ impl Registry {source,target,read_only,- state: MountState::Preparing,};- // Empty List envelope plus worst-case serialized records; the- // counter includes JSON escaping without copying existing records.+ // Empty List envelope plus the serialized record.let cost = record_cost(&mount)?;let envelope = br#"{"Ok":{"mounts":[]}}"#.len();if self.list_bytes + cost + envelope > MAX_MOUNT_BODY {@@ -104,38 +105,40 @@ impl Registry {.map_err(|_| errno(libc::ENOMEM))?;self.next = next;filesystem.register_fd(mount.export.clone(), directory, read_only)?;- self.mounts.push(mount.clone());+ self.mounts.push(RegisteredMount {+ mount: mount.clone(),+ request_id,+ cost,+ });self.list_bytes += cost;Ok(ControlReply::MountRegistered(mount))}- ControlOp::ListMounts => Ok(ControlReply::Mounts(self.mounts.clone())),- ControlOp::SetMountState { export, state } => {+ ControlOp::ListMounts => Ok(ControlReply::Mounts(+ self.mounts+ .iter()+ .map(|entry| entry.mount.clone())+ .collect(),+ )),+ ControlOp::FindRegisteredMount { request_id } => {let mount = self.mounts- .iter_mut()- .find(|mount| mount.export == export)- .ok_or_else(|| errno(libc::ENOENT))?;- match (mount.state, state) {- (current, requested) if current == requested => (),- (MountState::Preparing, MountState::Mounted | MountState::Detaching)- | (MountState::Mounted, MountState::Detaching) => mount.state = state,- _ => return Err(errno(libc::EINVAL)),- }- Ok(ControlReply::MountUpdated)+ .iter()+ .find(|entry| entry.request_id == request_id)+ .map(|entry| entry.mount.clone());+ Ok(ControlReply::RegisteredMount(mount))}ControlOp::RemoveMount { export } => {- let index = self+ // An export that is already gone stays gone, so a retry after a+ // lost reply finishes.+ let Some(index) = self.mounts.iter()- .position(|mount| mount.export == export)- .ok_or_else(|| errno(libc::ENOENT))?;- if self.mounts[index].state != MountState::Detaching {- return Err(errno(libc::EBUSY));- }- let cost = record_cost(&self.mounts[index])?;+ .position(|entry| entry.mount.export == export)+ else {+ return Ok(ControlReply::MountUpdated);+ };filesystem.remove(&export)?;- self.mounts.remove(index);- self.list_bytes -= cost;+ self.list_bytes -= self.mounts.remove(index).cost;Ok(ControlReply::MountUpdated)}ControlOp::ResizeDisk { .. } => unreachable!("disk resize is dispatched by the VMM"),diff --git a/src/boxlite/src/vmm/tests/vmm_socket.rs b/src/boxlite/src/vmm/tests/vmm_socket.rsindex a85245406..7666ee0c4 100644--- a/src/boxlite/src/vmm/tests/vmm_socket.rs+++ b/src/boxlite/src/vmm/tests/vmm_socket.rs@@ -456,13 +456,14 @@ fn http_runs_under_the_production_vmm_filter() {#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]mod mounts {use super::*;- use crate::vmm::controller::mount_control::{MountControlClient, MountState, Registry};+ use crate::vmm::controller::mount_control::{MountControlClient, MountRequestId, Registry};use boxlite_vmm::AggregateFs;use std::os::fd::AsRawFd;use std::path::PathBuf;use std::sync::Arc;const TIMEOUT: Duration = Duration::from_secs(5);+ const REQUEST_ID: MountRequestId = [7; 16];fn fixture() -> (tempfile::TempDir, Arc<AggregateFs>, PathBuf) {let dir = tempfile::tempdir().unwrap();@@ -480,11 +481,12 @@ mod mounts {(dir, fs, path)}- fn registration(target: &str) -> ControlOp {+ fn registration(target: &str, request_id: MountRequestId) -> ControlOp {ControlOp::RegisterMount {source: "/source".into(),target: target.into(),read_only: false,+ request_id,}}@@ -511,7 +513,7 @@ mod mounts {let directory = File::open(dir.path()).unwrap();let mut stream = UnixStream::connect(&path).unwrap();stream.set_read_timeout(Some(TIMEOUT)).unwrap();- let body = serde_json::to_vec(®istration("/data")).unwrap();+ let body = serde_json::to_vec(®istration("/data", REQUEST_ID)).unwrap();let request = http_request("POST", MOUNT_PATH, &body);assert_eq!(transport::send_with_file(stream.as_raw_fd(), &request[..1], directory.as_raw_fd())@@ -528,14 +530,12 @@ mod mounts {panic!("expected one recoverable registration, got {records:?}");};assert_eq!(mount.target, "/data");- assert_eq!(mount.state, MountState::Preparing);- client- .set_state(&mount.export, MountState::Mounted)- .unwrap();- assert_eq!(client.list().unwrap()[0].state, MountState::Mounted);- client- .set_state(&mount.export, MountState::Detaching)- .unwrap();+ // The reply never arrived: only the request's ID finds the export.+ assert_eq!(+ client.find_registered(REQUEST_ID).unwrap().as_ref(),+ Some(mount)+ );+ assert!(client.find_registered([8; 16]).unwrap().is_none());client.remove(&mount.export).unwrap();assert!(client.list().unwrap().is_empty());}@@ -545,7 +545,7 @@ mod mounts {let (dir, _fs, path) = fixture();let directory = File::open(dir.path()).unwrap();assert_eq!(- exchange(&path, registration("/data"), None, TIMEOUT).unwrap(),+ exchange(&path, registration("/data", REQUEST_ID), None, TIMEOUT).unwrap(),Err(ControlError::Mount(libc::EINVAL)));assert_eq!(@@ -554,10 +554,16 @@ mod mounts {);let file = tempfile::tempfile().unwrap();assert_eq!(- exchange(&path, registration("/data"), Some(&file), TIMEOUT).unwrap(),+ exchange(+ &path,+ registration("/data", REQUEST_ID),+ Some(&file),+ TIMEOUT+ )+ .unwrap(),Err(ControlError::Mount(libc::ENOTDIR)));- let body = serde_json::to_vec(®istration("/data")).unwrap();+ let body = serde_json::to_vec(®istration("/data", REQUEST_ID)).unwrap();let request = http_request("POST", MOUNT_PATH, &body);let mut stream = UnixStream::connect(&path).unwrap();stream.set_read_timeout(Some(TIMEOUT)).unwrap();@@ -582,7 +588,13 @@ mod mounts {let client = MountControlClient::new(path);assert!(client.list().unwrap().is_empty());client- .register("/source".into(), "/data".into(), directory, false)+ .register(+ "/source".into(),+ "/data".into(),+ directory,+ false,+ REQUEST_ID,+ ).unwrap();}@@ -593,7 +605,7 @@ mod mounts {let filesystem = Arc::new(AggregateFs::new(vec![]).unwrap());boxlite_vmm::insert_aggregate(tag, filesystem);let directory = File::open(dir.path()).unwrap();- let body = serde_json::to_vec(®istration("/data")).unwrap();+ let body = serde_json::to_vec(®istration("/data", REQUEST_ID)).unwrap();let (mut client, stream) = UnixStream::pair().unwrap();// Queue the complete HTTP request before the byte carrying the descriptor.@@ -633,14 +645,10 @@ mod mounts {format!("/{admitted}{}", "\"".repeat(2000)),File::open(dir.path()).unwrap(),true,+ (admitted as u128).to_be_bytes(),);match result {- Ok(mount) => {- client- .set_state(&mount.export, MountState::Mounted)- .unwrap();- admitted += 1;- }+ Ok(_) => admitted += 1,Err(error) => {assert_eq!(error.raw_os_error(), Some(libc::ENOSPC));break;@@ -651,11 +659,9 @@ mod mounts {assert!(admitted > 0);assert_eq!(mounts.len(), admitted);for mount in mounts {- client- .set_state(&mount.export, MountState::Detaching)- .unwrap();+ client.remove(&mount.export).unwrap();}- assert_eq!(client.list().unwrap().len(), admitted);+ assert!(client.list().unwrap().is_empty());}#[test]@@ -712,7 +718,10 @@ mod mounts {});for (op, directory) in [(ControlOp::ListMounts, None),- (registration("/data"), Some(File::open(dir.path()).unwrap())),+ (+ registration("/data", REQUEST_ID),+ Some(File::open(dir.path()).unwrap()),+ ),] {assert_eq!(exchange(&path, op, directory.as_ref(), TIMEOUT).unwrap(),diff --git a/src/boxlite/src/vmm/vmm_socket.rs b/src/boxlite/src/vmm/vmm_socket.rsindex b53a871ea..7736698ed 100644--- a/src/boxlite/src/vmm/vmm_socket.rs+++ b/src/boxlite/src/vmm/vmm_socket.rs@@ -41,7 +41,7 @@ use {};#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]-use super::controller::mount_control::{ControlMount, MountState};+use super::controller::mount_control::{ControlMount, MountRequestId};#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]mod transport;@@ -83,11 +83,12 @@ pub(crate) enum ControlOp {source: String,target: String,read_only: bool,+ request_id: MountRequestId,},#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]ListMounts,#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]- SetMountState { export: String, state: MountState },+ FindRegisteredMount { request_id: MountRequestId },#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]RemoveMount { export: String },}@@ -106,6 +107,8 @@ pub(crate) enum ControlReply {#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]Mounts(Vec<ControlMount>),#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ RegisteredMount(Option<ControlMount>),+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]MountUpdated,}diff --git a/src/boxlite/src/volumes/container_volume.rs b/src/boxlite/src/volumes/container_volume.rsindex bc65119ba..3c1dcdbce 100644--- a/src/boxlite/src/volumes/container_volume.rs+++ b/src/boxlite/src/volumes/container_volume.rs@@ -20,6 +20,10 @@ pub(crate) enum ContainerMountPayload {SingleFile { file_name: String },/// Pin one relative directory from a managed volume payload.ManagedSubDirectory { sub_path: String },+ /// Mount the shared directory itself. The guest records the mount under+ /// `key`, so the host can detach it while the container runs. `added`+ /// marks a directory saved while the box was stopped.+ RecordedDirectory { key: String, added: bool },}/// Container bind mount entry.diff --git a/src/boxlite/tests/README.md b/src/boxlite/tests/README.mdindex de4dd3244..7c25abeb5 100644--- a/src/boxlite/tests/README.md+++ b/src/boxlite/tests/README.md@@ -23,6 +23,7 @@ This directory contains integration tests for the BoxLite runtime. Tests run con| `pid_file.rs` | Yes | PID file management and process tracking tests || `jailer.rs` | Yes | Jailer default behavior and macOS seatbelt deny lifecycle tests || `clone_export_import.rs` | Yes | Clone, export, and import operations |+| `runtime_mounts.rs` | Yes | Persistent directory mounts through `bx.mount()` on the native engine. Outside the M2/M3 matrix; the file header gives the command || `sigstop_quiesce.rs` | Yes | SIGSTOP-based quiesce for snapshot operations || `rest_integration.rs` | Yes | REST API integration tests || `agents_opencode.rs` | Yes | OpenCode 2.2 agent adapter; ignored by default, run with `make test:integration:agents` and `BOXLITE_TEST_OPENCODE_BINARY` (see the file header). Its fake model lives in `common/opencode.rs`, which the CLI `agents` tests also include |diff --git a/src/boxlite/tests/native_mount_delivery.rs b/src/boxlite/tests/native_mount_delivery.rsindex c6ef03ee1..790f2dbbf 100644--- a/src/boxlite/tests/native_mount_delivery.rs+++ b/src/boxlite/tests/native_mount_delivery.rs@@ -5,7 +5,7 @@mod common;use boxlite::runtime::options::{BoxliteOptions, NetworkSpec};-use boxlite::vmm::controller::mount_control::{MountControlClient, MountState};+use boxlite::vmm::controller::mount_control::MountControlClient;use boxlite::{BoxCommand, LiteBox};use boxlite_shared::{ContainerClient, ContainerDetachRequest, ContainerMountRequest};use futures::StreamExt;@@ -88,13 +88,6 @@ async fn detached(client: &mut ContainerClient<Channel>, container: &str, export.unwrap();}-async fn state(socket: &Path, export: &str, state: MountState) {- let export = export.to_owned();- control(socket, move |client| client.set_state(&export, state))- .await- .unwrap();-}-async fn retire(socket: &Path, export: &str) {let export = export.to_owned();control(socket, move |client| client.remove(&export))@@ -148,17 +141,16 @@ async fn descriptor_delivery_mounts_and_detaches_in_an_existing_container() {"/workspace".into(),File::open(&path)?,false,+ uuid::Uuid::new_v4().into_bytes(),)}).await.unwrap();- assert_eq!(mount.state, MountState::Preparing);assert_eq!(control(&socket, |client| client.list()).await.unwrap(),vec![mount.clone()]);mounted(&mut rpc, &container, &mount.export, false).await;- state(&socket, &mount.export, MountState::Mounted).await;assert_eq!(run(&bx, "cat /workspace/value").await, (0, "host".into()));assert_eq!(run(&bx, "printf guest > /workspace/from-guest").await.0, 0);assert_eq!(@@ -166,7 +158,6 @@ async fn descriptor_delivery_mounts_and_detaches_in_an_existing_container() {"guest");- state(&socket, &mount.export, MountState::Detaching).await;detached(&mut rpc, &container, &mount.export).await;retire(&socket, &mount.export).await;assert_eq!(run(&bx, "test ! -e /workspace/value").await.0, 0);diff --git a/src/boxlite/tests/runtime_mounts.rs b/src/boxlite/tests/runtime_mounts.rsnew file mode 100644index 000000000..a082d2859--- /dev/null+++ b/src/boxlite/tests/runtime_mounts.rs@@ -0,0 +1,628 @@+//! OpenSpec PR-3 acceptance on Linux x86_64 KVM.+//! Run with `BOXLITE_TEST_ENGINE=native make test:integration:vmm:m2:run MATRIX_TEST_SUITES=runtime_mounts`.++#![cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]++mod common;++use boxlite::runtime::options::{BoxOptions, BoxliteOptions, MountSpec, NetworkSpec, VolumeSpec};+use boxlite::{+ BoxCommand, BoxStatus, BoxliteError, Execution, LiteBox, MountInfo, MountRequest, MountState,+};+use common::home::PerTestBoxHome;+use futures::{FutureExt, StreamExt};+use std::path::Path;+use std::time::Duration;++const READER: &str = "BOXLITE_TEST_MOUNT_READER";++fn source(probe: &str) -> tempfile::TempDir {+ let dir = tempfile::tempdir_in("/tmp").unwrap();+ std::fs::write(dir.path().join("probe"), probe).unwrap();+ dir+}++fn request(source: &Path, target: &str, read_only: bool) -> MountRequest {+ MountRequest {+ source: source.into(),+ target: target.into(),+ read_only,+ }+}++fn options() -> BoxOptions {+ BoxOptions {+ network: NetworkSpec::Disabled,+ cmd: Some(vec![+ "sh".into(),+ "-c".into(),+ "probe=$(cat /work/probe 2>/dev/null || echo absent); \+ printf '%s\\n' \"$probe\" >> /first-process; exec sleep 300"+ .into(),+ ]),+ ..common::alpine_opts()+ }+}++fn open(home: &Path) -> common::TestRuntime {+ common::TestRuntime::new(BoxliteOptions {+ home_dir: home.into(),+ image_registries: common::test_registries(),+ ..Default::default()+ })+ .unwrap()+}++struct Lab {+ runtime: Option<common::TestRuntime>,+ home: PerTestBoxHome,+ boxes: Vec<String>,+}++impl Lab {+ fn runtime(&self) -> &common::TestRuntime {+ self.runtime.as_ref().unwrap()+ }++ async fn create(&mut self, options: BoxOptions) -> LiteBox {+ let bx = self.runtime().create(options, None).await.unwrap();+ self.boxes.push(bx.id().to_string());+ bx+ }++ async fn handle(&self, id: &str) -> LiteBox {+ self.runtime().get(id).await.unwrap().unwrap()+ }++ async fn release(&mut self) {+ self.runtime+ .take()+ .unwrap()+ .shutdown(Some(common::TEST_SHUTDOWN_TIMEOUT))+ .await+ .unwrap();+ }+}++async fn scenario(scene: impl AsyncFnOnce(&mut Lab)) {+ assert_eq!(+ std::env::var("BOXLITE_TEST_ENGINE").as_deref(),+ Ok("native")+ );+ let home = PerTestBoxHome::new();+ let mut lab = Lab {+ runtime: Some(open(&home.path)),+ home,+ boxes: Vec::new(),+ };+ let outcome = std::panic::AssertUnwindSafe(scene(&mut lab))+ .catch_unwind()+ .await;+ if lab.runtime.is_none() {+ lab.runtime = Some(open(&lab.home.path));+ }+ for id in &lab.boxes {+ lab.runtime().remove(id, true).await.unwrap();+ }+ if let Err(panic) = outcome {+ std::panic::resume_unwind(panic);+ }+}++async fn run(bx: &LiteBox, script: &str) -> (i32, String) {+ tokio::time::timeout(Duration::from_secs(60), async {+ let mut execution = bx+ .exec(BoxCommand::new("sh").args(["-c", script]))+ .await+ .unwrap();+ let mut output = String::new();+ if let Some(mut stream) = execution.stdout() {+ while let Some(chunk) = stream.next().await {+ output.push_str(&chunk);+ }+ }+ (execution.wait().await.unwrap().exit_code, output)+ })+ .await+ .unwrap_or_else(|_| panic!("command timed out: {script}"))+}++async fn demand(bx: &LiteBox, script: &str) {+ let (code, output) = run(bx, script).await;+ assert_eq!(code, 0, "{script}: {output}");+}++async fn wait_for(bx: &LiteBox, script: &str) {+ tokio::time::timeout(Duration::from_secs(10), async {+ while run(bx, script).await.0 != 0 {+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ })+ .await+ .unwrap_or_else(|_| panic!("condition timed out: {script}"));+}++async fn first_process(bx: &LiteBox, start: usize, expected: &str) {+ wait_for(+ bx,+ &format!("test $(grep -c '' /first-process) -ge {start}"),+ )+ .await;+ assert_eq!(+ run(bx, &format!("sed -n '{start}p' /first-process")).await,+ (0, format!("{expected}\n"))+ );+}++// Open both references before removal; release them only after the replacement is visible.+async fn hold(bx: &LiteBox) -> Execution {+ let held = bx+ .exec(BoxCommand::new("sh").args([+ "-c",+ "exec 3</work/probe; exec 4</work; touch /tmp/held-ready; \+ while [ ! -e /tmp/held-go ]; do sleep 0.02; done; \+ cat <&3 > /tmp/held-file; cat /proc/self/fd/4/probe > /tmp/held-dir",+ ]))+ .await+ .unwrap();+ wait_for(bx, "test -e /tmp/held-ready").await;+ held+}++async fn release(bx: &LiteBox, held: Execution, probe: &str) {+ demand(bx, "touch /tmp/held-go").await;+ assert_eq!(+ tokio::time::timeout(Duration::from_secs(60), held.wait())+ .await+ .unwrap()+ .unwrap()+ .exit_code,+ 0+ );+ assert_eq!(+ run(bx, "cat /tmp/held-file /tmp/held-dir").await,+ (0, probe.repeat(2))+ );+}++// Fail only the final live commit, after real guest and shim effects.+struct CommitAbort(rusqlite::Connection);++impl CommitAbort {+ fn arm(home: &Path, id: &str, adding: bool) -> Self {+ let conn = rusqlite::Connection::open(home.join("db/boxlite.db")).unwrap();+ conn.busy_timeout(Duration::from_secs(5)).unwrap();+ let condition = if adding {+ r#"OLD.json -> '$.mounts.changes."/work"' IS NULL AND NEW.json -> '$.mounts.changes."/work"' IS NOT NULL"#+ } else {+ r#"OLD.json -> '$.mounts.run.targets."/work"' IS NOT NULL AND NEW.json -> '$.mounts.run.targets."/work"' IS NULL"#+ };+ conn.execute_batch(&format!(+ "CREATE TRIGGER test_abort_mount_commit BEFORE UPDATE ON box_state \+ WHEN OLD.id = '{}' AND NEW.pid IS NOT NULL AND {condition} \+ BEGIN SELECT RAISE(ABORT, 'mount commit interrupted'); END",+ id.replace('\'', "''")+ ))+ .unwrap();+ Self(conn)+ }+}++impl Drop for CommitAbort {+ fn drop(&mut self) {+ self.0+ .execute_batch("DROP TRIGGER test_abort_mount_commit")+ .unwrap();+ }+}++/// Wait until the entry at `target` is in `state`, or absent for `None`.+async fn wait_for_mount(bx: &LiteBox, target: &str, state: Option<MountState>) {+ tokio::time::timeout(Duration::from_secs(30), async {+ while bx+ .mount()+ .get(target)+ .await+ .unwrap()+ .map(|mount| mount.state)+ != state+ {+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ })+ .await+ .unwrap_or_else(|_| panic!("{target} never reached {state:?}"));+}++#[tokio::test(flavor = "multi_thread", worker_threads = 1)]+#[ignore = "requires native runtime, KVM and VMM_KERNEL"]+async fn live_mounts_keep_lazy_references_and_support_remount() {+ scenario(async |lab| {+ let (data, replacement) = (source("original"), source("replacement"));+ let bx = lab.create(options()).await;+ bx.start().await.unwrap();+ let mounts = bx.mount();+ let (added, command) = tokio::join!(+ mounts.add(request(data.path(), "/work", false)),+ run(&bx, "echo alive")+ );+ let added = added.unwrap();+ assert_eq!(added.state, MountState::Mounted);+ assert_eq!(command, (0, "alive\n".into()));+ assert_eq!(+ mounts.list().await.unwrap().as_slice(),+ std::slice::from_ref(&added)+ );+ assert_eq!(mounts.get("/work").await.unwrap(), Some(added));+ assert!(mounts.get("/missing").await.unwrap().is_none());+ demand(&bx, "printf guest > /work/from-guest").await;+ assert_eq!(+ std::fs::read_to_string(data.path().join("from-guest")).unwrap(),+ "guest"+ );+ let held = hold(&bx).await;+ mounts.remove("/work").await.unwrap();+ demand(&bx, "test ! -e /work/probe").await;+ assert!(mounts.get("/work").await.unwrap().is_none());+ assert!(matches!(+ mounts.remove("/work").await,+ Err(BoxliteError::NotFound(_))+ ));+ mounts+ .add(request(replacement.path(), "/work", true))+ .await+ .unwrap();+ assert_eq!(run(&bx, "cat /work/probe").await, (0, "replacement".into()));+ assert_ne!(run(&bx, "touch /work/denied").await.0, 0);+ release(&bx, held, "original").await;+ bx.stop().await.unwrap();+ })+ .await;+}++#[tokio::test]+#[ignore = "requires native runtime, KVM and VMM_KERNEL"]+async fn creation_formats_deliver_once_and_remove_persistently() {+ scenario(async |lab| {+ let data = source("creation");+ for typed in [false, true] {+ let mut opts = options();+ if typed {+ let mut mount = MountSpec::bind_mount(data.path().to_str().unwrap(), "/work");+ mount.read_only = true;+ opts.mounts.push(mount);+ } else {+ let mut volume = VolumeSpec::bind_mount(data.path().to_str().unwrap(), "/work");+ volume.read_only = true;+ opts.volumes.push(volume);+ }+ let bx = lab.create(opts).await;+ assert_eq!(+ bx.mount().get("/work").await.unwrap().unwrap().state,+ MountState::Configured+ );+ bx.start().await.unwrap();+ first_process(&bx, 1, "creation").await;+ assert_eq!(+ run(+ &bx,+ "awk '$5 == \"/work\" { n++ } END { print n }' /proc/self/mountinfo"+ )+ .await,+ (0, "1\n".into())+ );+ assert_ne!(run(&bx, "touch /work/denied").await.0, 0);+ bx.mount().remove("/work").await.unwrap();+ bx.stop().await.unwrap();+ let next = lab.handle(bx.id().as_str()).await;+ next.start().await.unwrap();+ first_process(&next, 2, "absent").await;+ assert!(next.mount().get("/work").await.unwrap().is_none());+ next.stop().await.unwrap();+ }+ })+ .await;+}++#[tokio::test]+#[ignore = "requires native runtime, KVM and VMM_KERNEL"]+async fn offline_declarations_are_read_by_another_process_and_restarted() {+ if let Ok(ask) = std::env::var(READER) {+ let (home, id, expected): (std::path::PathBuf, String, MountInfo) =+ serde_json::from_str(&ask).unwrap();+ let runtime = open(&home);+ let bx = runtime.get(&id).await.unwrap().unwrap();+ assert_eq!(+ bx.mount().get("/work").await.unwrap(),+ Some(expected.clone())+ );+ assert_eq!(bx.mount().list().await.unwrap(), [expected]);+ std::process::exit(23); // Proves the child reached the assertions, rather than matching zero tests.+ }+ scenario(async |lab| {+ let (data, late) = (source("offline"), source("late"));+ let (id, saved) = {+ let bx = lab.create(options()).await;+ let saved = bx+ .mount()+ .add(request(data.path(), "/work", true))+ .await+ .unwrap();+ assert_eq!(saved.state, MountState::Configured);+ let state = bx.info().await.unwrap();+ assert_eq!((state.status, state.pid), (BoxStatus::Configured, None));+ (bx.id().to_string(), saved)+ };+ lab.release().await;+ let ask = serde_json::to_string(&(&lab.home.path, &id, saved)).unwrap();+ let child = tokio::process::Command::new(std::env::current_exe().unwrap())+ .args([+ "--exact",+ "offline_declarations_are_read_by_another_process_and_restarted",+ "--ignored",+ ])+ .env(READER, ask)+ .kill_on_drop(true)+ .output();+ let child = tokio::time::timeout(Duration::from_secs(120), child)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(+ child.status.code(),+ Some(23),+ "{}{}",+ String::from_utf8_lossy(&child.stdout),+ String::from_utf8_lossy(&child.stderr)+ );+ lab.runtime = Some(open(&lab.home.path));+ let bx = lab.handle(&id).await;+ bx.start().await.unwrap();+ first_process(&bx, 1, "offline").await;+ let old = bx.mount();+ old.add(request(late.path(), "/late", false)).await.unwrap();+ bx.stop().await.unwrap();+ let next = lab.handle(&id).await;+ next.start().await.unwrap();+ first_process(&next, 2, "offline").await;+ assert_eq!(run(&next, "cat /late/probe").await, (0, "late".into()));+ assert!(matches!(+ old.remove("/work").await,+ Err(BoxliteError::Stopped(_))+ ));+ next.mount().remove("/work").await.unwrap();+ next.mount().remove("/late").await.unwrap();+ next.stop().await.unwrap();+ let last = lab.handle(&id).await;+ last.start().await.unwrap();+ first_process(&last, 3, "absent").await;+ demand(&last, "test ! -e /late/probe").await;+ last.stop().await.unwrap();+ })+ .await;+}++#[tokio::test]+#[ignore = "requires native runtime, KVM and VMM_KERNEL"]+async fn failed_boots_name_the_target_and_allow_offline_repair() {+ scenario(async |lab| {+ let data = source("data");+ let gone = data.path().join("gone");+ std::fs::create_dir(&gone).unwrap();+ let bx = lab.create(options()).await;+ bx.mount().add(request(&gone, "/work", false)).await.unwrap();+ std::fs::remove_dir(&gone).unwrap();+ assert!(bx.start().await.unwrap_err().to_string().contains("/work"));+ let bx = lab.handle(bx.id().as_str()).await;+ assert!(bx.info().await.unwrap().pid.is_none());+ bx.mount().remove("/work").await.unwrap();+ bx.start().await.unwrap();+ demand(&bx, "mkdir -p /work /mnt/behind; printf kept > /work/occupied; ln -s /mnt/behind /mnt/link").await;+ bx.stop().await.unwrap();+ for target in ["/work", "/mnt/link"] {+ let idle = lab.handle(bx.id().as_str()).await;+ idle.mount().add(request(data.path(), target, false)).await.unwrap();+ assert!(idle.start().await.unwrap_err().to_string().contains(target));+ let repair = lab.handle(bx.id().as_str()).await;+ assert!(repair.info().await.unwrap().pid.is_none());+ repair.mount().remove(target).await.unwrap();+ }+ let repaired = lab.handle(bx.id().as_str()).await;+ repaired.start().await.unwrap();+ demand(&repaired, "test \"$(cat /work/occupied)\" = kept; test -L /mnt/link; test -z \"$(ls -A /mnt/behind)\"").await;+ repaired.stop().await.unwrap();+ }).await;+}++#[tokio::test]+#[ignore = "requires native runtime, KVM and VMM_KERNEL"]+async fn interrupted_and_committed_changes_choose_the_next_boot() {+ scenario(async |lab| {+ let data = source("recovered");+ for adding in [true, false] {+ let bx = lab.create(options()).await;+ bx.start().await.unwrap();+ if !adding {+ bx.mount()+ .add(request(data.path(), "/work", false))+ .await+ .unwrap();+ }+ let abort = CommitAbort::arm(&lab.home.path, bx.id().as_str(), adding);+ let result = if adding {+ bx.mount()+ .add(request(data.path(), "/work", false))+ .await+ .map(|_| ())+ } else {+ bx.mount().remove("/work").await+ };+ let error = result.unwrap_err();+ assert!(+ matches!(error, BoxliteError::Database(_))+ && error.to_string().contains("mount commit interrupted"),+ "{error}"+ );+ drop(abort);+ bx.stop().await.unwrap();+ let next = lab.handle(bx.id().as_str()).await;+ assert_eq!(+ next.mount()+ .get("/work")+ .await+ .unwrap()+ .map(|entry| entry.state),+ (!adding).then_some(MountState::Configured)+ );+ next.start().await.unwrap();+ first_process(&next, 2, if adding { "absent" } else { "recovered" }).await;+ if adding {+ next.mount()+ .add(request(data.path(), "/work", false))+ .await+ .unwrap();+ }+ assert_eq!(run(&next, "cat /work/probe").await, (0, "recovered".into()));+ next.stop().await.unwrap();+ let idle = lab.handle(bx.id().as_str()).await;+ idle.mount().remove("/work").await.unwrap();+ idle.start().await.unwrap();+ first_process(&idle, 3, "absent").await;+ idle.stop().await.unwrap();+ }++ // A caller nobody waits for does not undo its change: the admitted task+ // commits, and the next boot follows the commit.+ let bx = lab.create(options()).await;+ bx.start().await.unwrap();+ let (handle, directory) = (bx.mount(), request(data.path(), "/work", false));+ let caller = tokio::spawn(async move { handle.add(directory).await });+ wait_for_mount(&bx, "/work", Some(MountState::Mounted)).await;+ caller.abort();+ let _ = caller.await;+ bx.stop().await.unwrap();+ let next = lab.handle(bx.id().as_str()).await;+ assert_eq!(+ next.mount().get("/work").await.unwrap().unwrap().state,+ MountState::Configured+ );+ next.start().await.unwrap();+ first_process(&next, 2, "recovered").await;+ let handle = next.mount();+ let caller = tokio::spawn(async move { handle.remove("/work").await });+ wait_for_mount(&next, "/work", None).await;+ caller.abort();+ let _ = caller.await;+ next.stop().await.unwrap();+ let last = lab.handle(bx.id().as_str()).await;+ last.start().await.unwrap();+ first_process(&last, 3, "absent").await;+ assert!(matches!(+ last.mount().remove("/work").await,+ Err(BoxliteError::NotFound(_))+ ));+ last.stop().await.unwrap();+ })+ .await;+}++#[tokio::test]+#[ignore = "requires native runtime, KVM and VMM_KERNEL"]+async fn a_directory_stays_mounted_while_a_mount_sits_below_it() {+ scenario(async |lab| {+ let (data, nested) = (source("above"), source("below"));+ let mut opts = options();+ opts.mounts.push(MountSpec::bind_mount(+ data.path().to_str().unwrap(),+ "/work",+ ));+ opts.mounts.push(MountSpec::bind_mount(+ nested.path().to_str().unwrap(),+ "/work/nested",+ ));+ let bx = lab.create(opts).await;+ bx.start().await.unwrap();+ assert_eq!(+ run(&bx, "cat /work/nested/probe").await,+ (0, "below".into())+ );++ // The guest keeps a parent mounted while a child is mounted, so the+ // refusal comes before anything is marked.+ let error = bx.mount().remove("/work").await.unwrap_err();+ assert!(+ matches!(error, BoxliteError::InvalidState(_))+ && error.to_string().contains("/work/nested"),+ "{error}"+ );+ assert_eq!(+ bx.mount()+ .get("/work")+ .await+ .unwrap()+ .map(|mount| mount.state),+ Some(MountState::Mounted)+ );+ assert_eq!(run(&bx, "cat /work/probe").await, (0, "above".into()));++ // The child goes first, then the parent.+ bx.mount().remove("/work/nested").await.unwrap();+ bx.mount().remove("/work").await.unwrap();+ assert!(bx.mount().list().await.unwrap().is_empty());+ bx.stop().await.unwrap();+ })+ .await;+}++#[tokio::test]+#[ignore = "requires native runtime, KVM and VMM_KERNEL"]+async fn two_mounts_at_one_destination_are_refused_before_the_workload_runs() {+ scenario(async |lab| {+ let (first, second) = (source("first"), source("second"));+ let mut opts = options();+ for (data, target) in [(first.path(), "/work"), (second.path(), "/work/")] {+ opts.mounts+ .push(MountSpec::bind_mount(data.to_str().unwrap(), target));+ }+ let bx = lab.create(opts).await;+ // Neither of two mounts on one directory could be detached alone.+ let error = bx.start().await.unwrap_err().to_string();+ assert!(error.contains("another declared directory"), "{error}");+ assert!(bx.info().await.unwrap().pid.is_none());+ })+ .await;+}++#[tokio::test]+#[ignore = "requires native runtime, KVM and VMM_KERNEL"]+async fn directories_nested_at_runtime_come_back_in_order_after_a_restart() {+ scenario(async |lab| {+ let (above, below) = (source("above"), source("below"));+ let bx = lab.create(options()).await;+ let id = bx.id().to_string();+ bx.start().await.unwrap();+ bx.mount()+ .add(request(above.path(), "/nest", false))+ .await+ .unwrap();+ bx.mount()+ .add(request(below.path(), "/nest/child", false))+ .await+ .unwrap();+ assert_eq!(run(&bx, "cat /nest/child/probe").await, (0, "below".into()));+ bx.stop().await.unwrap();++ // Mounts apply in list order at start, so the parent comes first.+ let bx = lab.handle(&id).await;+ bx.start().await.unwrap();+ assert_eq!(+ run(&bx, "cat /nest/probe /nest/child/probe").await,+ (0, "abovebelow".into())+ );+ bx.mount().remove("/nest/child").await.unwrap();+ bx.mount().remove("/nest").await.unwrap();+ assert!(bx.mount().list().await.unwrap().is_empty());+ bx.stop().await.unwrap();+ })+ .await;+}diff --git a/src/guest/README.md b/src/guest/README.mdindex 49edab11e..96993df36 100644--- a/src/guest/README.md+++ b/src/guest/README.md@@ -26,11 +26,14 @@ later RPCs.Aggregate Mount and Detach require a container whose capability bounding setexcludes `CAP_SYS_ADMIN`. Aggregate Mount also requires that the target mount-namespace belong to the guest agent's user namespace. The agent rejects-unsupported targets before publishing a mount. Mount replay and Detach must-refer to the recorded namespace. If init has switched namespaces, the agent-reports a failed precondition and retains the record. Legacy share delivery is-read-only.+namespace belong to the guest agent's user namespace. Before publishing a+mount, the agent rejects unsupported targets and any destination at, below or+above `/proc`, `/dev`, `/sys` or `/tmp`, which the runtime mounts itself. Mount+replay and Detach start in the recorded namespace: if init has switched, the+agent reports a failed precondition and retains the record. The namespace is+confirmed again once the mount changed; a failure then leaves the outcome+unknown, so the agent reports `INTERNAL` and retains the record. Legacy share+delivery is read-only.The agent clones the export with `open_tree`, applies recursive read-only flagswhen requested, and moves the clone into the running container's mount namespace@@ -39,6 +42,27 @@ component without following symlinks. Guest writable mode does not override thehost export's permission policy. A retry must match the incarnation's source,mode, destination, and actual mounted tree.+A `BindMount` with a `record_key` on `Container.Init` is mounted by the container+runtime like any whole-directory bind. Once the container is created, before+init runs, the agent records that mount under the key: it resolves the+destination through init's `/proc/<pid>/root` the way the runtime did, keeps an+`O_PATH` descriptor on the mount point, and reads the mount ID. It also notes+where the mounts without a record sit, so a later Mount cannot cover them.+`Detach` then handles it like an attached mount. A `BindMount` with `added` set+was saved while the box was stopped: its target must be empty and reached+through no symbolic link. Mounts apply in list order, as on Linux: a saved+directory may sit below an earlier mount and have later ones below it, but it+must not cover an earlier mount, and no later mount may cover it. Its owner is+not remapped. `Ping` advertises this with `records_boot_mounts`, which is set+only where the kernel identifies a mount namespace. A guest without it+receives the directories created with the box as plain binds.++Two recorded mounts that resolve to one mount, through an image link between+their destinations or two spellings of one target, fail `Container.Init`:+neither could be detached alone. `Detach` also refuses a recorded directory+that has one of the runtime's other mounts at or below it, files and volumes+included, because a lazy detach would take that mount along.+The incarnation record retains the original cloned-tree descriptor. This pinsthe mounted tree rather than the directory underneath it, preventing mount-IDreuse while the record is attached. The agent reads that tree's checkeddiff --git a/src/guest/src/container/lifecycle.rs b/src/guest/src/container/lifecycle.rsindex 81706c336..7c8852001 100644--- a/src/guest/src/container/lifecycle.rs+++ b/src/guest/src/container/lifecycle.rs@@ -163,7 +163,7 @@ impl Container {// Auto-idmap: remap volume UIDs when host owner differs from container user.// Uses a full-range swap mapping so all UIDs remain valid (no overflow).for mount in &user_mounts {- if mount.read_only || mount.owner_uid == uid {+ if mount.read_only || mount.added || mount.owner_uid == uid {continue;}let uid_mappings =diff --git a/src/guest/src/container/spec.rs b/src/guest/src/container/spec.rsindex bff748c36..a4e13db6d 100644--- a/src/guest/src/container/spec.rs+++ b/src/guest/src/container/spec.rs@@ -76,6 +76,8 @@ pub struct UserMount {pub owner_uid: u32,/// Owner GID of host directory (for auto-idmap)pub owner_gid: u32,+ /// Saved while the box was stopped: its owner is never remapped.+ pub added: bool,}/// Device nodes the host asked to republish inside the container, resolved@@ -1736,6 +1738,7 @@ mod tests {read_only: false,owner_uid: 0,owner_gid: 0,+ added: false,}];let spec = create_oci_spec(@@ -1779,4 +1782,46 @@ mod tests {);}}++ #[test]+ fn standard_mounts_stay_under_their_reserved_roots() {+ use boxlite_shared::constants::STANDARD_MOUNT_TARGETS;++ let mounts = build_standard_mounts(+ Path::new("/bundle"),+ MountOverride {+ source: "none".into(),+ options: vec!["ro".into()],+ },+ true,+ )+ .unwrap();+ let destinations: Vec<_> = mounts+ .iter()+ .map(|mount| mount.destination().as_path())+ .collect();++ // A directory delivered at runtime is refused around each of these+ // roots, so every standard mount has to be under one, except the+ // `/etc` files: a directory cannot land on a file.+ for destination in destinations+ .iter()+ .filter(|destination| !destination.starts_with("/etc"))+ {+ assert!(+ STANDARD_MOUNT_TARGETS+ .iter()+ .any(|root| destination.starts_with(root)),+ "{destination:?} is not under a reserved root"+ );+ }+ for root in STANDARD_MOUNT_TARGETS {+ assert!(+ destinations+ .iter()+ .any(|destination| destination.starts_with(root)),+ "no standard mount under {root}"+ );+ }+ }}diff --git a/src/guest/src/service/container.rs b/src/guest/src/service/container.rsindex 07ae02a38..be8ed39f6 100644--- a/src/guest/src/service/container.rs+++ b/src/guest/src/service/container.rs@@ -49,6 +49,140 @@ fn init_error(context: &str, error: &BoxliteError) -> ContainerInitError {}}+/// A mount the container runtime makes for a declared directory. Once the+/// container exists, the guest records its identity under `key`.+struct RecordedMount {+ key: String,+ source: PathBuf,+ destination: PathBuf,+ read_only: bool,+}++/// A directory saved while the box was stopped keeps the rules of its first+/// delivery: the target is created when missing, and must then be empty and+/// be reached through no symbolic link.+fn require_empty_target(rootfs: &Path, destination: &Path) -> BoxliteResult<()> {+ let mut path = rootfs.to_path_buf();+ for component in destination.components().skip(1) {+ path.push(component);+ match std::fs::symlink_metadata(&path) {+ Ok(metadata) if metadata.is_dir() => (),+ Ok(_) => {+ return Err(BoxliteError::InvalidState(format!(+ "{destination:?} is not reached through directories only"+ )));+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ std::fs::create_dir(&path)?;+ }+ Err(error) => return Err(error.into()),+ }+ }+ let mut entries = std::fs::read_dir(&path)?;+ match entries.next() {+ None => Ok(()),+ Some(_) => Err(BoxliteError::InvalidState(format!(+ "{destination:?} already has entries"+ ))),+ }+}++/// Whether the mount at `target`, applied at `position`, and the mount at+/// `other`, applied at `index`, would hide one another. Mounts apply in list+/// order, so where they overlap the later one covers the earlier.+fn hides(index: usize, position: usize, target: &Path, other: &Path) -> bool {+ (index < position && other.starts_with(target))+ || (index > position && target.starts_with(other))+}++/// Where `destination` sits once the mounts before it are in place: below an+/// earlier one, it is that mount's source with the rest of the path.+fn effective_target(destination: &Path, earlier: &[(String, PathBuf)]) -> Option<PathBuf> {+ let (target, source) = earlier+ .iter()+ .filter(|(target, _)| destination.starts_with(target.as_str()))+ .max_by_key(|(target, _)| target.len())?;+ Some(source.join(destination.strip_prefix(target).unwrap_or(Path::new(""))))+}++/// Refuse a saved directory that would hide a mount, or whose target has+/// entries where it lands. Mounts apply in list order, as on Linux: a saved+/// directory may sit below an earlier mount and have later ones below it, but+/// it must not cover an earlier mount, and a later one must not cover it.+/// Below an earlier mount its target is that mount's source.+fn check_saved_target(+ destination: &str,+ position: usize,+ mounts: &[BindMount],+ earlier: &[(String, PathBuf)],+ rootfs: &Path,+) -> BoxliteResult<()> {+ let target = Path::new(destination);+ for (index, other) in mounts.iter().enumerate() {+ let other_path = Path::new(&other.destination);+ if other.destination == destination || !hides(index, position, target, other_path) {+ continue;+ }+ return Err(BoxliteError::InvalidState(if index < position {+ format!(+ "{destination} would cover the earlier mount at {}",+ other_path.display()+ )+ } else {+ format!(+ "the later mount at {} would cover {destination}",+ other_path.display()+ )+ }));+ }+ match effective_target(target, earlier) {+ Some(below) => require_empty_target(Path::new("/"), &below).map_err(|error| {+ BoxliteError::InvalidState(format!("{destination} is below an earlier mount: {error}"))+ }),+ None => require_empty_target(rootfs, target),+ }+}++/// Record each mount the runtime made for a declared directory, under the+/// identity every process of the container will find, and note where its other+/// mounts sit. Init is created and has not run, so nothing has touched these+/// mounts since the runtime made them.+async fn record_mounts(+ container: &Container,+ mounts: Vec<RecordedMount>,+ unrecorded: Vec<PathBuf>,+) -> BoxliteResult<()> {+ if mounts.is_empty() && unrecorded.is_empty() {+ return Ok(());+ }+ // Adopting a mount needs the capability; noting where the others sit does+ // not.+ if !mounts.is_empty() {+ container.ensure_runtime_mounts_supported()?;+ }+ let init = container.init_pid().ok_or_else(|| {+ BoxliteError::InvalidState("the container is created but its init process is gone".into())+ })?;+ let target = Target::open(init)?;+ let mut attacher = container.attacher().write_owned().await;+ tokio::task::spawn_blocking(move || {+ for mount in mounts {+ attacher.adopt_runtime(+ &mount.key,+ &mount.source,+ &target,+ &mount.destination,+ mount.read_only,+ )?;+ }+ attacher.note_unrecorded(&target, &unrecorded)?;+ Ok::<(), BoxliteError>(())+ })+ .await+ .map_err(|error| BoxliteError::Internal(format!("mount record task failed: {error}")))??;+ Ok(())+}+#[derive(Debug, PartialEq)]enum BindMountSource<'a> {WholeDirectory,@@ -417,8 +551,11 @@ impl ContainerService for GuestServer {// Keep every resolved volume subpath mount alive until startup is done.let mut resolved_mounts = Vec::new();+ let mut recorded = Vec::new();+ let mut unrecorded = Vec::new();let mut user_mounts = Vec::with_capacity(init_req.mounts.len());- for m in &init_req.mounts {+ let mut earlier: Vec<(String, PathBuf)> = Vec::new();+ for (position, m) in init_req.mounts.iter().enumerate() {let volume_dir = container_layout.volume_dir(&m.volume_name);let selected = match bind_mount_source(m) {Ok(selected) => selected,@@ -458,12 +595,41 @@ impl ContainerService for GuestServer {}}};+ if !m.record_key.is_empty() {+ recorded.push(RecordedMount {+ key: m.record_key.clone(),+ source: source.clone(),+ destination: PathBuf::from(&m.destination),+ read_only: m.read_only,+ });+ } else {+ unrecorded.push(PathBuf::from(&m.destination));+ }+ if m.added {+ let checked = check_saved_target(+ &m.destination,+ position,+ &init_req.mounts,+ &earlier,+ &bundle_rootfs,+ );+ if let Err(error) = checked {+ return Ok(Response::new(ContainerInitResponse {+ result: Some(container_init_response::Result::Error(init_error(+ "check the target of a saved directory",+ &error,+ ))),+ }));+ }+ }+ earlier.push((m.destination.clone(), source.clone()));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,+ added: m.added,});}@@ -538,6 +704,18 @@ impl ContainerService for GuestServer {// against it, and a client attach to it, before it runs.debug!(container_id = %container_id, "Container created");+ // The runtime made the mounts of declared directories. Their+ // identity is recorded now: the container is created and+ // nothing in it has run.+ if let Err(error) = record_mounts(&container, recorded, unrecorded).await {+ return Ok(Response::new(ContainerInitResponse {+ result: Some(container_init_response::Result::Error(init_error(+ "record the mount of a declared directory",+ &error,+ ))),+ }));+ }+info!(container_id = %container_id,"✅ Container started successfully and ready for exec"@@ -1216,4 +1394,71 @@ mod tests {assert_eq!(mount_status(error).code(), code);}}++ #[test]+ fn mounts_in_list_order_hide_one_another_only_when_out_of_order() {+ let (parent, child) = (Path::new("/work"), Path::new("/work/nested"));+ // A saved directory below an earlier mount, or above a later one, hides nothing.+ assert!(!hides(0, 1, child, parent));+ assert!(!hides(1, 0, parent, child));+ // An earlier mount below it, or a later one above it, would be covered.+ assert!(hides(0, 1, parent, child));+ assert!(hides(1, 0, child, parent));+ assert!(!hides(0, 1, Path::new("/work"), Path::new("/workday")));+ }++ #[test]+ fn a_saved_directory_below_an_earlier_mount_is_checked_in_that_mount() {+ let earlier = [+ ("/work".to_string(), PathBuf::from("/share/work")),+ ("/work/nested".to_string(), PathBuf::from("/share/nested")),+ ];+ assert_eq!(+ effective_target(Path::new("/work/nested/deeper"), &earlier),+ Some(PathBuf::from("/share/nested/deeper"))+ );+ assert_eq!(+ effective_target(Path::new("/work/other"), &earlier),+ Some(PathBuf::from("/share/work/other"))+ );+ assert_eq!(effective_target(Path::new("/data"), &earlier), None);+ }++ #[tokio::test]+ async fn mounts_without_a_record_are_still_noted() {+ use crate::container::Container;+ use libcontainer::container::{ContainerStatus, State};++ // A created container whose init is this test's own process.+ let home = tempfile::tempdir().unwrap();+ let id = home+ .path()+ .file_name()+ .unwrap()+ .to_string_lossy()+ .into_owned();+ State::new(+ &id,+ ContainerStatus::Running,+ Some(i32::try_from(std::process::id()).unwrap()),+ home.path().join("bundle"),+ )+ .save(home.path())+ .unwrap();+ let container = Container::for_unit_test(+ &id,+ home.path().parent().unwrap().to_path_buf(),+ home.path().join("bundle"),+ );++ // Only mounts the runtime made without a record: there is nothing to+ // adopt, yet a later runtime mount must not cover them.+ record_mounts(&container, Vec::new(), vec![PathBuf::from("/tmp")])+ .await+ .unwrap();+ assert_eq!(+ container.attacher().read().await.unrecorded(),+ &[PathBuf::from("/tmp")]+ );+ }}diff --git a/src/guest/src/service/guest.rs b/src/guest/src/service/guest.rsindex 80c479b50..7228596e5 100644--- a/src/guest/src/service/guest.rs+++ b/src/guest/src/service/guest.rs@@ -89,6 +89,7 @@ impl GuestService for GuestServer {Ok(Response::new(PingResponse {version: env!("CARGO_PKG_VERSION").to_string(),safe_managed_volume_sub_path: true,+ records_boot_mounts: crate::storage::attach::identifies_namespaces(),}))}diff --git a/src/guest/src/storage/attach.rs b/src/guest/src/storage/attach.rsindex 7aee90deb..57dbb5c2e 100644--- a/src/guest/src/storage/attach.rs+++ b/src/guest/src/storage/attach.rs@@ -20,7 +20,7 @@//! past that the agent kills it, so a late child never mounts.use std::collections::HashMap;-use std::ffi::{CStr, CString, OsStr};+use std::ffi::{CStr, CString, OsStr, OsString};use std::fs::File;use std::io;use std::num::NonZeroU64;@@ -30,6 +30,7 @@ use std::os::unix::fs::MetadataExt;use std::path::{Component, Path, PathBuf};use std::time::{Duration, Instant};+use boxlite_shared::constants::{path_is_below, reserved_mount_target};use boxlite_shared::errors::{BoxliteError, BoxliteResult};use nix::fcntl::OFlag;use nix::libc;@@ -50,6 +51,8 @@ const NR_PIDFD_SEND_SIGNAL: libc::c_long = 424;const NR_CLONE3: libc::c_long = 435;const NR_CLOSE_RANGE: libc::c_long = 436;const NR_STATMOUNT: libc::c_long = 457;+/// Symbolic links one destination may resolve through, the kernel's own limit.+const MAX_SYMLINKS: usize = 40;const P_PIDFD: libc::idtype_t = 3;/// Accept only an absolute path of normal components other than `/`, shorter@@ -93,12 +96,18 @@ pub(crate) struct Attacher {/// Pidfd of a killed child that had not exited yet.straggler: Option<OwnedFd>,runtime: HashMap<String, RuntimeMount>,+ /// Where the mounts the runtime made for files and volumes sit, links+ /// resolved. Detaching a recorded directory above one would take it along.+ unrecorded: Vec<PathBuf>,}#[derive(Debug)]struct RuntimeMount {source: PathBuf,destination: PathBuf,+ /// Where the mount sits in the container, links resolved. It differs from+ /// `destination` only for a mount the container runtime made at creation.+ mount_point: PathBuf,read_only: bool,namespace_id: Option<NonZeroU64>,// Retain the tree while it may still be published, even if confirmation was lost.@@ -193,10 +202,105 @@ impl Target {Ok(id)}- fn check_current_namespace(&self, id: NonZeroU64) -> BoxliteResult<()> {- Self::open(self.pid)?.check_namespace(Some(id))?;- Ok(())+ /// Confirm, once the mount changed, that the process is still in the+ /// namespace `expected`: the held descriptor can outlive the process's+ /// membership in it. A failure here leaves the outcome unknown, so it is+ /// no refusal: the caller undoes the mount or retries.+ fn check_after_change(&self, step: &'static str, expected: NonZeroU64) -> BoxliteResult<()> {+ Self::open(self.pid)+ .and_then(|current| current.check_namespace(Some(expected)))+ .map(|_| ())+ .map_err(|error| {+ BoxliteError::Internal(format!(+ "{step}, but the container's mount namespace could not be confirmed: {error}"+ ))+ })+ }+}++/// Whether this kernel identifies a mount namespace, which recording a+/// mount needs. The guest advertises it per ping: one read of its own+/// namespace says whether the container's can be read.+pub(crate) fn identifies_namespaces() -> bool {+ Target::open(nix::unistd::getpid())+ .and_then(|own| own.namespace_id())+ .is_ok()+}++/// Resolve an OCI destination against the created container's held root.+/// Detach needs its absolute in-container path even when the image uses links.+fn resolve_in_root(root: &File, destination: &Path) -> BoxliteResult<PathBuf> {+ // Components to walk, innermost last: the next one is popped from the end.+ let queue = |pending: &mut Vec<OsString>, path: &Path| {+ pending.extend(+ path.components()+ .filter_map(|component| match component {+ Component::Normal(name) => Some(name.to_os_string()),+ Component::ParentDir => Some("..".into()),+ Component::RootDir | Component::CurDir | Component::Prefix(_) => None,+ })+ .rev(),+ );+ };+ let unreachable = |error: std::io::Error| {+ BoxliteError::InvalidState(format!(+ "{} is not reachable in the container: {error}",+ destination.display()+ ))+ };+ let root = PathBuf::from(format!("/proc/self/fd/{}", root.as_raw_fd()));+ let mut resolved = PathBuf::new();+ let mut pending = Vec::new();+ queue(&mut pending, destination);+ let mut links = 0;+ while let Some(component) = pending.pop() {+ if component == ".." {+ resolved.pop();+ continue;+ }+ resolved.push(component);+ let path = root.join(&resolved);+ let metadata = std::fs::symlink_metadata(&path).map_err(unreachable)?;+ if !metadata.file_type().is_symlink() {+ continue;+ }+ links += 1;+ if links > MAX_SYMLINKS {+ return Err(BoxliteError::InvalidState(format!(+ "{} resolves through more than {MAX_SYMLINKS} symbolic links",+ destination.display()+ )));+ }+ let link = std::fs::read_link(&path).map_err(unreachable)?;+ resolved.pop();+ if link.is_absolute() {+ resolved.clear();+ }+ queue(&mut pending, &link);+ }+ if resolved.as_os_str().is_empty() {+ return Err(BoxliteError::InvalidState(format!(+ "{} resolves to the container root",+ destination.display()+ )));}+ Ok(resolved)+}++/// Open the resolved target under the same root. A concurrent change to a+/// path component must fail before the guest records an unrelated mount.+fn open_mounted(root: &File, relative: &Path) -> BoxliteResult<File> {+ use rustix::fs::{openat2, Mode, OFlags, ResolveFlags};++ openat2(+ root,+ relative,+ OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC,+ Mode::empty(),+ ResolveFlags::BENEATH | ResolveFlags::NO_SYMLINKS,+ )+ .map(File::from)+ .map_err(|error| BoxliteError::Storage(format!("open boot mount {relative:?}: {error}")))}impl Attacher {@@ -205,6 +309,12 @@ impl Attacher {.get(key).is_some_and(|record| record.tree.is_some())}++ #[cfg(test)]+ pub(crate) fn unrecorded(&self) -> &[PathBuf] {+ &self.unrecorded+ }+/// The caller holds the container's attacher write lock across the syscall/// and its metadata update. Tombstones outlive canceled RPC callers.pub(crate) fn attach_runtime(@@ -215,6 +325,13 @@ impl Attacher {destination: &Path,read_only: bool,) -> BoxliteResult<RuntimeAttach> {+ // The runtime mounts its own filesystems before any user mount applies.+ if let Some(root) = reserved_mount_target(destination) {+ return Err(BoxliteError::InvalidArgument(format!(+ "{} is reserved for the container's own mount at {root}",+ destination.display()+ )));+ }if let Some(record) = self.runtime.get(key) {if record.destination != destination|| (record.tree.is_some()@@ -231,7 +348,7 @@ impl Attacher {};let namespace_id = target.check_namespace(record.namespace_id)?;self.check_runtime(target, destination, Mode::Verify(tree.id))?;- target.check_current_namespace(namespace_id)?;+ target.check_after_change("the mount is still in place", namespace_id)?;return Ok(RuntimeAttach {added: false,confirmation: Ok(()),@@ -240,7 +357,9 @@ impl Attacher {if self.runtime.values()- .any(|record| record.tree.is_some() && record.destination == destination)+ // A mount sits where its destination resolves, so that is what a+ // new destination is compared with.+ .any(|record| record.tree.is_some() && record.mount_point == destination){return Err(BoxliteError::InvalidState("destination already has a runtime mount".into(),@@ -255,6 +374,7 @@ impl Attacher {RuntimeMount {source: source.to_owned(),destination: destination.to_owned(),+ mount_point: destination.to_owned(),read_only,namespace_id: Some(namespace_id),tree: Some(tree),@@ -262,10 +382,79 @@ impl Attacher {);Ok(RuntimeAttach {added: true,- confirmation: confirmation.and_then(|()| target.check_current_namespace(namespace_id)),+ confirmation: confirmation+ .and_then(|()| target.check_after_change("the mount was attached", namespace_id)),})}+ /// Record the mount the container runtime installed for `key` at+ /// `destination`, under the identity the container's first process finds.+ /// The container is created and nothing in it has run, so no process has+ /// touched the mount since the runtime made it.+ /// The caller holds the container's attacher write lock.+ pub(crate) fn adopt_runtime(+ &mut self,+ key: &str,+ source: &Path,+ target: &Target,+ destination: &Path,+ read_only: bool,+ ) -> BoxliteResult<()> {+ target.check_runtime_owner()?;+ let namespace_id = target.namespace_id()?;+ let root = File::open(format!("/proc/{}/root", target.pid))?;+ let relative = resolve_in_root(&root, destination)?;+ let fd = open_mounted(&root, &relative)?;+ let id = mount_identity(fd.as_raw_fd()).map_err(|code| {+ BoxliteError::Storage(format!(+ "statx the mount at {}: {}",+ destination.display(),+ io::Error::from_raw_os_error(code)+ ))+ })?;+ // Two declared directories can land on one mount: an image link+ // between their destinations, or two spellings of one target. Neither+ // could be detached alone, so the container does not start.+ if self+ .runtime+ .values()+ .any(|record| record.tree.as_ref().is_some_and(|tree| tree.id == id))+ {+ return Err(BoxliteError::InvalidState(format!(+ "{} is mounted where another declared directory already is",+ destination.display()+ )));+ }+ self.runtime.insert(+ key.to_owned(),+ RuntimeMount {+ source: source.to_owned(),+ destination: destination.to_owned(),+ mount_point: Path::new("/").join(relative),+ read_only,+ namespace_id: Some(namespace_id),+ tree: Some(MountedTree { fd: fd.into(), id }),+ },+ );+ Ok(())+ }++ /// Note where the runtime's other mounts sit, links resolved, so that a+ /// recorded directory above one of them is not detached from under it.+ /// The caller holds the container's attacher write lock.+ pub(crate) fn note_unrecorded(+ &mut self,+ target: &Target,+ destinations: &[PathBuf],+ ) -> BoxliteResult<()> {+ let root = File::open(format!("/proc/{}/root", target.pid))?;+ for destination in destinations {+ self.unrecorded+ .push(Path::new("/").join(resolve_in_root(&root, destination)?));+ }+ Ok(())+ }+pub(crate) fn detach_runtime(&mut self,key: &str,@@ -287,6 +476,7 @@ impl Attacher {RuntimeMount {source: PathBuf::new(),destination: destination.to_owned(),+ mount_point: destination.to_owned(),read_only: false,namespace_id: None,tree: None,@@ -294,11 +484,26 @@ impl Attacher {);return Ok(false);}- if self.runtime.values().any(|record| {- record.tree.is_some()- && record.destination != destination- && record.destination.starts_with(destination)- }) {+ // `mount_point` is where each mount sits with links resolved, so two+ // spellings of one directory still compare as parent and child.+ let mount_point = self.runtime[key].mount_point.clone();+ // A mount the runtime made for a file or a volume leaves only with the+ // container, so a recorded directory above it stays too.+ if self+ .unrecorded+ .iter()+ .any(|path| path.starts_with(&mount_point))+ {+ return Err(BoxliteError::InvalidState(format!(+ "a mount the box was created with sits at or below {}; stop the box to remove this directory",+ mount_point.display()+ )));+ }+ if self+ .runtime+ .values()+ .any(|record| record.tree.is_some() && path_is_below(&record.mount_point, &mount_point))+ {return Err(BoxliteError::InvalidState("detach runtime descendants first".into(),));@@ -306,7 +511,7 @@ impl Attacher {let record = &self.runtime[key];let namespace_id = target.check_namespace(record.namespace_id)?;let id = record.tree.as_ref().expect("attached tree").id;- if let Err(error) = self.check_runtime(target, destination, Mode::Detach(id)) {+ if let Err(error) = self.check_runtime(target, &mount_point, Mode::Detach(id)) {let tree = self.runtime[key].tree.as_ref().expect("attached tree");// A different tree at the path does not prove the original was detached.let absent = matches!(tree.is_mounted_in(namespace_id.get()), Ok(false));@@ -314,8 +519,7 @@ impl Attacher {return Err(error);}}- // The helper's namespace FD can outlive init's membership in it.- target.check_current_namespace(namespace_id)?;+ target.check_after_change("the mount was detached", namespace_id)?;let record = self.runtime.get_mut(key).expect("checked incarnation");record.tree = None;Ok(true)@@ -346,10 +550,15 @@ impl Attacher {runtime_namespace: Option<NonZeroU64>,) -> BoxliteResult<(MountedTree, BoxliteResult<()>)> {validate_destination(destination)?;+ // A mount applied here comes last, so where it overlaps an existing+ // one it covers it: the runtime's recorded directories and its other+ // mounts alike. Either could then no longer leave on its own.+ let covers = |mount_point: &Path| mount_point.starts_with(destination);if self.runtime.values()- .any(|record| record.tree.is_some() && record.destination.starts_with(destination))+ .any(|record| record.tree.is_some() && covers(&record.mount_point))+ || self.unrecorded.iter().any(|path| covers(path)){return Err(BoxliteError::InvalidState("destination would cover a runtime mount".into(),@@ -1248,6 +1457,17 @@ mod tests {}}+ /// A stand-in for the root of a container that takes runtime mounts.+ /// `attach_runtime` refuses a destination at, below or above a mount the+ /// container provides itself, and the system temporary directory is `/tmp`+ /// on CI and on most hosts.+ fn runtime_mount_root() -> tempfile::TempDir {+ tempfile::Builder::new()+ .prefix("boxlite-guest-runtime-mount.")+ .tempdir_in("/var/tmp")+ .expect("a root outside the container's own mounts")+ }+#[test]fn canceled_incarnation_never_attaches_or_detaches_another_mount() {let target = Target::open(nix::unistd::getpid()).unwrap();@@ -1273,12 +1493,45 @@ mod tests {.is_err());}+ #[test]+ fn a_mount_of_the_box_below_a_directory_keeps_it_attached() {+ let target = Target::open(nix::unistd::getpid()).unwrap();+ let root = tempfile::tempdir().unwrap();+ let directory = root.path().join("data");+ fs::create_dir(&directory).unwrap();+ fs::write(directory.join("config.yml"), b"kept").unwrap();+ let mut attacher = Attacher::default();+ attacher+ .note_unrecorded(&target, &[directory.join("config.yml")])+ .unwrap();+ // The record of a directory the runtime mounted. The guard reads only+ // where it sits, before any namespace is entered.+ attacher.runtime.insert(+ "data".into(),+ RuntimeMount {+ source: PathBuf::new(),+ destination: directory.clone(),+ mount_point: directory.clone(),+ read_only: false,+ namespace_id: None,+ tree: Some(MountedTree {+ fd: OwnedFd::from(File::open("/").unwrap()),+ id: 0,+ }),+ },+ );+ let error = attacher+ .detach_runtime("data", &target, &directory)+ .unwrap_err();+ assert!(error.to_string().contains("sits at or below"), "{error}");+ }+#[test]#[ignore = "needs root in a private mount namespace: make test:guest-perms"]fn privileged_detach_can_recover_an_unconfirmed_attachment() {let source = tempfile::tempdir().unwrap();fs::write(source.path().join("marker"), b"mounted").unwrap();- let root = tempfile::tempdir().unwrap();+ let root = runtime_mount_root();let destination = root.path().join("mount");let holder = NamespaceHolder::spawn();let target = Target::open(holder.pid).unwrap();@@ -1304,7 +1557,7 @@ mod tests {fn privileged_detach_confirms_absence_after_its_result_is_lost() {let source = tempfile::tempdir().unwrap();fs::write(source.path().join("marker"), b"mounted").unwrap();- let root = tempfile::tempdir().unwrap();+ let root = runtime_mount_root();let destination = root.path().join("mount");let holder = NamespaceHolder::spawn();let target = Target::open(holder.pid).unwrap();@@ -1338,7 +1591,7 @@ mod tests {fn privileged_detach_refuses_a_different_namespace() {let source = tempfile::tempdir().unwrap();fs::write(source.path().join("marker"), b"original").unwrap();- let root = tempfile::tempdir().unwrap();+ let root = runtime_mount_root();let destination = root.path().join("mount");let mut attacher = Attacher::default();{@@ -1369,7 +1622,7 @@ mod tests {fn privileged_incarnation_replay_and_replacement_are_safe() {let source = tempfile::tempdir().unwrap();fs::write(source.path().join("marker"), b"runtime").unwrap();- let root = tempfile::tempdir().unwrap();+ let root = runtime_mount_root();let destination = root.path().join("mount");let holder = NamespaceHolder::spawn();let target = Target::open(holder.pid).unwrap();@@ -1544,7 +1797,7 @@ mod tests {fn privileged_writable_attach_allows_writes_until_detached() {let source = tempfile::tempdir().unwrap();fs::write(source.path().join("agent"), b"agent-bytes").unwrap();- let root = tempfile::tempdir().unwrap();+ let root = runtime_mount_root();let destination = root.path().join("opt/boxlite/late");let holder = NamespaceHolder::spawn();let mut attacher = Attacher::default();@@ -1607,7 +1860,7 @@ mod tests {use std::io::Read as _;let source = tempfile::tempdir().unwrap();fs::write(source.path().join("payload"), b"still readable").unwrap();- let root = tempfile::tempdir().unwrap();+ let root = runtime_mount_root();let destination = root.path().join("mounted");let holder = NamespaceHolder::spawn();let target = Target::open(holder.pid).unwrap();@@ -1639,7 +1892,7 @@ mod tests {let replacement = tempfile::tempdir().unwrap();fs::write(original.path().join("marker"), b"original").unwrap();fs::write(replacement.path().join("marker"), b"replacement").unwrap();- let root = tempfile::tempdir().unwrap();+ let root = runtime_mount_root();let ancestor = root.path().join("parent");let renamed = root.path().join("renamed");let destination = ancestor.join("mount");@@ -1745,4 +1998,68 @@ mod tests {};assert!(matches!(error, BoxliteError::NotFound(_)), "{error}");}++ /// The target of a container whose init already exited.+ fn gone_target(namespace: File) -> Target {+ let mut exited = std::process::Command::new("true").spawn().unwrap();+ let pid = Pid::from_raw(i32::try_from(exited.id()).unwrap());+ exited.wait().unwrap();+ Target { pid, namespace }+ }++ #[test]+ fn a_runtime_mount_never_covers_a_mount_the_container_needs() {+ let target = Target::open(nix::unistd::getpid()).unwrap();+ let mut attacher = Attacher::default();+ // Below one root the runtime mounts itself, and at another.+ for destination in ["/dev/null", "/tmp"] {+ let error = attacher+ .attach_runtime(+ "reserved",+ Path::new("/missing"),+ &target,+ Path::new(destination),+ false,+ )+ .unwrap_err();+ assert!(+ matches!(error, BoxliteError::InvalidArgument(_)),+ "{destination}: {error}"+ );+ }+ assert!(attacher.runtime.is_empty());+ // A path that only shares the spelling is another directory: the attach goes on.+ let error = attacher+ .attach_runtime(+ "inside",+ Path::new("/missing"),+ &target,+ Path::new("/tmpwork"),+ false,+ )+ .unwrap_err();+ assert!(+ matches!(&error, BoxliteError::Storage(message) if message.contains("clone")),+ "{error}"+ );+ }++ #[test]+ fn a_namespace_check_after_the_mount_changed_is_no_refusal() {+ let own = Target::open(nix::unistd::getpid()).unwrap();+ let namespace_id = own.namespace_id().unwrap();+ own.check_after_change("the mount was attached", namespace_id)+ .unwrap();++ // Init is gone, so whether the mount reached the container stays+ // unknown. The caller must undo it, not read a refusal.+ let error = gone_target(File::open("/proc/self/ns/mnt").unwrap())+ .check_after_change("the mount was detached", namespace_id)+ .unwrap_err();+ assert!(+ matches!(&error, BoxliteError::Internal(message)+ if message.contains("the mount was detached") && message.contains("gone")),+ "{error}"+ );+ }}diff --git a/src/shared/proto/boxlite/v1/service.proto b/src/shared/proto/boxlite/v1/service.protoindex a2e749dcd..e6132167e 100644--- a/src/shared/proto/boxlite/v1/service.proto+++ b/src/shared/proto/boxlite/v1/service.proto@@ -238,6 +238,9 @@ message PingRequest {}message PingResponse {string version = 1; // Guest agent versionbool safe_managed_volume_sub_path = 2; // Supports pinned managed-volume subdirectories+ // Records the mounts Container.Init makes for declared directories, so the+ // host can detach them with Container.Detach while the container runs.+ bool records_boot_mounts = 3;}message ShutdownRequest {}@@ -477,6 +480,12 @@ message BindMount {string subpath = 6;// Explicit payload interpretation. Old hosts omit this field.BindMountKind kind = 7;+ // When set, the guest records the mount it just made under this key, so the+ // host can detach it later with Container.Detach (export_key).+ string record_key = 8;+ // The directory was saved while the box was stopped: its target must be+ // empty and reached through no symbolic link, and its owner is not remapped.+ bool added = 9;}message ContainerInitResponse {diff --git a/src/shared/src/constants.rs b/src/shared/src/constants.rsindex da3caf4e8..770b28f15 100644--- a/src/shared/src/constants.rs+++ b/src/shared/src/constants.rs@@ -2,6 +2,8 @@//!//! These constants must be identical on both sides of the host-guest boundary.+use std::path::{Component, Path};+/// Container runtime constantspub mod container {/// Default container hostname@@ -57,6 +59,94 @@ pub mod mount_tags {pub const SHARED: &str = "BoxLiteShared";}+/// Roots of the mounts the guest runtime makes for every container before any+/// user mount applies. A directory delivered at runtime must not sit at, below+/// or above one of them: it would hide the container's own mount.+pub const STANDARD_MOUNT_TARGETS: [&str; 4] = ["/dev", "/proc", "/sys", "/tmp"];++/// The mount target as the store, the shim and the guest all spell it: an+/// absolute UTF-8 path of at least one normal component, without `..`. `.` and+/// repeated separators are dropped.+pub fn normalize_target(target: &str) -> Option<String> {+ if !target.starts_with('/') || target.contains('\0') {+ return None;+ }+ let mut components = Vec::new();+ for component in Path::new(target).components() {+ match component {+ Component::RootDir | Component::CurDir => (),+ Component::Normal(name) => components.push(name.to_str()?),+ _ => return None,+ }+ }+ (!components.is_empty()).then(|| format!("/{}", components.join("/")))+}++/// Whether `path` lies below `dir`. Components are compared, so `/devnull` is+/// not below `/dev`.+pub fn path_is_below(path: impl AsRef<Path>, dir: impl AsRef<Path>) -> bool {+ let (path, dir) = (path.as_ref(), dir.as_ref());+ path.strip_prefix(dir).is_ok() && path != dir+}++/// Whether the container paths `a` and `b` are equal, or one lies below the+/// other.+pub fn paths_overlap(a: impl AsRef<Path>, b: impl AsRef<Path>) -> bool {+ let (a, b) = (a.as_ref(), b.as_ref());+ a == b || path_is_below(a, b) || path_is_below(b, a)+}++/// The standard mount root that `target` is at, below or above, if any.+pub fn reserved_mount_target(target: impl AsRef<Path>) -> Option<&'static str> {+ let target = target.as_ref();+ STANDARD_MOUNT_TARGETS+ .into_iter()+ .find(|root| paths_overlap(target, *root))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn container_paths_compare_by_component() {+ for (path, dir) in [("/dev/null", "/dev"), ("/tmp/work", "/tmp")] {+ assert!(path_is_below(path, dir) && paths_overlap(path, dir));+ }+ for (path, dir) in [("/devnull", "/dev"), ("/tmpwork", "/tmp")] {+ assert!(!path_is_below(path, dir) && !paths_overlap(path, dir));+ }+ // Equal paths overlap without one lying below the other.+ assert!(!path_is_below("/dev", "/dev") && paths_overlap("/dev", "/dev"));+ assert!(paths_overlap("/dev", "/dev/null"));+ }++ #[test]+ fn reserved_targets_follow_path_components() {+ for target in [+ "/dev",+ "/dev/",+ "/dev/null",+ "/proc",+ "/sys/fs",+ "/tmp",+ "/tmp/work",+ ] {+ assert!(reserved_mount_target(target).is_some(), "{target}");+ }+ assert!(reserved_mount_target("/tmpwork").is_none());+ assert_eq!(reserved_mount_target("/proc/1"), Some("/proc"));+ }++ #[test]+ fn a_target_is_normalized_or_refused() {+ assert_eq!(normalize_target("//work/./"), Some("/work".to_owned()));+ for target in ["", "/", "relative", "/a/../b", "/a\0"] {+ assert_eq!(normalize_target(target), None, "{target:?}");+ }+ }+}+/// SSH lifecycle limits shared between host and guest.pub mod ssh {use std::time::Duration;diff --git a/src/vmm/README.md b/src/vmm/README.mdindex c200d850f..37cbca505 100644--- a/src/vmm/README.md+++ b/src/vmm/README.md@@ -106,16 +106,17 @@ sequenceDiagramparticipant Guest as Guest agent on box.sockHost->>Shim: Register with directory FDShim->>FS: Publish directory export- Shim-->>Host: Preparing record+ Shim-->>Host: Export identityHost->>Guest: Mount(export key, device tag, destination, mode)Guest-->>Host: Mount complete- Host->>Shim: Set state Mounted```-Registration reserves a target, allocates an export identity, and publishes a-`Preparing` record before replying. A new connection can query the record if-the reply is lost. List admission accounts for serialized JSON bytes,-including escaping and later state changes.+Registration allocates an export identity and publishes the export before+replying. The shim keeps no state beyond that table: delivery progress is the+caller's. A new connection can find the export by request ID if the reply is+lost. A request ID, like a target, names at most one export: a repeated+request, or a second export for one target, is refused with `EBUSY`. List+admission accounts for serialized JSON bytes, including escaping.The kernel queues connections for the serial control thread. The client hasone deadline for connect, queue wait, and I/O, including time behind a disk@@ -138,10 +139,10 @@ Run `make test:integration:vmm:mount-delivery` with a compatible `VMM_KERNEL`to register, attach, and retire a directory through the native shim and guest.The host control client is blocking and belongs in `spawn_blocking` when used-from async code. Its caller must mark an incarnation `Detaching` before requesting-guest detach, acknowledge that detach before retiring the export, and retain recovery ownership when outcomes-are uncertain. The public `box.mounts()` facade and runtime transaction-coordinator are a separate layer above these delivery primitives.+from async code. Its caller owns the delivery state: it asks the guest to+detach before retiring the export, and keeps recovery ownership when outcomes+are uncertain. `BoxImpl` coordinates these steps for the public `bx.mount()`+handle.## Virtio network device