Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/agents/sandbox/sandboxes/docker_removal.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
user before binding, as normal session startup does.
Path-only grant roots must exist at binding time;
the client does not create unrelated grant directories.
Canonical workspace/grant roots and removal targets must not contain backslashes.
Read-only host bind mounts are supported outside the private workspace. Writable
shared mounts, additional capabilities, user namespaces, and missing grant roots are excluded.
The application must exclusively own container lifecycle and Docker API access;
Expand Down Expand Up @@ -322,6 +323,11 @@ def _bind_new(
paths=[manifest.root, *(grant.path for grant in manifest.extra_path_grants)],
)
paths = result["paths"]
# Linux canonical names must not be reinterpreted as caller path syntax.
if any("\\" in path for path in paths):
raise ValueError(
"Docker removal does not support canonical paths containing backslashes"
)
root = coerce_posix_path(paths[0])
for grant, path in zip(manifest.extra_path_grants, paths[1:], strict=True):
mounted = coerce_posix_path(path)
Expand Down Expand Up @@ -398,6 +404,12 @@ def remove(
)
target = inspection["path"]
if target:
# Policy coercion would treat literal Linux backslashes as separators.
if "\\" in target:
raise WorkspaceArchiveWriteError(
path=posix_path_for_error(original),
context={"reason": "docker_removal_canonical_path"},
)
selected = coerce_posix_path(target)
root = binding.policy.normalize_sandbox_path(".")
live_roots = (
Expand Down
44 changes: 44 additions & 0 deletions tests/sandbox/test_docker_removal.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,50 @@
service = removal_helpers.service


@pytest.mark.parametrize("bound_path", ["/workspace", "/external", "/grant-alias"])
def test_binding_rejects_canonical_backslashes(service: Any, bound_path: str) -> None:
manager, container, worker = service
configured = manifest()
worker.aliases[bound_path] = r"/private/\root"
with pytest.raises(ValueError, match="canonical paths containing backslashes"):
manager.bind_new(container, configured)
assert manager._bindings == {}
assert worker.removed == []
assert container.events == ["pause", "close", "unpause"]


@pytest.mark.asyncio
@pytest.mark.parametrize("is_directory", [True, False])
async def test_removal_rejects_canonical_backslashes(
service: Any, monkeypatch: pytest.MonkeyPatch, is_directory: bool
) -> None:
manager, container, worker = service
configured = Manifest(
root="/workspace",
extra_path_grants=(SandboxPathGrant(path="/protected", read_only=True),),
)
manager.bind_new(container, configured)
worker.aliases["/workspace/link/data"] = r"/protected/\..\..\workspace/data"
original_request = worker.request

def request(**data: Any) -> dict[str, Any]:
result = original_request(**data)
if data["operation"] == "inspect":
result["is_directory"] = is_directory
return result

monkeypatch.setattr(worker, "request", request)
current = session(manager, container, configured)
with pytest.raises(WorkspaceArchiveWriteError) as caught:
await current.rm("link/data", recursive=True)
assert caught.value.context["reason"] == "docker_removal_canonical_path"
assert [call["operation"] for call in worker.calls] == ["bind", "inspect"]
assert worker.removed == []
assert not container.attrs["State"]["Paused"]
await current.rm("build", recursive=True)
assert worker.removed == ["/workspace/build"]


@pytest.mark.asyncio
@pytest.mark.parametrize(("bound", "change_grants"), [(True, True), (True, False), (False, True)])
async def test_live_manifest_update_preserves_removal_authority(
Expand Down
39 changes: 39 additions & 0 deletions tests/sandbox/test_docker_removal_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,45 @@
)


@pytest.mark.asyncio
async def test_removal_preserves_protected_literal_backslash_tree(
service: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
manager, container, worker = service
workspace = tmp_path.resolve() / "workspace"
workspace.mkdir()
protected = tmp_path.resolve() / "protected"
target = protected / r"\..\workspace" / "data"
target.mkdir(parents=True)
sentinel = target / "sentinel.txt"
sentinel.write_text("protected contents")
(workspace / "link").symlink_to(target.parent, target_is_directory=True)
configured = Manifest(
root=workspace.as_posix(),
extra_path_grants=(SandboxPathGrant(path=protected.as_posix(), read_only=True),),
)
manager.bind_new(container, configured)
original_request = worker.request
selected_paths: list[str] = []

def request(**data: Any) -> dict[str, Any]:
result = original_request(**data)
if data["operation"] == "inspect":
selected, is_directory = worker_code._selected_path(data["path"])
selected_paths.append(selected)
result.update(path=selected, is_directory=is_directory)
return result

monkeypatch.setattr(worker, "request", request)
with pytest.raises(WorkspaceArchiveWriteError) as caught:
await session(manager, container, configured).rm("link/data", recursive=True)
assert caught.value.context["reason"] == "docker_removal_canonical_path"
assert selected_paths == [target.as_posix()]
assert worker.removed == []
assert sentinel.read_text() == "protected contents"
assert not container.attrs["State"]["Paused"]


def test_empty_directory_needs_no_search_of_its_contents(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
worker_code.os, "lstat", lambda _, **kwargs: SimpleNamespace(st_mode=0o040000)
Expand Down
Loading