Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

fix(server): reject duplicate and root Docker mount destinations with 400

Jackmeson1daf138dbc0c2
diff --git a/docs/examples/docker-pvc-volume-mount.md b/docs/examples/docker-pvc-volume-mount.md
index d6483e02a..a642992dc 100644
--- a/docs/examples/docker-pvc-volume-mount.md
+++ b/docs/examples/docker-pvc-volume-mount.md
@@ -11,6 +11,10 @@ This example demonstrates how to mount Docker named volumes into sandbox contain
The `pvc` backend is a runtime-neutral abstraction. In Kubernetes it maps to a PersistentVolumeClaim; in Docker it maps to a named volume. The same API request works on both runtimes.
:::
+::: info Docker mount destinations
+For all Docker volume backends (`host`, `pvc`, and `ossfs`), `mountPath` must resolve to a non-root path and be unique within the request after POSIX path normalization. For example, `/mnt/data`, `/mnt/data/`, and `/mnt/./data` identify the same destination. Invalid destinations return HTTP 400 with `VOLUME::INVALID_MOUNT_PATH` before volume provisioning. Nested destinations such as `/mnt/data` and `/mnt/data/cache`, and the same source mounted at distinct destinations, are supported.
+:::
+
## Why Named Volumes over Host Paths?
| | Host path (`host` backend) | Named volume (`pvc` backend) |
diff --git a/server/opensandbox_server/services/docker/docker_service.py b/server/opensandbox_server/services/docker/docker_service.py
index a64879b49..fa2ca2a86 100644
--- a/server/opensandbox_server/services/docker/docker_service.py
+++ b/server/opensandbox_server/services/docker/docker_service.py
@@ -656,6 +656,7 @@ class DockerSandboxService(DockerDiagnosticsMixin, DockerRuntimeMixin, DockerVol
self._ensure_secure_access_support(request)
self._ensure_network_policy_support(request)
resource_limits = self._prepare_resource_limits(request)
+ self._validate_volume_definitions(request)
# Docker API calls block; keep them off the event loop.
await asyncio.to_thread(self._validate_network_exists)
diff --git a/server/opensandbox_server/services/docker/volumes.py b/server/opensandbox_server/services/docker/volumes.py
index 44396f4a2..45e615623 100644
--- a/server/opensandbox_server/services/docker/volumes.py
+++ b/server/opensandbox_server/services/docker/volumes.py
@@ -24,7 +24,7 @@ from __future__ import annotations
import logging
import os
import posixpath
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
from docker.errors import DockerException, NotFound as DockerNotFound
from fastapi import HTTPException, status
@@ -40,17 +40,58 @@ from opensandbox_server.services.validators import (
ensure_volumes_valid,
)
+if TYPE_CHECKING:
+ from opensandbox_server.api.schema import CreateSandboxRequest
+
logger = logging.getLogger(__name__)
class DockerVolumesMixin:
"""Mixin providing volume validation, bind mount building, and cleanup."""
+ def _validate_volume_definitions(self, request: CreateSandboxRequest) -> None:
+ """Validate request volumes before filesystem changes or Docker API calls."""
+ if not request.volumes:
+ return
+
+ allowed_prefixes = self.app_config.storage.allowed_host_paths
+ ensure_volumes_valid(request.volumes, allowed_host_prefixes=allowed_prefixes)
+
+ seen_mount_paths: set[str] = set()
+ for volume in request.volumes:
+ # Docker cleans container paths, including repeated leading slashes.
+ mount_path = posixpath.normpath("/" + volume.mount_path.lstrip("/"))
+ if mount_path == "/":
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={
+ "code": SandboxErrorCodes.INVALID_MOUNT_PATH,
+ "message": (
+ f"Volume '{volume.name}': mount path '{volume.mount_path}' "
+ "resolves to '/', which is not supported by the Docker runtime."
+ ),
+ },
+ )
+ if mount_path in seen_mount_paths:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={
+ "code": SandboxErrorCodes.INVALID_MOUNT_PATH,
+ "message": (
+ f"Duplicate mount path '{mount_path}'. Each volume must have "
+ "a unique mount destination in the Docker runtime."
+ ),
+ },
+ )
+ seen_mount_paths.add(mount_path)
+
def _validate_volumes(
self, request
) -> tuple[dict[str, dict], list[str]]:
"""
- Validate volume definitions for Docker runtime.
+ Validate volume backends for Docker runtime.
+
+ Request definitions must already have passed ``_validate_volume_definitions``.
Returns:
A tuple of:
@@ -69,8 +110,6 @@ class DockerVolumesMixin:
return {}, []
allowed_prefixes = self.app_config.storage.allowed_host_paths
- ensure_volumes_valid(request.volumes, allowed_host_prefixes=allowed_prefixes)
-
pvc_inspect_cache: dict[str, dict] = {}
auto_created_volumes: list[str] = []
try:
diff --git a/server/tests/test_docker_service.py b/server/tests/test_docker_service.py
index e83fa403f..37423aab9 100644
--- a/server/tests/test_docker_service.py
+++ b/server/tests/test_docker_service.py
@@ -4045,6 +4045,119 @@ class TestBuildVolumeBinds:
@patch("opensandbox_server.services.docker.docker_service.docker")
class TestDockerVolumeValidation:
+ @pytest.mark.parametrize("network_mode", ["host", "test-network"])
+ @pytest.mark.parametrize(
+ "name,mount_path,error_code",
+ [
+ ("data", "/mnt/other", SandboxErrorCodes.DUPLICATE_VOLUME_NAME),
+ ("other", "/mnt/data", SandboxErrorCodes.INVALID_MOUNT_PATH),
+ ("other", "/mnt/data/", SandboxErrorCodes.INVALID_MOUNT_PATH),
+ ("other", "/mnt/data/.", SandboxErrorCodes.INVALID_MOUNT_PATH),
+ ("other", "/mnt/./data", SandboxErrorCodes.INVALID_MOUNT_PATH),
+ ("other", "/mnt/cache/../data", SandboxErrorCodes.INVALID_MOUNT_PATH),
+ ("other", "//mnt/data", SandboxErrorCodes.INVALID_MOUNT_PATH),
+ ("other", "/", SandboxErrorCodes.INVALID_MOUNT_PATH),
+ ("other", "//", SandboxErrorCodes.INVALID_MOUNT_PATH),
+ ("other", "/.", SandboxErrorCodes.INVALID_MOUNT_PATH),
+ ("other", "/mnt/..", SandboxErrorCodes.INVALID_MOUNT_PATH),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_invalid_volumes_rejected_before_docker_calls(
+ self, mock_docker, name, mount_path, error_code, network_mode
+ ):
+ mock_client = MagicMock()
+ mock_client.containers.list.return_value = []
+ mock_client.api.inspect_volume.return_value = {"Name": "shared-data"}
+ mock_client.api.create_host_config.return_value = {}
+ mock_client.api.create_container.side_effect = DockerException("invalid mount destination")
+ mock_docker.from_env.return_value = mock_client
+ cfg = _app_config()
+ cfg.docker.network_mode = network_mode
+ service = DockerSandboxService(config=cfg)
+ mock_client.reset_mock()
+
+ request = CreateSandboxRequest(
+ image=ImageSpec(uri="python:3.11"),
+ timeout=120,
+ resourceLimits=ResourceLimits(root={}),
+ entrypoint=["python"],
+ volumes=[
+ Volume(
+ name="data",
+ pvc=PVC(claim_name="shared-data"),
+ mount_path="/mnt/data",
+ ),
+ Volume(
+ name=name,
+ pvc=PVC(claim_name="shared-data"),
+ mount_path=mount_path,
+ ),
+ ],
+ )
+
+ with (
+ patch.object(service, "_ensure_image_available"),
+ patch.object(service, "_prepare_sandbox_runtime"),
+ pytest.raises(HTTPException) as exc_info,
+ ):
+ await service.create_sandbox(request)
+
+ assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST
+ assert exc_info.value.detail["code"] == error_code
+ assert isinstance(exc_info.value.detail["message"], str)
+ mock_client.containers.create.assert_not_called()
+ mock_client.api.create_container.assert_not_called()
+ mock_client.api.inspect_volume.assert_not_called()
+ mock_client.api.create_volume.assert_not_called()
+ assert mock_client.mock_calls == []
+
+ @pytest.mark.parametrize(
+ "mount_path", ["/mnt/data/cache", "/mnt/other", "/tmp/opensandbox-execd"]
+ )
+ @pytest.mark.asyncio
+ async def test_nested_and_repeated_source_mounts_allowed(self, mock_docker, mount_path):
+ mock_client = MagicMock()
+ mock_client.containers.list.return_value = []
+ mock_client.api.inspect_volume.return_value = {"Name": "shared-data"}
+ mock_client.api.create_host_config.return_value = {}
+ mock_client.api.create_container.return_value = {"Id": "cid"}
+ mock_client.containers.get.return_value = MagicMock()
+ mock_docker.from_env.return_value = mock_client
+ service = DockerSandboxService(config=_app_config())
+
+ request = CreateSandboxRequest(
+ image=ImageSpec(uri="python:3.11"),
+ timeout=120,
+ resourceLimits=ResourceLimits(root={}),
+ entrypoint=["python"],
+ volumes=[
+ Volume(
+ name="data",
+ pvc=PVC(claim_name="shared-data"),
+ mount_path="/mnt/data",
+ ),
+ Volume(
+ name="other",
+ pvc=PVC(claim_name="shared-data"),
+ mount_path=mount_path,
+ ),
+ ],
+ )
+
+ with (
+ patch.object(service, "_ensure_image_available"),
+ patch.object(service, "_prepare_sandbox_runtime"),
+ ):
+ response = await service.create_sandbox(request)
+
+ assert response.status.state == "Running"
+ mock_client.api.create_container.assert_called_once()
+ assert mock_client.api.create_host_config.call_args.kwargs["binds"] == [
+ "shared-data:/mnt/data:rw",
+ f"shared-data:{mount_path}:rw",
+ ]
+
@pytest.mark.asyncio
async def test_pvc_volume_not_found_rejected(self, mock_docker):
"""PVC backend with non-existent Docker named volume should be rejected when createIfNotExists is false."""
diff --git a/server/tests/test_validators.py b/server/tests/test_validators.py
index dbe369594..bd7923e4d 100644
--- a/server/tests/test_validators.py
+++ b/server/tests/test_validators.py
@@ -489,6 +489,23 @@ class TestEnsureVolumesValid:
assert exc_info.value.status_code == 400
assert exc_info.value.detail["code"] == SandboxErrorCodes.DUPLICATE_VOLUME_NAME
+ @pytest.mark.parametrize("mount_path", ["/", "/mnt/data", "/mnt/data/", "/mnt/./data"])
+ def test_mount_destination_constraints_are_runtime_specific(self, mount_path):
+ volumes = [
+ Volume(
+ name="data",
+ pvc=PVC(claim_name="shared-data"),
+ mount_path="/mnt/data",
+ ),
+ Volume(
+ name="other",
+ pvc=PVC(claim_name="shared-data"),
+ mount_path=mount_path,
+ ),
+ ]
+
+ assert ensure_volumes_valid(volumes) is None
+
def test_invalid_volume_name_rejected_by_pydantic(self):
from pydantic import ValidationError