The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(volume): add REST API for LocalVolumeStore (#2925)
Lhfcws4bdab63b4728
diff --git a/.github/workflows/README.md b/.github/workflows/README.mdindex a966147a6..6e6800c13 100644--- a/.github/workflows/README.md+++ b/.github/workflows/README.md@@ -140,7 +140,8 @@ Python runs all four supported versions on Linux x64 and the latest on macOS and(six jobs); Node runs all three versions on Linux x64 and the latest on the other platforms(five jobs). Weekly and manually dispatched tests exercise every platform/version combinationand bypass change filters. Combined Rust and CLI coverage runs on all three platforms, including-non-VM integration tests and Linux guest tests. Codecov requires 90% coverage of changed lines+non-VM integration tests and Linux guest tests. Linux CI also runs the volume REST lifecycle+against a real `boxlite serve` process. Codecov requires 90% coverage of changed linesand reports total coverage.The Linux Rust jobs enable unprivileged user namespaces on their disposable runnersdiff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex c3a7cad58..cbafc1768 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -509,6 +509,42 @@ jobs:disable_search: truefail_ci_if_error: true+ # The volume REST lifecycle needs a real server process and its runtime+ # artifacts, but not a VM or persistent E2E runner.+ serve-rest-e2e:+ name: REST Server E2E (Linux)+ needs: changes+ if: ${{ needs.changes.outputs.sdk-tests-enabled == 'true' && needs.changes.outputs.rust == 'true' }}+ runs-on: ubuntu-latest+ timeout-minutes: 45+ permissions:+ contents: read+ steps:+ - name: Checkout code+ uses: actions/checkout@v5++ - uses: ./.github/actions/setup-rust+ with:+ toolchain: ${{ needs.changes.outputs.rust-toolchain }}++ - name: Install cargo-nextest+ uses: taiki-e/install-action@nextest++ - name: Enable unprivileged user namespaces+ run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0++ - name: Enable KVM access for the runtime warm-up+ run: sudo chmod a+rw /dev/kvm++ - name: Prepare runtime dependencies+ run: |+ make setup:submodules+ make setup:build++ - name: Run volume REST lifecycle E2E+ timeout-minutes: 20+ run: make test:e2e:serve:volume+# Python SDK unit testspython:name: Python Tests (${{ matrix.platform.target }} / Python ${{ matrix.python-version }})@@ -1020,7 +1056,7 @@ jobs:# NOTE: keep `needs` in sync with the jobs above when adding/removing jobs.test-conclusion:name: Test (conclusion)- needs: [changes, infra, rust, python, node, go, secret-server-postgres, setup, api, dashboard, plugins, guest_artifacts, coverage-empty]+ needs: [changes, infra, rust, serve-rest-e2e, python, node, go, secret-server-postgres, setup, api, dashboard, plugins, guest_artifacts, coverage-empty]if: ${{ !cancelled() }}runs-on: ubuntu-latestpermissions: {}diff --git a/docs/contributing/development/local-volume-testing.md b/docs/contributing/development/local-volume-testing.mdindex dc5a169db..06ab7f4ab 100644--- a/docs/contributing/development/local-volume-testing.md+++ b/docs/contributing/development/local-volume-testing.md@@ -1,8 +1,9 @@# Local volume test runbookUse this runbook for changes to local managed volumes: the store, box holder lifecycle, archive-round trips, CLI mounts, guest resolved mounts, or the existing Python `volumes` dictionary API.-It tests the local runtime only; cloud, REST, and runner behavior are out of scope.+round trips, CLI mounts, guest resolved mounts, the REST volume API, or the existing Python+`volumes` dictionary API. It tests the local runtime and the server-backed REST API; cloud and+runner behavior are out of scope.Run every command from the repository root unless the command changes directory itself. Execute thesteps in order and keep the output needed to identify which tests actually ran.@@ -134,6 +135,23 @@ Step 4 is complete when the three CLI scenarios and archive round trip pass, pludirectory cases on Linux. On a host without a usable hypervisor, skip the remaining VM steps andcontinue to the final report with that coverage marked as blocked.+For REST API changes, start a real `boxlite serve` process and drive its volume endpoints:++```bash+make test:e2e:serve:volume+```++This Make entry runs `volume_crud_over_rest` with the CLI integration target and skips rebuilding+runtime artifacts when `SETUP_DONE=1` is already set. Confirm that `volume_crud_over_rest` ran. It+creates a named volume through the Rust REST client, checks list and get metadata, verifies the+invalid-id and missing-volume error classes, removes the volume, and confirms that both get and+list reflect the removal. Unlike the local CLI scenarios, this case does not boot a VM; it verifies+server startup, routing, persistence-backed CRUD, and HTTP error mapping. CI runs this case in the+`REST Server E2E (Linux)` job.++REST coverage is complete when this named test runs; it does not replace the real-VM coverage above+when the mount or guest protocol changes.+## 5. Verify the Python compatibility pathRun the standard target first:diff --git a/docs/guides/volumes.md b/docs/guides/volumes.mdindex e45f7d6d3..127246050 100644--- a/docs/guides/volumes.md+++ b/docs/guides/volumes.md@@ -77,6 +77,43 @@ A single box cannot mount the same canonical volume id more than once, even undetargets, or read-only modes. This is rejected with `InvalidArgument`. Different boxes may stillmount the same id independently.+### REST and `boxlite serve`++The REST API exposes the same volume lifecycle:++```bash+curl -X POST -H 'Content-Type: application/json' -d '{"name":"workspace"}' \+ http://127.0.0.1:7860/v1/volumes+curl http://127.0.0.1:7860/v1/volumes+curl http://127.0.0.1:7860/v1/volumes/<volume-id>+curl -X DELETE 'http://127.0.0.1:7860/v1/volumes/<volume-id>?force=true'+```++Get and remove use the canonical id. Create-box mounts may use either id or name:++```bash+curl -X POST -H 'Content-Type: application/json' -d @request.json \+ http://127.0.0.1:7860/v1/boxes+```++```json+{+ "image": "alpine:latest",+ "mounts": [{+ "type": "volume",+ "source": "workspace",+ "target": "/workspace",+ "read_only": true,+ "sub_path": "team/backend"+ }]+}+```++The legacy `volumes` array is still accepted, but a request cannot contain both non-empty+`volumes` and `mounts`. REST does not accept host bind mounts: a path in a REST request names the+server filesystem, not the caller filesystem. Create the volume on the server and mount it by id or+name instead.+### Lifecycle, clone, and importEvery persisted box configuration that references a volume prevents its deletion, includingdiff --git a/docs/reference/rust/README.md b/docs/reference/rust/README.mdindex cc2dbaded..80c419d24 100644--- a/docs/reference/rust/README.md+++ b/docs/reference/rust/README.md@@ -980,7 +980,7 @@ The two origins are not interchangeable across runtimes:| Origin | Local runtime | REST runtime || --- | --- | --- |-| `VolumeSpec::managed_volume` | rejected — no volume backend | mounted |+| `VolumeSpec::managed_volume` | mounted | mounted || `VolumeSpec::bind_mount` | mounted | rejected — the path is the server's, not yours |### MountSpec@@ -1018,20 +1018,22 @@ let prefix = MountSpec {let bind = MountSpec::bind_mount("/tmp/data", "/data");```-`MountType` parses from and displays as `"volume"` and `"bind"` exactly. Only-the Rust `BoxOptions` carries a `MountSpec`; no CLI flag, other SDK or REST-request does yet.+`MountType` parses from and displays as `"volume"` and `"bind"` exactly. The CLI+and REST create-box request carry a typed volume `mount`; other SDKs are phased+in separately.`MountSpec::validate` refuses a relative `target`, a missing `source`,`sub_path` on a `Bind`, and an empty `sub_path`; create runs it for every mount.A runtime refuses the mounts it does not take rather than dropping them; use`volumes` where it takes none:-- REST runtimes take no typed mounts yet.--- The local runtime takes no typed mounts yet.-- Importing an archive that carries mounts is not supported yet.+Named REST `get_or_create` preserves name-based reuse for legacy read-write `volumes`; it does not+verify the requested mount configuration against the existing box. Typed `mounts` and read-only+mounts require verifiable mount metadata, so the current box response rejects their reuse. Use a+different name or recreate the box for those requests. Creation and reuse without mounts are+unaffected.+### NetworkSpecGuest egress policy — unchanged by the outbound/inbound split.diff --git a/make/help.mk b/make/help.mkindex 0404d6275..3a2abf087 100644--- a/make/help.mk+++ b/make/help.mk@@ -126,6 +126,7 @@ help:@echo " make test:apps:mdeploy - Type-check and test deployment scripts"@echo " make test:apps:mbuild - Type-check and test image publication scripts"@echo " make test:e2e:drivers - Test acceptance-client argument handling"+ @echo " make test:e2e:serve:volume - Start boxlite serve and test volume REST CRUD"@echo " make fmt:apps:proxy - Format the proxy Go service"@echo " make fmt:proxy - Format the proxy package"@echo " make test:skill:boxlite-diagrams - Run diagram skill validator tests"diff --git a/make/test.mk b/make/test.mkindex 210be6adf..f28ab3335 100644--- a/make/test.mk+++ b/make/test.mk@@ -808,6 +808,13 @@ test\:rest\:e2e:test\:rest\:report:@python3 scripts/test/rest/report.py+# Validate the production server against a real Rust REST client. Run+# SETUP_DONE=1 make test:e2e:serve:volume after preparing runtime artifacts.+PHONY_TARGETS += test\:e2e\:serve\:volume+test\:e2e\:serve\:volume:+ @echo "🧪 Starting boxlite serve and exercising volume REST CRUD..."+ @$(MAKE) test:integration:cli FILTER=volume_crud_over_rest+# Validate acceptance-client invocation without a running cloud or VM.test\:e2e\:drivers:@cargo test --locked -p boxlite-e2e-rust $(CARGOTEST_FILTER)diff --git a/openapi/box.openapi.yaml b/openapi/box.openapi.yamlindex c33ebf418..bd61419d8 100644--- a/openapi/box.openapi.yaml+++ b/openapi/box.openapi.yaml@@ -2328,7 +2328,7 @@ components:name: volume_idin: pathrequired: true- description: Server-assigned managed volume identifier+ description: Server-assigned managed volume identifier. Local servers require the lower-case canonical UUID.schema:type: stringminLength: 1@@ -2864,6 +2864,14 @@ components:type: booleandescription: Server honors `ExecRequest.user`.example: true+ volume_read_only_enabled:+ type: boolean+ description: "Whether managed-volume mounts may set `read_only: true`."+ example: true+ typed_mounts_enabled:+ type: boolean+ description: Whether create-box accepts the typed `mounts` field.+ example: trueidempotency_key_lifetime:type: stringdescription: How long idempotency keys are retained (ISO 8601 duration)@@ -3347,6 +3355,15 @@ components:type: arrayitems:$ref: "#/components/schemas/VolumeSpec"+ mounts:+ type: array+ items:+ $ref: "#/components/schemas/MountSpec"+ description: |+ Typed mounts for newer callers. `bind` identifies a path on the+ server's filesystem and is rejected by `boxlite serve`; use a managed+ volume for the REST security boundary. A request must not send+ non-empty legacy `volumes` and typed `mounts` together.network:$ref: "#/components/schemas/NetworkSpec"description: |@@ -3434,13 +3451,48 @@ components:Names are case-insensitive, may include the `CAP_` prefix, and may be `ALL`.example: [NET_RAW]+ MountSpec:+ type: object+ description: |+ Typed mount declaration. The mount type is explicit instead of inferred+ from whether the source looks like a path.+ additionalProperties: false+ required: [type, source, target]+ properties:+ type:+ type: string+ enum: [volume, bind]+ description: Whether `source` names a managed volume or a host path.+ source:+ type: string+ minLength: 1+ description: |+ The volume id or name for `type=volume`; the host path for `type=bind`.+ A REST server treats a bind source as its own filesystem and rejects it.+ target:+ type: string+ pattern: "^/"+ description: Absolute mount point inside the box.+ read_only:+ type: boolean+ default: false+ description: >+ Mount without write access. Supported only when the server advertises+ `volume_read_only_enabled`.+ sub_path:+ type: string+ description: >+ Relative subtree inside a `type=volume` source. It must already exist+ and cannot traverse out through symlinks. Supported only when the+ server advertises `typed_mounts_enabled`.+VolumeSpec:type: objectdescription: |- Managed volume mounted into a box. Host bind mounts have no- representation here: the path would name the server's filesystem, not- the caller's, so the only mount source this API accepts is a managed- volume.+ Legacy managed-volume mount. New requests should use `mounts` with+ `type=volume`; do not send non-empty `volumes` and `mounts` together.+ Host bind mounts have no representation here because a REST path would+ name the server's filesystem.additionalProperties: falserequired: [managed_volume, guest_path]properties:@@ -3457,10 +3509,9 @@ components:read_only:type: booleandefault: false- enum: [false]- description: |- Read-only managed mounts are not implemented yet; `true` is- rejected rather than silently downgraded to read-write.+ description: >+ Mount without write access. Supported only when the server advertises+ `volume_read_only_enabled`.VolumeState:type: string@@ -3485,6 +3536,18 @@ components:type: stringformat: date-timedescription: Volume creation timestamp (UTC)+ updated_at:+ type: string+ format: date-time+ description: >+ Last update timestamp. Local directory volumes use the creation time.+ size_bytes:+ type: [integer, "null"]+ format: int64+ minimum: 0+ description: >+ Best-effort size. Local directory volumes report null rather than scan+ the payload synchronously.CreateVolumeRequest:type: object@@ -3529,6 +3592,13 @@ components:error_reason:type: stringdescription: Failure detail when state is "error"+ size_bytes:+ type: [integer, "null"]+ format: int64+ minimum: 0+ description: >+ Best-effort size. Local directory volumes report null rather than scan+ the payload synchronously.ListVolumesResponse:type: objectdiff --git a/src/boxlite/src/rest/client.rs b/src/boxlite/src/rest/client.rsindex 1b974d7bf..783268468 100644--- a/src/boxlite/src/rest/client.rs+++ b/src/boxlite/src/rest/client.rs@@ -804,6 +804,29 @@ impl ApiClient {ensure_capability("per-exec user", capabilities.exec_user_enabled)}+ pub async fn require_mount_capabilities(+ &self,+ typed_mounts: bool,+ read_only_mounts: bool,+ ) -> BoxliteResult<()> {+ if !typed_mounts && !read_only_mounts {+ return Ok(());+ }+ let config = self.fetch_config().await?;+ let capabilities = config.capabilities.ok_or_else(|| {+ BoxliteError::Unsupported(+ "Remote server did not advertise volume mount capability".to_string(),+ )+ })?;+ if typed_mounts {+ ensure_capability("typed mounts", capabilities.typed_mounts_enabled)?;+ }+ if read_only_mounts {+ ensure_capability("volume read-only", capabilities.volume_read_only_enabled)?;+ }+ Ok(())+ }+pub async fn require_privileged_enabled(&self) -> BoxliteResult<()> {// Recheck before every create: cached support may outlive a rollback.let config = self.fetch_config().await?;diff --git a/src/boxlite/src/rest/runtime.rs b/src/boxlite/src/rest/runtime.rsindex c73e23f1d..5968ba2fa 100644--- a/src/boxlite/src/rest/runtime.rs+++ b/src/boxlite/src/rest/runtime.rs@@ -383,16 +383,12 @@ impl BoxOptions {));}- // Mounts. `BoxOptions::sanitize` is local-only, so- // `VolumeSpec::validate` — the "exactly one origin" invariant that C and- // Go callers can violate by setting the fields directly — has no other- // chance to run before the request goes out.- //- // A host bind has no meaning against a REST runtime either: the path- // names the *server's* filesystem, not the caller's. The rejected path- // is deliberately not quoted back — the caller already knows what they- // asked for, and echoing a server-side path into a client error is a- // leak, not a diagnostic.+ if !self.volumes.is_empty() && !self.mounts.is_empty() {+ return Err(BoxliteError::InvalidArgument(+ "volumes and mounts must not both be non-empty; use typed mounts for new requests"+ .to_string(),+ ));+ }for volume in &self.volumes {volume.validate()?;@@ -410,26 +406,15 @@ impl BoxOptions {));}- // The server rejects `read_only: true` on a managed mount. Refusing here- // says so plainly instead of surfacing a field-level 400, and — more to the- // point — never lets a caller believe a writable mount is protected.- if let Some(volume) = self- .volumes- .iter()- .find(|volume| volume.read_only)- .and_then(|volume| volume.managed_volume.as_deref())- {- return Err(BoxliteError::Unsupported(format!(- "read-only managed volumes are not supported yet; mount {volume:?} read-write"- )));- }-- // REST runtimes send no typed mounts yet(TODO): refused here, before- // any request, rather than left out of it.- if !self.mounts.is_empty() {- return Err(BoxliteError::Unsupported(- "typed mounts are not supported by REST runtimes yet".to_string(),- ));+ for mount in &self.mounts {+ mount.validate()?;+ if mount.mount_type == crate::runtime::options::MountType::Bind {+ return Err(BoxliteError::Unsupported(+ "host bind mounts are only supported by the local runtime; create a volume \+ and mount it by id or name instead"+ .to_string(),+ ));+ }}Ok(())@@ -471,6 +456,17 @@ impl RuntimeBackend for RestRuntime {if options.advanced.privileged {self.client.require_privileged_enabled().await?;}+ let uses_mounts_field_for_new_mountspec = !options.mounts.is_empty();+ let has_read_only_mounts = options.volumes.iter().any(|volume| volume.read_only)+ || options.mounts.iter().any(|mount| mount.read_only);+ if uses_mounts_field_for_new_mountspec || has_read_only_mounts {+ self.client+ .require_mount_capabilities(+ uses_mounts_field_for_new_mountspec,+ has_read_only_mounts,+ )+ .await?;+ }let req = CreateBoxRequest::from_options(&options, name);let resp = self.client.create_box(&req).await?;@@ -492,11 +488,30 @@ impl RuntimeBackend for RestRuntime {));}options.sanitize_remote()?;+ let uses_mounts_field_for_new_mountspec = !options.mounts.is_empty();+ let has_read_only_mounts = options.volumes.iter().any(|volume| volume.read_only)+ || options.mounts.iter().any(|mount| mount.read_only);+ if uses_mounts_field_for_new_mountspec || has_read_only_mounts {+ self.client+ .require_mount_capabilities(+ uses_mounts_field_for_new_mountspec,+ has_read_only_mounts,+ )+ .await?;+ }if let Some(ref box_name) = name {let path = format!("/boxes/{box_name}");match self.client.get::<BoxResponse>(&path).await {Ok(response) => {+ // TODO DISCUSS: Legacy read-write volumes retain name-based reuse without+ // verifying mount metadata; decide whether tighter protection is preferable.+ if uses_mounts_field_for_new_mountspec || has_read_only_mounts {+ return Err(BoxliteError::Unsupported(format!(+ "cannot reuse box {box_name:?}: the REST response does not expose its \+ existing mount configuration; use a different name or recreate the box"+ )));+ }let actual = response.privileged.ok_or_else(|| {BoxliteError::Unsupported(format!("cannot reuse box {box_name:?}: the server did not report its \@@ -1366,37 +1381,43 @@ mod tests {);}- /// Until REST runtimes send typed mounts, create refuses them before any- /// network I/O rather than leaving them out of the request.+ /// Typed mounts can only be sent to a server that advertises the wire+ /// contract. The probe happens before the create request so an older+ /// server cannot drop the field silently.#[tokio::test]- async fn create_refuses_typed_mounts_until_rest_sends_them() {+ async fn create_requires_typed_mount_advertisement() {use crate::runtime::options::MountSpec;- let options = BoxliteRestOptions::new("http://localhost:1");- let runtime = RestRuntime::new(&options).expect("failed to create REST runtime");+ let (port, server) = json_server(vec![r#"{"capabilities":{}}"#]).await;+ let runtime =+ RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}")))+ .expect("failed to create REST runtime");let box_options = BoxOptions {mounts: vec![MountSpec::volume_mount("run42", "/workspace")],..Default::default()};- let error = RuntimeBackend::create(&runtime, box_options, None)- .await- .err()- .expect("typed mounts must be refused before network I/O");+ let error = match RuntimeBackend::create(&runtime, box_options, None).await {+ Err(error) => error,+ Ok(_) => panic!("unadvertised typed mounts must be rejected before creation"),+ };assert!(matches!(error, BoxliteError::Unsupported(_)), "{error:?}");assert!(error.to_string().contains("typed mounts"), "{error}");+ assert_eq!(server.await.unwrap(), ["GET /v1/config HTTP/1.1"]);}- /// The server rejects `read_only: true` on a managed mount. Refusing it- /// here keeps a caller from believing a writable mount is protected — the- /// failure mode that matters is the silent downgrade, not the 400.+ /// Read-only is a safety property, not a cosmetic flag. If an older server+ /// cannot advertise it, the client refuses to ask rather than assume both+ /// sides agree on writable data.#[tokio::test]- async fn create_rejects_read_only_managed_volume() {+ async fn create_requires_read_only_advertisement() {use crate::runtime::options::VolumeSpec;- let options = BoxliteRestOptions::new("http://localhost:1");- let runtime = RestRuntime::new(&options).expect("failed to create REST runtime");+ let (port, server) = json_server(vec![r#"{"capabilities":{}}"#]).await;+ let runtime =+ RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}")))+ .expect("failed to create REST runtime");let box_options = BoxOptions {volumes: vec![VolumeSpec {read_only: true,@@ -1405,13 +1426,276 @@ mod tests {..Default::default()};- let error = RuntimeBackend::create(&runtime, box_options, None)- .await- .err()- .expect("read-only managed volumes must be rejected before network I/O");+ let error = match RuntimeBackend::create(&runtime, box_options, None).await {+ Err(error) => error,+ Ok(_) => panic!("unadvertised read-only mounts must be rejected before creation"),+ };assert!(matches!(error, BoxliteError::Unsupported(_)), "{error:?}");assert!(error.to_string().contains("read-only"), "{error}");+ assert_eq!(server.await.unwrap(), ["GET /v1/config HTTP/1.1"]);+ }++ #[tokio::test]+ async fn create_sends_typed_read_only_mount_after_both_capabilities() {+ use crate::runtime::options::MountSpec;++ let (port, server) = capture_server(vec![+ (+ 200,+ r#"{"capabilities":{"typed_mounts_enabled":true,"volume_read_only_enabled":true}}"#,+ ),+ (200, BOX_RESPONSE),+ ])+ .await;+ let runtime =+ RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();+ let options = BoxOptions {+ mounts: vec![MountSpec {+ read_only: true,+ sub_path: Some("team/backend".into()),+ ..MountSpec::volume_mount("workspace", "/workspace")+ }],+ ..Default::default()+ };++ RuntimeBackend::create(&runtime, options, None)+ .await+ .expect("both advertised capabilities permit the create");++ let requests = server.await.unwrap();+ assert_eq!(+ requests+ .iter()+ .map(|(headers, _)| headers.lines().next().unwrap())+ .collect::<Vec<_>>(),+ ["GET /v1/config HTTP/1.1", "POST /v1/boxes HTTP/1.1"]+ );+ let body: serde_json::Value = serde_json::from_str(&requests[1].1).unwrap();+ assert_eq!(+ body["mounts"][0],+ serde_json::json!({+ "type": "volume",+ "source": "workspace",+ "target": "/workspace",+ "read_only": true,+ "sub_path": "team/backend",+ })+ );+ }++ #[tokio::test]+ async fn typed_writable_mount_requires_only_typed_mount_capability() {+ use crate::runtime::options::MountSpec;++ let (port, server) = capture_server(vec![+ (200, r#"{"capabilities":{"typed_mounts_enabled":true}}"#),+ (200, BOX_RESPONSE),+ ])+ .await;+ let runtime =+ RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();+ let options = BoxOptions {+ mounts: vec![MountSpec::volume_mount("workspace", "/workspace")],+ ..Default::default()+ };++ RuntimeBackend::create(&runtime, options, None)+ .await+ .expect("writable typed mounts do not need the read-only capability");+ assert_eq!(+ server+ .await+ .unwrap()+ .iter()+ .map(|(headers, _)| headers.lines().next().unwrap().to_owned())+ .collect::<Vec<_>>(),+ ["GET /v1/config HTTP/1.1", "POST /v1/boxes HTTP/1.1"]+ );+ }++ #[tokio::test]+ async fn create_sends_legacy_read_only_volume_after_capability() {+ use crate::runtime::options::VolumeSpec;++ let (port, server) = capture_server(vec![+ (200, r#"{"capabilities":{"volume_read_only_enabled":true}}"#),+ (200, BOX_RESPONSE),+ ])+ .await;+ let runtime =+ RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();+ let options = BoxOptions {+ volumes: vec![VolumeSpec {+ read_only: true,+ ..VolumeSpec::managed_volume("workspace", "/workspace")+ }],+ ..Default::default()+ };++ RuntimeBackend::create(&runtime, options, None)+ .await+ .expect("advertised read-only support permits the legacy create");++ let requests = server.await.unwrap();+ assert_eq!(+ requests+ .iter()+ .map(|(headers, _)| headers.lines().next().unwrap())+ .collect::<Vec<_>>(),+ ["GET /v1/config HTTP/1.1", "POST /v1/boxes HTTP/1.1"]+ );+ let body = json_body(&requests[1].1);+ assert_eq!(+ body["volumes"],+ serde_json::json!([{+ "managed_volume": "workspace",+ "guest_path": "/workspace",+ "read_only": true+ }])+ );+ assert!(body.get("mounts").is_none());+ }++ #[tokio::test]+ async fn get_or_create_requires_mount_capabilities_before_lookup() {+ use crate::runtime::options::{MountSpec, VolumeSpec};++ for options in [+ BoxOptions {+ mounts: vec![MountSpec::volume_mount("workspace", "/workspace")],+ ..Default::default()+ },+ BoxOptions {+ volumes: vec![VolumeSpec {+ read_only: true,+ ..VolumeSpec::managed_volume("workspace", "/workspace")+ }],+ ..Default::default()+ },+ ] {+ let (port, server) = json_server(vec![r#"{"capabilities":{}}"#]).await;+ let runtime =+ RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}")))+ .unwrap();++ let error = RuntimeBackend::get_or_create(&runtime, options, Some("named".into()))+ .await+ .err()+ .expect("an old server must not reuse or create a mounted box");+ assert!(matches!(error, BoxliteError::Unsupported(_)), "{error:?}");+ assert_eq!(server.await.unwrap(), ["GET /v1/config HTTP/1.1"]);+ }+ }++ #[tokio::test]+ async fn get_or_create_reuses_legacy_read_write_volume_without_mount_metadata() {+ use crate::runtime::options::VolumeSpec;++ let mut response = serde_json::from_str::<serde_json::Value>(BOX_RESPONSE).unwrap();+ response["privileged"] = false.into();+ let response = Box::leak(response.to_string().into_boxed_str());+ let (port, server) = json_server(vec![response]).await;+ let runtime =+ RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}"))).unwrap();+ let options = BoxOptions {+ volumes: vec![VolumeSpec::managed_volume("workspace", "/workspace")],+ ..Default::default()+ };++ let (litebox, created) =+ RuntimeBackend::get_or_create(&runtime, options, Some("named".into()))+ .await+ .expect("legacy read-write volumes preserve name-based reuse");++ assert!(!created);+ assert_eq!(litebox.id().as_str(), "01HJK4TNRPQSXYZ8WM6NCVT9R5");+ assert_eq!(server.await.unwrap(), ["GET /v1/boxes/named HTTP/1.1"]);+ }++ #[tokio::test]+ async fn get_or_create_rejects_mount_reuse_without_configuration_metadata() {+ use crate::runtime::options::{MountSpec, VolumeSpec};++ for options in [+ BoxOptions {+ volumes: vec![VolumeSpec {+ read_only: true,+ ..VolumeSpec::managed_volume("workspace", "/workspace")+ }],+ ..Default::default()+ },+ BoxOptions {+ mounts: vec![MountSpec::volume_mount("workspace", "/workspace")],+ ..Default::default()+ },+ BoxOptions {+ mounts: vec![MountSpec {+ read_only: true,+ sub_path: Some("team/backend".into()),+ ..MountSpec::volume_mount("workspace", "/workspace")+ }],+ ..Default::default()+ },+ ] {+ let mut response = serde_json::from_str::<serde_json::Value>(BOX_RESPONSE).unwrap();+ response["privileged"] = false.into();+ let response = Box::leak(response.to_string().into_boxed_str());+ let (port, server) = capture_server(vec![+ (+ 200,+ r#"{"capabilities":{"typed_mounts_enabled":true,"volume_read_only_enabled":true}}"#,+ ),+ (200, response),+ ])+ .await;+ let runtime =+ RestRuntime::new(&BoxliteRestOptions::new(format!("http://127.0.0.1:{port}")))+ .unwrap();++ let error = RuntimeBackend::get_or_create(&runtime, options, Some("named".into()))+ .await+ .err()+ .expect("reuse must not assume the existing mount configuration matches");+ assert!(matches!(error, BoxliteError::Unsupported(_)), "{error:?}");+ assert!(error.to_string().contains("mount configuration"), "{error}");++ let requests = server.await.unwrap();+ assert_eq!(+ requests+ .iter()+ .map(|(headers, _)| headers.lines().next().unwrap())+ .collect::<Vec<_>>(),+ ["GET /v1/config HTTP/1.1", "GET /v1/boxes/named HTTP/1.1"]+ );+ }+ }++ #[test]+ fn create_box_request_carries_typed_volume_mount() {+ use crate::runtime::options::MountSpec;++ let options = BoxOptions {+ mounts: vec![MountSpec {+ read_only: true,+ sub_path: Some("team/backend".to_string()),+ ..MountSpec::volume_mount("workspace", "/workspace")+ }],+ ..Default::default()+ };+ let request = CreateBoxRequest::from_options(&options, None);+ let json = serde_json::to_value(&request).unwrap();++ assert_eq!(+ json["mounts"],+ serde_json::json!([{+ "type": "volume",+ "source": "workspace",+ "target": "/workspace",+ "read_only": true,+ "sub_path": "team/backend"+ }])+ );}/// The guard is about host paths, not about mounts: a managed volume getsdiff --git a/src/boxlite/src/rest/types.rs b/src/boxlite/src/rest/types.rsindex b80046619..e6d4f2eae 100644--- a/src/boxlite/src/rest/types.rs+++ b/src/boxlite/src/rest/types.rs@@ -105,6 +105,8 @@ pub(crate) struct ServerCapabilities {pub import_enabled: Option<bool>,pub private_tunnels_enabled: Option<bool>,pub exec_user_enabled: Option<bool>,+ pub volume_read_only_enabled: Option<bool>,+ pub typed_mounts_enabled: Option<bool>,}// ============================================================================@@ -143,6 +145,8 @@ pub(crate) struct CreateBoxRequest {#[serde(skip_serializing_if = "Option::is_none")]pub volumes: Option<Vec<CreateBoxVolumeSpec>>,#[serde(skip_serializing_if = "Option::is_none")]+ pub mounts: Option<Vec<CreateBoxMountSpec>>,+ #[serde(skip_serializing_if = "Option::is_none")]pub detach: Option<bool>,/// A terminal for the main command (`run -t`). Only sent when asked for:/// the server rejects unknown fields, so an older one would 400 on it —@@ -197,6 +201,17 @@ impl CreateBoxRequest {.collect(),)};+ let mounts = if options.mounts.is_empty() {+ None+ } else {+ Some(+ options+ .mounts+ .iter()+ .map(CreateBoxMountSpec::from)+ .collect(),+ )+ };// SecurityOptions is intentionally NOT carried on the wire.// Sandbox security is the operator's policy and is set@@ -224,6 +239,7 @@ impl CreateBoxRequest {user: options.user.clone(),secrets,volumes,+ mounts,detach: Some(options.detach),tty: options.tty.then_some(true),// Guest privilege and capability policy cross the wire. Like `security`,@@ -269,6 +285,32 @@ pub(crate) struct CreateBoxVolumeSpec {pub read_only: bool,}+/// Typed mount on the wire. Server-side bind paths are never accepted; the+/// client refuses them before the request instead of sending a server path.+#[derive(Debug, Serialize)]+pub(crate) struct CreateBoxMountSpec {+ #[serde(rename = "type")]+ pub mount_type: crate::runtime::options::MountType,+ pub source: String,+ pub target: String,+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub read_only: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub sub_path: Option<String>,+}++impl From<&crate::runtime::options::MountSpec> for CreateBoxMountSpec {+ fn from(mount: &crate::runtime::options::MountSpec) -> Self {+ Self {+ mount_type: mount.mount_type,+ source: mount.source.clone().unwrap_or_default(),+ target: mount.target.clone(),+ read_only: mount.read_only,+ sub_path: mount.sub_path.clone(),+ }+ }+}+impl From<&crate::runtime::options::VolumeSpec> for CreateBoxVolumeSpec {fn from(volume: &crate::runtime::options::VolumeSpec) -> Self {Self {diff --git a/src/boxlite/src/volumes/local_store.rs b/src/boxlite/src/volumes/local_store.rsindex 20bd2a0b8..698f8065a 100644--- a/src/boxlite/src/volumes/local_store.rs+++ b/src/boxlite/src/volumes/local_store.rs@@ -178,6 +178,7 @@ impl LocalVolumeStore {pub(crate) fn list(&self) -> BoxliteResult<Vec<VolumeInfo>> {self.with_registry_lock(false, || {let mut volumes = Vec::new();+ let mut names = std::collections::HashSet::new();for entry in self.canonical_entries()? {let id = entry.file_name()@@ -185,7 +186,15 @@ impl LocalVolumeStore {.unwrap_or_default().to_owned();match self.read_info(&entry) {- Ok(info) => volumes.push(info),+ Ok(info) => {+ if !names.insert(info.name.clone()) {+ return Err(BoxliteError::MetadataError(format!(+ "duplicate volume name {:?} in local store",+ info.name+ )));+ }+ volumes.push(info);+ }Err(error) => {tracing::warn!(volume_id = %id, %error, "Skipping invalid local volume");}@@ -1591,6 +1600,11 @@ mod tests {.create(Some("another")).expect_err("duplicate metadata names must fail creation");assert!(matches!(error, BoxliteError::MetadataError(_)), "{error:?}");+ let error = runtime+ .local_volume_store+ .list()+ .expect_err("list must not hide duplicate volume names");+ assert!(matches!(error, BoxliteError::MetadataError(_)), "{error:?}");let options = BoxOptions {volumes: vec![VolumeSpec::managed_volume("duplicate", "/workspace")],..Default::default()@@ -1603,6 +1617,34 @@ mod tests {assert!(matches!(error, BoxliteError::MetadataError(_)), "{error:?}");}+ #[tokio::test]+ async fn named_volume_cannot_shadow_a_canonical_id() {+ let home = tempfile::tempdir().unwrap();+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {+ home_dir: home.path().to_path_buf(),+ ..Default::default()+ })+ .unwrap();+ let existing = runtime.local_volume_store.create(None).unwrap();++ let error = runtime+ .local_volume_store+ .create(Some(&existing.id))+ .expect_err("a canonical UUID must not become a volume name");+ assert!(+ matches!(error, BoxliteError::InvalidArgument(_)),+ "{error:?}"+ );+ assert_eq!(+ runtime+ .local_volume_store+ .resolve_selector(&existing.id, VolumeReferenceMode::Selector)+ .unwrap()+ .id,+ existing.id+ );+ }+#[tokio::test]async fn name_audit_ignores_unrelated_payload_corruption() {let home = tempfile::tempdir().unwrap();diff --git a/src/cli/src/commands/serve/handlers/config.rs b/src/cli/src/commands/serve/handlers/config.rsindex ab02160f3..095197413 100644--- a/src/cli/src/commands/serve/handlers/config.rs+++ b/src/cli/src/commands/serve/handlers/config.rs@@ -15,6 +15,8 @@ pub(in crate::commands::serve) async fn get_config() -> Json<ServerConfig> {export_enabled: true,import_enabled: true,exec_user_enabled: true,+ volume_read_only_enabled: true,+ typed_mounts_enabled: true,},})}@@ -34,4 +36,11 @@ mod tests {async fn config_does_not_advertise_local_checkpoints() {assert!(!get_config().await.0.capabilities.checkpoints_enabled);}++ #[tokio::test]+ async fn config_advertises_volume_mount_support() {+ let capabilities = get_config().await.0.capabilities;+ assert!(capabilities.volume_read_only_enabled);+ assert!(capabilities.typed_mounts_enabled);+ }}diff --git a/src/cli/src/commands/serve/handlers/volumes.rs b/src/cli/src/commands/serve/handlers/volumes.rsindex d233b5938..f2cda6ade 100644--- a/src/cli/src/commands/serve/handlers/volumes.rs+++ b/src/cli/src/commands/serve/handlers/volumes.rs@@ -1,8 +1,9 @@//! Named-volume handlers (`/v1/volumes`).//!//! These mirror the box handlers, delegating to `runtime.volumes()`. The-//! concrete backend returns `Unsupported` for now, so every operation currently-//! responds `400 UnsupportedError`.+//! concrete backend can support, including the local runtime's named-volume+//! store. A backend that does not implement the trait still surfaces its own+//! `UnsupportedError`.use std::sync::Arc;diff --git a/src/cli/src/commands/serve/mod.rs b/src/cli/src/commands/serve/mod.rsindex 03abc8921..06131ba77 100644--- a/src/cli/src/commands/serve/mod.rs+++ b/src/cli/src/commands/serve/mod.rs@@ -27,7 +27,9 @@ use tokio::sync::RwLock;use tower_http::catch_panic::CatchPanicLayer;use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer};-use boxlite::runtime::options::{InboundNetworkConfig, NetworkMode, OutboundNetworkConfig};+use boxlite::runtime::options::{+ InboundNetworkConfig, MountSpec, NetworkMode, OutboundNetworkConfig, VolumeSpec,+};use boxlite::{BoxCommand, BoxInfo, BoxOptions, BoxStatus, BoxliteRuntime, ExecStdin, Execution, LiteBox,NetworkSpec, RootfsSpec,@@ -1220,15 +1222,95 @@ fn box_info_to_response(info: &BoxInfo) -> BoxResponse {}fn volume_info_to_response(info: &boxlite::runtime::types::VolumeInfo) -> types::VolumeResponse {+ let created_at = info+ .created_at+ .to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true);types::VolumeResponse {id: info.id.clone(),name: info.name.clone(),- created_at: info.created_at.to_rfc3339(),+ state: "ready".to_string(),+ created_at: created_at.clone(),+ updated_at: created_at,size_bytes: info.size_bytes,}}+fn mount_requests_to_options(+ legacy: Option<&[types::VolumeSpecRequest]>,+ typed: Option<&[types::MountSpecRequest]>,+) -> Result<(Vec<VolumeSpec>, Vec<MountSpec>), boxlite::BoxliteError> {+ use boxlite::BoxliteError;++ let legacy = legacy.unwrap_or_default();+ let typed = typed.unwrap_or_default();+ if !legacy.is_empty() && !typed.is_empty() {+ return Err(BoxliteError::InvalidArgument(+ "volumes and mounts must not both be non-empty; use typed mounts for new requests"+ .to_string(),+ ));+ }++ let mut volumes = Vec::with_capacity(legacy.len());+ for volume in legacy {+ match (&volume.managed_volume, &volume.host_path) {+ (Some(managed_volume), None) => {+ volumes.push(VolumeSpec::managed_volume(+ managed_volume,+ &volume.guest_path,+ ));+ volumes.last_mut().expect("just pushed").read_only = volume.read_only;+ }+ (None, Some(_)) => {+ return Err(BoxliteError::Unsupported(+ "host bind mounts are unsupported at the REST boundary; create a volume \+ and mount it by id or name instead"+ .to_string(),+ ));+ }+ (Some(_), Some(_)) => {+ return Err(BoxliteError::InvalidArgument(format!(+ "volume mount {:?} sets both managed_volume and host_path; use exactly one",+ volume.guest_path+ )));+ }+ (None, None) => {+ return Err(BoxliteError::InvalidArgument(format!(+ "volume mount {:?} needs managed_volume or host_path",+ volume.guest_path+ )));+ }+ }+ }++ let mut mounts = Vec::with_capacity(typed.len());+ for mount in typed {+ let mount = MountSpec {+ mount_type: match mount.mount_type {+ types::MountTypeRequest::Bind => boxlite::runtime::options::MountType::Bind,+ types::MountTypeRequest::Volume => boxlite::runtime::options::MountType::Volume,+ },+ source: Some(mount.source.clone()),+ target: mount.target.clone(),+ read_only: mount.read_only,+ sub_path: mount.sub_path.clone(),+ };+ mount.validate()?;+ if mount.mount_type == boxlite::runtime::options::MountType::Bind {+ return Err(BoxliteError::Unsupported(+ "host bind mounts are unsupported at the REST boundary; create a volume \+ and mount it by id or name instead"+ .to_string(),+ ));+ }+ mounts.push(mount);+ }++ Ok((volumes, mounts))+}+fn build_box_options(req: &CreateBoxRequest) -> Result<BoxOptions, boxlite::BoxliteError> {+ let (volumes, mounts) =+ mount_requests_to_options(req.volumes.as_deref(), req.mounts.as_deref())?;let rootfs = if let Some(ref path) = req.rootfs_path {RootfsSpec::RootfsPath(path.clone())} else {@@ -1292,14 +1374,6 @@ fn build_box_options(req: &CreateBoxRequest) -> Result<BoxOptions, boxlite::Boxl// uniformly. Operators who want a different policy run the// server with a different default; clients cannot relax it.- if let Some(volumes) = &req.volumes- && !volumes.is_empty()- {- return Err(boxlite::BoxliteError::InvalidArgument(- "managed volumes are not supported by boxlite serve".into(),- ));- }-// An empty name or value can never substitute anything. Reject at the// boundary so this server agrees with the Cloud API's IsNotEmpty and the// runner's per-element `dive` required validation on what a secret is.@@ -1345,6 +1419,8 @@ fn build_box_options(req: &CreateBoxRequest) -> Result<BoxOptions, boxlite::Boxldisk_size_gb: req.disk_size_gb,working_dir: req.working_dir.clone(),env,+ volumes,+ mounts,secrets,network,inbound_network,@@ -2406,19 +2482,215 @@ mod tests {}#[test]- fn build_box_options_rejects_nonempty_volumes() {- let req: super::types::CreateBoxRequest = serde_json::from_str(- r#"{"image":"alpine:latest","volumes":[{"managed_volume":"v1","guest_path":"/data"}]}"#,- )- .expect("body with volumes must deserialize (accepted, then rejected)");+ fn build_box_options_carries_typed_volume_mount() {+ let req: super::types::CreateBoxRequest = serde_json::from_value(serde_json::json!({+ "image": "alpine:latest",+ "mounts": [{+ "type": "volume",+ "source": "workspace",+ "target": "/workspace",+ "read_only": true,+ "sub_path": "team/backend"+ }]+ }))+ .expect("typed volume mount must deserialize");++ let opts = build_box_options(&req).expect("typed volume mount must build");+ assert_eq!(opts.mounts.len(), 1);+ let mount = &opts.mounts[0];+ assert_eq!(+ mount.mount_type,+ boxlite::runtime::options::MountType::Volume+ );+ assert_eq!(mount.source.as_deref(), Some("workspace"));+ assert_eq!(mount.target, "/workspace");+ assert!(mount.read_only);+ assert_eq!(mount.sub_path.as_deref(), Some("team/backend"));+ }- let err = build_box_options(&req).expect_err("non-empty volumes must be rejected");+ #[test]+ fn build_box_options_carries_legacy_managed_volume() {+ for read_only in [false, true] {+ let req: super::types::CreateBoxRequest = serde_json::from_value(serde_json::json!({+ "image": "alpine:latest",+ "volumes": [{+ "managed_volume": "workspace",+ "guest_path": "/workspace",+ "read_only": read_only+ }]+ }))+ .expect("legacy managed volume must deserialize");++ let opts = build_box_options(&req).expect("legacy managed volume must build");+ assert!(opts.mounts.is_empty());+ assert_eq!(opts.volumes.len(), 1);+ assert_eq!(opts.volumes[0].managed_volume.as_deref(), Some("workspace"));+ assert_eq!(opts.volumes[0].guest_path, "/workspace");+ assert_eq!(opts.volumes[0].read_only, read_only);+ }+ }++ #[test]+ fn volume_info_to_response_hides_host_metadata() {+ use chrono::TimeZone;++ let created_at = chrono::Utc.with_ymd_and_hms(2026, 1, 2, 3, 4, 5).unwrap();+ let info = boxlite::runtime::types::VolumeInfo {+ id: "018f6f36-7d28-7b28-a2fa-4b5c6d7e8f90".into(),+ name: "workspace".into(),+ created_at,+ size_bytes: Some(2048),+ };++ let response = volume_info_to_response(&info);+ let json = serde_json::to_value(&response).unwrap();+ let timestamp = "2026-01-02T03:04:05Z";+ assert_eq!(+ json,+ serde_json::json!({+ "id": info.id,+ "name": "workspace",+ "state": "ready",+ "created_at": timestamp,+ "updated_at": timestamp,+ "size_bytes": 2048,+ })+ );+ }++ #[test]+ fn mount_requests_accept_empty_and_reject_invalid_wire_fields() {+ for volumes in [None, Some(serde_json::json!([]))] {+ let body = serde_json::json!({"volumes": volumes});+ let body = match volumes {+ None => serde_json::json!({}),+ _ => body,+ };+ let request: CreateBoxRequest = serde_json::from_value(body).unwrap();+ let (legacy, typed) =+ mount_requests_to_options(request.volumes.as_deref(), request.mounts.as_deref())+ .unwrap();+ assert!(legacy.is_empty() && typed.is_empty());+ }++ let cases = [+ ("unknown field", serde_json::json!({"unknown": true})),+ (+ "missing type",+ serde_json::json!({"source": "data", "target": "/data"}),+ ),+ (+ "missing source",+ serde_json::json!({"type": "volume", "target": "/data"}),+ ),+ (+ "missing target",+ serde_json::json!({"type": "volume", "source": "data"}),+ ),+ (+ "bind sub_path",+ serde_json::json!({"type": "bind", "source": "/tmp", "target": "/data", "sub_path": "project"}),+ ),+ (+ "non-boolean read_only",+ serde_json::json!({"type": "volume", "source": "data", "target": "/data", "read_only": "true"}),+ ),+ ];+ for (description, raw_mount) in cases {+ let raw = format!(r#"{{"mounts":[{raw_mount}]}}"#);+ let request: Result<CreateBoxRequest, _> = serde_json::from_str(&raw);+ let error = match request {+ Ok(request) => {+ mount_requests_to_options(request.volumes.as_deref(), request.mounts.as_deref())+ .expect_err(description)+ }+ Err(error) => boxlite::BoxliteError::InvalidArgument(error.to_string()),+ };+ assert!(+ matches!(+ error,+ boxlite::BoxliteError::InvalidArgument(_)+ | boxlite::BoxliteError::Unsupported(_)+ ),+ "{description}: {error:?}"+ );+ }+ }++ #[test]+ fn build_box_options_rejects_serve_host_binds() {+ let legacy: super::types::CreateBoxRequest = serde_json::from_value(serde_json::json!({+ "image": "alpine:latest",+ "volumes": [{"host_path": "/tmp/secrets", "guest_path": "/mnt"}]+ }))+ .expect("legacy bind shape must deserialize so the policy can reject it");+ let typed: super::types::CreateBoxRequest = serde_json::from_value(serde_json::json!({+ "image": "alpine:latest",+ "mounts": [{"type": "bind", "source": "/tmp/secrets", "target": "/mnt"}]+ }))+ .expect("typed bind must deserialize so the policy can reject it");++ for req in [legacy, typed] {+ let error = build_box_options(&req)+ .expect_err("a server-side host path must not be mounted over REST");+ assert!(+ matches!(error, boxlite::BoxliteError::Unsupported(ref message)+ if message.contains("host bind mounts")),+ "{error:?}"+ );+ assert!(+ !error.to_string().contains("/tmp/secrets"),+ "a rejected server-side host path must not be echoed: {error}"+ );+ }+ }++ #[test]+ fn build_box_options_rejects_mixed_mount_lists() {+ let req: super::types::CreateBoxRequest = serde_json::from_value(serde_json::json!({+ "image": "alpine:latest",+ "volumes": [{"managed_volume": "old", "guest_path": "/old"}],+ "mounts": [{"type": "volume", "source": "new", "target": "/new"}]+ }))+ .expect("mixed lists must deserialize so their combination can be rejected");++ let error = build_box_options(&req)+ .expect_err("legacy and typed mount lists are mutually exclusive");assert!(- matches!(err, boxlite::BoxliteError::InvalidArgument(ref msg) if msg.contains("managed volumes")),- "unexpected error: {err}"+ matches!(error, boxlite::BoxliteError::InvalidArgument(ref message)+ if message.contains("volumes and mounts")),+ "{error:?}");}+ #[test]+ fn build_box_options_treats_empty_mount_lists_as_absent() {+ for volumes in [None, Some(serde_json::json!([]))] {+ for mounts in [None, Some(serde_json::json!([]))] {+ let mut body = serde_json::Map::new();+ if let Some(value) = volumes.as_ref() {+ body.insert("volumes".into(), value.clone());+ }+ if let Some(value) = mounts.as_ref() {+ body.insert("mounts".into(), value.clone());+ }+ let request: CreateBoxRequest =+ serde_json::from_value(serde_json::Value::Object(body)).unwrap();+ let options = build_box_options(&request).unwrap();+ assert!(options.volumes.is_empty() && options.mounts.is_empty());+ }+ }+ }++ #[test]+ fn create_volume_request_rejects_unknown_fields() {+ let error = serde_json::from_str::<super::types::CreateVolumeRequest>(+ r#"{"name":"workspace","host_path":"/tmp/data"}"#,+ )+ .expect_err("volume create has no host_path field");+ assert!(error.to_string().contains("host_path"), "{error}");+ }+#[test]fn build_box_options_carries_container_capabilities_from_the_wire() {let req: super::types::CreateBoxRequest = serde_json::from_str(@@ -4054,6 +4326,242 @@ mod tests {local.shutdown(Some(1)).await.expect("shutdown runtime");}+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn volume_crud_http_contract_uses_canonical_ids() {+ let home = tempfile::tempdir().expect("runtime home");+ let local = BoxliteRuntime::new_for_test(boxlite::BoxliteOptions {+ home_dir: home.path().join("boxlite"),+ ..Default::default()+ })+ .expect("local runtime");+ let state = Arc::new(AppState {+ runtime: local.clone(),+ boxes: RwLock::new(HashMap::new()),+ executions: RwLock::new(HashMap::new()),+ api_key: None,+ lifecycle: RwLock::new(HashMap::new()),+ last_activity: RwLock::new(HashMap::new()),+ recovered_terminals: RwLock::new(HashMap::new()),+ browser_sessions: Default::default(),+ });+ let (base, server) = serve_router(state).await;+ let client = reqwest::Client::new();++ let created: serde_json::Value = client+ .post(format!("{base}/v1/volumes"))+ .send()+ .await+ .unwrap()+ .error_for_status()+ .unwrap()+ .json()+ .await+ .unwrap();+ let id = created["id"].as_str().unwrap().to_owned();+ assert_eq!(created["name"].as_str().unwrap(), id);+ assert_eq!(created["state"].as_str().unwrap(), "ready");+ assert_eq!(created["size_bytes"], serde_json::Value::Null);+ assert!(created.get("host_path").is_none());++ let named: serde_json::Value = client+ .post(format!("{base}/v1/volumes"))+ .json(&serde_json::json!({"name": "workspace"}))+ .send()+ .await+ .unwrap()+ .error_for_status()+ .unwrap()+ .json()+ .await+ .unwrap();+ let named_id = named["id"].as_str().unwrap().to_owned();+ assert_eq!(named["name"], "workspace");+ assert_ne!(named_id, "workspace");+ assert_eq!(named["updated_at"], named["created_at"]);++ let duplicate = client+ .post(format!("{base}/v1/volumes"))+ .json(&serde_json::json!({"name": "workspace"}))+ .send()+ .await+ .unwrap();+ assert_eq!(duplicate.status(), reqwest::StatusCode::CONFLICT);++ let uuid_name = client+ .post(format!("{base}/v1/volumes"))+ .json(&serde_json::json!({"name": id}))+ .send()+ .await+ .unwrap();+ assert_eq!(uuid_name.status(), reqwest::StatusCode::BAD_REQUEST);++ let fetched: serde_json::Value = client+ .get(format!("{base}/v1/volumes/{named_id}"))+ .send()+ .await+ .unwrap()+ .error_for_status()+ .unwrap()+ .json()+ .await+ .unwrap();+ assert_eq!(fetched["id"], named["id"]);+ assert_eq!(fetched["name"], "workspace");+ let by_name = client+ .get(format!("{base}/v1/volumes/workspace"))+ .send()+ .await+ .unwrap();+ assert_eq!(by_name.status(), reqwest::StatusCode::BAD_REQUEST);++ let listed: serde_json::Value = client+ .get(format!("{base}/v1/volumes"))+ .send()+ .await+ .unwrap()+ .json()+ .await+ .unwrap();+ let listed_ids = listed["volumes"]+ .as_array()+ .unwrap()+ .iter()+ .map(|volume| volume["id"].as_str().unwrap())+ .collect::<std::collections::HashSet<_>>();+ assert_eq!(+ listed_ids,+ std::collections::HashSet::from([id.as_str(), named_id.as_str()])+ );++ for volume_id in [&id, &named_id] {+ let removed = client+ .delete(format!("{base}/v1/volumes/{volume_id}"))+ .send()+ .await+ .unwrap();+ assert_eq!(removed.status(), reqwest::StatusCode::NO_CONTENT);+ }+ let missing = client+ .delete(format!("{base}/v1/volumes/{id}?force=false"))+ .send()+ .await+ .unwrap();+ assert_eq!(missing.status(), reqwest::StatusCode::NOT_FOUND);+ let missing_forced = client+ .delete(format!("{base}/v1/volumes/{id}?force=true"))+ .send()+ .await+ .unwrap();+ assert_eq!(missing_forced.status(), reqwest::StatusCode::NO_CONTENT);++ server.abort();+ local.shutdown(Some(1)).await.expect("shutdown runtime");+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn rest_mounts_reach_local_runtime_and_register_volume_holders() {+ let home = tempfile::tempdir().expect("runtime home");+ let local = BoxliteRuntime::new_for_test(boxlite::BoxliteOptions {+ home_dir: home.path().join("boxlite"),+ ..Default::default()+ })+ .expect("local runtime");+ let state = Arc::new(AppState {+ runtime: local.clone(),+ boxes: RwLock::new(HashMap::new()),+ executions: RwLock::new(HashMap::new()),+ api_key: None,+ lifecycle: RwLock::new(HashMap::new()),+ last_activity: RwLock::new(HashMap::new()),+ recovered_terminals: RwLock::new(HashMap::new()),+ browser_sessions: Default::default(),+ });+ let (base, server) = serve_router(state).await;+ let remote = BoxliteRuntime::rest(boxlite::BoxliteRestOptions::new(base.clone()))+ .expect("rest runtime");+ let client = reqwest::Client::new();+ let volumes = remote.volumes().expect("volume handle");+ let typed_volume = volumes.create(Some("typed")).await.expect("typed volume");+ let legacy_volume = volumes.create(Some("legacy")).await.expect("legacy volume");+ std::fs::create_dir_all(+ home.path()+ .join("boxlite/volumes")+ .join(&typed_volume.id)+ .join("_data/team/backend"),+ )+ .expect("typed mount subdirectory");++ let typed = BoxOptions {+ mounts: vec![MountSpec {+ read_only: true,+ sub_path: Some("team/backend".into()),+ ..MountSpec::volume_mount("typed", "/workspace")+ }],+ ..Default::default()+ };+ let legacy = BoxOptions {+ volumes: vec![VolumeSpec {+ read_only: true,+ ..VolumeSpec::managed_volume("legacy", "/workspace")+ }],+ ..Default::default()+ };+ let missing_subdirectory = BoxOptions {+ mounts: vec![MountSpec {+ sub_path: Some("missing".into()),+ ..MountSpec::volume_mount("typed", "/workspace")+ }],+ ..Default::default()+ };+ let error = remote+ .create(missing_subdirectory, Some("missing-sub-path".into()))+ .await+ .err()+ .expect("a missing typed-mount subdirectory must cross the REST boundary");+ assert!(+ matches!(error, boxlite::BoxliteError::NotFound(_)),+ "{error:?}"+ );+ let not_created = client+ .get(format!("{base}/v1/boxes/missing-sub-path"))+ .send()+ .await+ .unwrap();+ assert_eq!(not_created.status(), reqwest::StatusCode::NOT_FOUND);++ for (name, volume, options) in [+ ("typed-box", &typed_volume, typed),+ ("legacy-box", &legacy_volume, legacy),+ ] {+ let litebox = remote+ .create(options, Some(name.to_string()))+ .await+ .expect("REST create must preserve the volume mount");+ let held = client+ .delete(format!("{base}/v1/volumes/{}?force=true", volume.id))+ .send()+ .await+ .unwrap();+ assert_eq!(held.status(), reqwest::StatusCode::CONFLICT);++ let removed = client+ .delete(format!("{base}/v1/boxes/{}", litebox.id()))+ .send()+ .await+ .unwrap();+ assert_eq!(removed.status(), reqwest::StatusCode::NO_CONTENT);+ let remaining = client+ .get(format!("{base}/v1/volumes/{}", volume.id))+ .send()+ .await+ .unwrap();+ assert_eq!(remaining.status(), reqwest::StatusCode::OK);+ }++ server.abort();+ local.shutdown(Some(1)).await.expect("shutdown runtime");+ }+/// Reading a box back over HTTP must report the deadlines `serve` holds.////// `box_response` being correct is not enough — the defect this guards is adiff --git a/src/cli/src/commands/serve/types.rs b/src/cli/src/commands/serve/types.rsindex 82072dc09..6ca2f38b6 100644--- a/src/cli/src/commands/serve/types.rs+++ b/src/cli/src/commands/serve/types.rs@@ -58,12 +58,12 @@ pub(super) struct CreateBoxRequest {/// `build_box_options`, matching the Go SDK's own default.#[serde(default)]pub secrets: Option<Vec<SecretSpecRequest>>,- /// Managed volumes are not supported by `boxlite serve` (no volume- /// backend). Accepted here only so a combined secrets+volumes request does- /// not fail deserialization on an unrelated field; rejected explicitly in- /// `build_box_options` when non-empty.+ /// The pre-typed managed-volume field. Kept for callers written against the+ /// old API; the server still rejects a host path at its security boundary.#[serde(default)]- pub volumes: Option<Vec<serde_json::Value>>,+ pub volumes: Option<Vec<VolumeSpecRequest>>,+ #[serde(default)]+ pub mounts: Option<Vec<MountSpecRequest>>,// `security` / `security_settings` are intentionally absent from// the REST wire schema. Sandbox security is the operator's// policy, set server-side. Because the struct carries@@ -226,12 +226,15 @@ pub(super) struct ListBoxesResponse {pub(super) struct VolumeResponse {pub id: String,pub name: String,+ pub state: String,pub created_at: String,+ pub updated_at: String,pub size_bytes: Option<u64>,}/// Body for `POST /v1/volumes`. An absent body means an unnamed volume.-#[derive(Deserialize, Default)]+#[derive(Debug, Deserialize, Default)]+#[serde(deny_unknown_fields)]pub(super) struct CreateVolumeRequest {#[serde(default)]pub name: Option<String>,@@ -242,6 +245,38 @@ pub(super) struct ListVolumesResponse {pub volumes: Vec<VolumeResponse>,}+#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub(super) struct VolumeSpecRequest {+ #[serde(default)]+ pub managed_volume: Option<String>,+ #[serde(default)]+ pub host_path: Option<String>,+ pub guest_path: String,+ #[serde(default)]+ pub read_only: bool,+}++#[derive(Clone, Copy, Deserialize)]+#[serde(rename_all = "lowercase")]+pub(super) enum MountTypeRequest {+ Bind,+ Volume,+}++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub(super) struct MountSpecRequest {+ #[serde(rename = "type")]+ pub mount_type: MountTypeRequest,+ pub source: String,+ pub target: String,+ #[serde(default)]+ pub read_only: bool,+ #[serde(default)]+ pub sub_path: Option<String>,+}+/// One reference, as `GET /v1/images` lists it.#[derive(Serialize)]pub(super) struct ImageInfoResponse {@@ -363,6 +398,8 @@ pub(super) struct ServerCapabilities {pub export_enabled: bool,pub import_enabled: bool,pub exec_user_enabled: bool,+ pub volume_read_only_enabled: bool,+ pub typed_mounts_enabled: bool,}// ============================================================================diff --git a/src/cli/tests/volumes_rest.rs b/src/cli/tests/volumes_rest.rsnew file mode 100644index 000000000..30e1080f3--- /dev/null+++ b/src/cli/tests/volumes_rest.rs@@ -0,0 +1,50 @@+//! Managed volume lifecycle over a real `boxlite serve` process.++mod common;++use boxlite::{BoxliteError, BoxliteRestOptions, BoxliteRuntime};+use common::serve::ServeChild;++#[tokio::test]+async fn volume_crud_over_rest() {+ let serve = ServeChild::start();+ let runtime = BoxliteRuntime::rest(BoxliteRestOptions::new(serve.url())).expect("REST runtime");+ let volumes = runtime.volumes().expect("volume capability");++ let created = volumes.create(Some("server-data")).await.unwrap();+ assert_eq!(created.name, "server-data");++ let listed = volumes.list().await.unwrap();+ assert_eq!(listed.len(), 1);+ assert_eq!(listed[0].id, created.id);+ assert_eq!(listed[0].name, created.name);+ assert_eq!(listed[0].created_at, created.created_at);++ let fetched = volumes.get(&created.id).await.unwrap();+ assert_eq!(fetched.id, created.id);+ assert_eq!(fetched.name, created.name);+ assert_eq!(fetched.created_at, created.created_at);++ let invalid_id = volumes.get("missing-volume").await.unwrap_err();+ assert!(+ matches!(invalid_id, BoxliteError::InvalidArgument(_)),+ "expected InvalidArgument for a non-UUID id, got {invalid_id:?}"+ );++ let missing = volumes+ .get("00000000-0000-0000-0000-000000000000")+ .await+ .unwrap_err();+ assert!(+ matches!(missing, BoxliteError::NotFound(_)),+ "expected NotFound, got {missing:?}"+ );++ volumes.remove(&created.id, false).await.unwrap();+ let removed = volumes.get(&created.id).await.unwrap_err();+ assert!(+ matches!(removed, BoxliteError::NotFound(_)),+ "expected NotFound after removal, got {removed:?}"+ );+ assert!(volumes.list().await.unwrap().is_empty());+}