From 27f442fa0515718cac068580cc381a29167c6311 Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Thu, 19 Nov 2026 17:57:46 -0500 Subject: [PATCH 01/15] feat(env-providers): tear down one slot of a shared VM tear_down_slot ends one slot's stack, leaving the VM and every other slot running: it removes the containers, volumes and networks its compose project labels, then its dir and scratch files. It needs no compose file, so it also clears a slot whose deploy failed early, and it is idempotent, so a retry is safe. It refuses the default stack and any layout not made by for_slot, so its file glob can't reach another stack's files. Nothing calls it yet. Co-Authored-By: Claude Opus 5.5 --- .../env_providers/env_gateway_provider.py | 17 ++++ .../providers/env_providers/stack_layout.py | 27 +++++++ .../env_providers/slot_teardown_test.py | 79 +++++++++++++++++++ .../env_providers/stack_layout_test.py | 55 +++++++++++++ 4 files changed, 178 insertions(+) create mode 100644 tst/integration/providers/env_providers/slot_teardown_test.py diff --git a/src/agent_env/providers/env_providers/env_gateway_provider.py b/src/agent_env/providers/env_providers/env_gateway_provider.py index bafe2b816..c352bbfff 100644 --- a/src/agent_env/providers/env_providers/env_gateway_provider.py +++ b/src/agent_env/providers/env_providers/env_gateway_provider.py @@ -135,6 +135,23 @@ def uses_database(self) -> bool: return _ENV_NETWORK in self.networks +TEARDOWN_RETRIES = 2 + + +async def tear_down_slot(sandbox: Sandbox, layout: StackLayout) -> None: + """End one slot's stack on a VM other slots share, leaving the VM and every other slot running. Idempotent, so a + retry after a dropped connection is safe. Raises for the default stack, or for a sandbox that is not a VM, since + only a VM holds slots; raises too if the script fails, so the caller never counts a slot gone that isn't. + + The caller must first cancel or await the slot's own deploy: a ``compose up`` still running can create containers + after the script has listed them, and the slot would be counted gone while it still holds its ports.""" + if not layout.is_slot: + raise ValueError("tear_down_slot ends one slot of a shared VM; the default stack ends with its VM") + if sandbox.mode != SANDBOX_MODE_VM: + raise ValueError(f"slot {layout.compose_project} can only be on a VM, not a {sandbox.mode} sandbox") + await sandbox.exec_script(layout.teardown_script, max_retries=TEARDOWN_RETRIES) + + @dataclass class DeployedGateway: """Result of a gateway deployment.""" diff --git a/src/agent_env/providers/env_providers/stack_layout.py b/src/agent_env/providers/env_providers/stack_layout.py index f3277ec36..04ff5c723 100644 --- a/src/agent_env/providers/env_providers/stack_layout.py +++ b/src/agent_env/providers/env_providers/stack_layout.py @@ -8,6 +8,7 @@ import posixpath import re +import shlex from dataclasses import dataclass from agent_env.providers.env_providers.constants import GATEWAY_APP_DIR @@ -133,6 +134,32 @@ def from_record(cls, data: object) -> StackLayout: raise ValueError(f"a recorded stack layout must be a slot's, got {data!r}") return layout + @property + def teardown_script(self) -> str: + """A root shell script that removes this slot's stack and nothing else on the VM: every container, volume and + network its compose project labels, then its dir and scratch files. Images stay, since every stack on the VM + shares them. Idempotent, and it needs no compose file, so it also clears a slot whose deploy failed before + writing one. Raises for the default stack, which has the VM to itself and goes with it, and for any layout + not made by ``for_slot``: a hand-built project such as ``s1-x`` would have its files caught by ``s1``'s glob.""" + if not self.is_slot: + raise ValueError("only a slot's stack is torn down on its own; the default stack ends with its VM") + index = self.compose_project[1:] + if not (self.compose_project.startswith("s") and index.isascii() and index.isdigit() + and self == StackLayout.for_slot(int(index))): + raise ValueError(f"only a layout made by StackLayout.for_slot is torn down, so its dir and scratch glob " + f"can't reach another stack's files; got {self}") + label = shlex.quote(f"label=com.docker.compose.project={self.compose_project}") + return "\n".join([ + "set -eu", + f"containers=$(docker ps -aq --filter {label})", + '[ -z "$containers" ] || docker rm -f -v $containers >/dev/null', + f"volumes=$(docker volume ls -q --filter {label})", + '[ -z "$volumes" ] || docker volume rm -f $volumes >/dev/null', + f"networks=$(docker network ls -q --filter {label})", + '[ -z "$networks" ] || docker network rm $networks >/dev/null', + f"rm -rf {shlex.quote(self.app_dir)} {shlex.quote(self.scratch_prefix)}*", + ]) + def scratch_path(self, name: str) -> str: return f"{self.scratch_prefix}{name}" diff --git a/tst/integration/providers/env_providers/slot_teardown_test.py b/tst/integration/providers/env_providers/slot_teardown_test.py new file mode 100644 index 000000000..b9303700a --- /dev/null +++ b/tst/integration/providers/env_providers/slot_teardown_test.py @@ -0,0 +1,79 @@ +"""``StackLayout.teardown_script`` against a real Docker daemon: it ends one slot's containers, volumes, networks, dir and +scratch files, and leaves a neighbouring slot whole. The script runs in a throwaway Docker CLI container that holds the +slots' dirs, so it never touches this machine's /app or /tmp. Needs Docker.""" + +import shutil +import subprocess +import uuid +from pathlib import Path + +import pytest + +from agent_env.providers.env_providers.stack_layout import StackLayout +from tst.util.capabilities import missing_capability_reason + +pytestmark = [pytest.mark.integration, pytest.mark.int_test_slow] + +BUSYBOX = "mirror.gcr.io/library/busybox:1.37" +DOCKER_CLI = "mirror.gcr.io/library/docker:28-cli" +COMPOSE = f"""services: + web: + image: {BUSYBOX} + command: ["sleep", "3600"] + volumes: ["data:/data", "/scratch"] +volumes: + data: {{}} +""" +GONE, KEPT = StackLayout.for_slot(43), StackLayout.for_slot(44) + + +def _docker(*args: str) -> str: + return subprocess.run(["docker", *args], check=True, capture_output=True, text=True).stdout + + +def _labelled(kind: str, layout: StackLayout) -> list[str]: + listing = ["ps", "-aq"] if kind == "container" else [kind, "ls", "-q"] + return _docker(*listing, "--filter", f"label=com.docker.compose.project={layout.compose_project}").split() + + +@pytest.fixture +def two_slots(tmp_path: Path): + if shutil.which("docker") is None or subprocess.run(["docker", "info"], capture_output=True).returncode != 0: + pytest.skip(missing_capability_reason("docker_daemon")) + compose_file = tmp_path / "docker-compose.yml" + compose_file.write_text(COMPOSE) + for layout in (GONE, KEPT): + _docker("compose", "-p", layout.compose_project, "-f", str(compose_file), "up", "-d", "--quiet-pull") + try: + yield + finally: + for layout in (GONE, KEPT): + subprocess.run(["docker", "compose", "-p", layout.compose_project, "-f", str(compose_file), "down", "-v"], + capture_output=True) + + +def _run_teardown_twice_beside_both_slots_files() -> str: + files = f"{GONE.app_dir} {KEPT.app_dir} {GONE.scratch_path('pgdata')} {KEPT.scratch_path('pgdata')} /tmp/s430-other" + script = "\n".join([ + f"mkdir -p {GONE.app_dir} {KEPT.app_dir} && touch {GONE.scratch_path('pgdata')} {KEPT.scratch_path('pgdata')} " + "/tmp/s430-other", + GONE.teardown_script, + GONE.teardown_script, + f"for f in {files}; do [ -e $f ] && echo kept $f || echo gone $f; done", + ]) + return _docker("run", "--rm", "--name", f"slot-teardown-{uuid.uuid4().hex[:8]}", + "-v", "/var/run/docker.sock:/var/run/docker.sock", DOCKER_CLI, "sh", "-c", script) + + +def test_tearing_down_one_slot_ends_its_stack_and_files_and_leaves_its_neighbour_whole(two_slots): + kept_before = {kind: _labelled(kind, KEPT) for kind in ("container", "volume", "network")} + assert all(kept_before.values()) and all(_labelled(kind, GONE) for kind in kept_before) + + report = _run_teardown_twice_beside_both_slots_files() + + assert {kind: _labelled(kind, GONE) for kind in kept_before} == {"container": [], "volume": [], "network": []} + assert {kind: _labelled(kind, KEPT) for kind in kept_before} == kept_before + assert report.split("\n")[:-1] == [ + f"gone {GONE.app_dir}", f"kept {KEPT.app_dir}", f"gone {GONE.scratch_path('pgdata')}", + f"kept {KEPT.scratch_path('pgdata')}", "kept /tmp/s430-other", + ] diff --git a/tst/unit/providers/env_providers/stack_layout_test.py b/tst/unit/providers/env_providers/stack_layout_test.py index 9a6ccf1f0..199c71de4 100644 --- a/tst/unit/providers/env_providers/stack_layout_test.py +++ b/tst/unit/providers/env_providers/stack_layout_test.py @@ -11,9 +11,11 @@ from agent_env.env.envs.service_db import DB_MCP_PORT, DB_WEB_PORT, ServiceDBConfig from agent_env.env.gateway import AGENT_ENV_GATEWAY_MCP_PORT from agent_env.providers.env_providers.env_gateway_provider import ( + TEARDOWN_RETRIES, EnvironmentGatewayProvider, MCPServerConfig, SidecarConfig, + tear_down_slot, ) from agent_env.providers.env_providers.stack_layout import DEFAULT_STACK_LAYOUT, StackLayout @@ -395,3 +397,56 @@ def test_the_default_stack_records_nothing_and_a_record_without_a_layout_is_the_ def test_a_damaged_recorded_layout_is_refused_rather_than_read_as_the_default_stack(data): with pytest.raises((ValueError, TypeError)): StackLayout.from_record(data) + + +def test_the_default_stack_is_never_torn_down_on_its_own(): + with pytest.raises(ValueError, match="default stack"): + DEFAULT_STACK_LAYOUT.teardown_script + + +@pytest.mark.parametrize("layout", [ + StackLayout(compose_project="s1"), + StackLayout(app_dir="/app/s2", compose_project="s1", scratch_prefix="/tmp/s1-"), + StackLayout(app_dir="/app/s1", compose_project="s1", scratch_prefix="/tmp/"), + StackLayout(app_dir="/app/s1", compose_project="s1", scratch_prefix="/tmp/s1"), + StackLayout(app_dir="/app/s1-x", compose_project="s1-x", scratch_prefix="/tmp/s1-x-", host_port_offset=2000), + StackLayout(app_dir="/app/s1", compose_project="s1", scratch_prefix="/tmp/s1-", host_port_offset=5000), + StackLayout(app_dir="/app/web", compose_project="web", scratch_prefix="/tmp/web-", host_port_offset=1000), + StackLayout(app_dir="/app/s01", compose_project="s01", scratch_prefix="/tmp/s01-", host_port_offset=2000), +]) +def test_a_slot_layout_not_made_by_for_slot_is_never_torn_down(layout): + with pytest.raises(ValueError, match="for_slot"): + layout.teardown_script + + +def test_a_slots_teardown_names_only_its_own_project_dir_and_scratch_files(): + script = StackLayout.for_slot(7).teardown_script + assert script.count("label=com.docker.compose.project=s7") == 3 + assert script.splitlines()[-1] == "rm -rf /app/s7 /tmp/s7-*" + + +@pytest.mark.asyncio +async def test_tearing_down_a_slot_runs_its_script_on_the_vm_and_may_retry(): + vm = _RecordingVm([], set()) + vm.exec_script = AsyncMock(return_value="") + await tear_down_slot(vm, StackLayout.for_slot(2)) + vm.exec_script.assert_awaited_once_with(StackLayout.for_slot(2).teardown_script, max_retries=TEARDOWN_RETRIES) + + +@pytest.mark.asyncio +async def test_a_failed_slot_teardown_raises_so_the_slot_is_never_counted_gone(): + vm = _RecordingVm([], set()) + vm.exec_script = AsyncMock(side_effect=RuntimeError("Script failed (exit 1)")) + with pytest.raises(RuntimeError, match="exit 1"): + await tear_down_slot(vm, StackLayout.for_slot(2)) + + +@pytest.mark.asyncio +async def test_only_a_slot_on_a_vm_can_be_torn_down(): + vm = _RecordingVm([], set()) + with pytest.raises(ValueError, match="default stack"): + await tear_down_slot(vm, DEFAULT_STACK_LAYOUT) + vm.mode = "container" + with pytest.raises(ValueError, match="only be on a VM"): + await tear_down_slot(vm, StackLayout.for_slot(2)) + assert vm.calls == [] From 7b8f7cb42bed967fc309eb2255cd3ebaa6ef997f Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Thu, 19 Nov 2026 18:39:17 -0500 Subject: [PATCH 02/15] feat(sandbox-providers): a shared Modal VM is ended only by terminate_shared_box Several tasks' slots will share one Modal VM, a shared box, so no single task's close may end it. Every Modal terminate now goes through one check: a handle this process created terminates as before; one reattached by id, and terminate_sandbox, first read the sandbox's tags and refuse, with SharedBoxTerminateRefused, to end one tagged agent_env_shared_box. A tag read that keeps failing raises and terminates nothing. create_shared_box tags the VM at create, and terminate_shared_box ends a box only when its tag names that box. Callers already log a failed terminate, and a teardown reports the box as not terminated. Nothing creates boxes yet. Co-Authored-By: Claude Opus 5.5 --- .../providers/sandbox_providers/AGENTS.md | 1 + .../sandbox_providers/modal_sandbox.py | 86 +++++- .../sandbox_providers/modal_vm_sandbox.py | 48 +++- .../sandbox_providers/sandbox_provider.py | 15 + tst/unit/env/envs/shared_box_close_test.py | 130 +++++++++ .../sandbox_providers/modal_sandbox_test.py | 1 + .../modal_shared_box_test.py | 269 ++++++++++++++++++ .../modal_vm_sandbox_test.py | 1 + tst/unit/task/teardown_test.py | 1 + 9 files changed, 542 insertions(+), 10 deletions(-) create mode 100644 tst/unit/env/envs/shared_box_close_test.py create mode 100644 tst/unit/providers/sandbox_providers/modal_shared_box_test.py diff --git a/src/agent_env/providers/sandbox_providers/AGENTS.md b/src/agent_env/providers/sandbox_providers/AGENTS.md index 4727eaff5..dc9e92321 100644 --- a/src/agent_env/providers/sandbox_providers/AGENTS.md +++ b/src/agent_env/providers/sandbox_providers/AGENTS.md @@ -54,6 +54,7 @@ with `exposed_ports=[port]` and returns the VM, and the deploy then loads and st | `create_sandbox(*, image_name, port, env, cpu, memory, disk_size_gb, timeout, attribution, network_policy) -> Sandbox` | yes (a VM backend wraps `create_vm`) | an agent's sandbox (`provider.create_sandbox`); `create_container` of a container-only backend | | `get_sandbox(sandbox_id) -> Sandbox` | yes | every step after the one that created the sandbox, and teardown | | `terminate_sandbox(sandbox_id)` | no | teardown. The default calls `get_sandbox` then `terminate()`, and treats `SandboxNotFoundError` as done; override when you can terminate without a live handle | +| `create_shared_box(box_id, *, cpu, memory, timeout, exposed_ports, setup_for_gateway, attribution, network_policy) -> VmSandbox` | no | nothing yet: a VM for several tasks' slots. The default raises `NotImplementedError`; `modal_vm` tags the VM with `SHARED_BOX_TAG` at create, refuses to end it from its handle's `terminate()` or `terminate_sandbox`, raising `SharedBoxTerminateRefused`, and ends it only through `terminate_shared_box(sandbox_id, box_id)` | | `create_container(...)` | inherited | containers that run an env or agent image. Override only when the platform boots images natively. Its `shm_mb` is the MiB the container's `/dev/shm` holds (`--shm-size` on the default VM path), passed only where `SHARED_MEMORY` is on | | `reset_container(sandbox, *, image_name, port, env, shm_mb)` | inherited | a computer env's reset, which replaces the container `create_container` ran with a fresh one on the same sandbox and port, its `/dev/shm` as before. The default works on a VM backend; one whose sandbox is the container itself raises `NotImplementedError` | | `native_platforms()` | no | a computer env's deploy and gate 3, which boot a build only on a provider that runs its arch without emulation. The default is `linux/amd64`; local Docker returns this machine's | diff --git a/src/agent_env/providers/sandbox_providers/modal_sandbox.py b/src/agent_env/providers/sandbox_providers/modal_sandbox.py index 43c9907de..4438d2b13 100644 --- a/src/agent_env/providers/sandbox_providers/modal_sandbox.py +++ b/src/agent_env/providers/sandbox_providers/modal_sandbox.py @@ -6,6 +6,7 @@ import base64 import collections import contextlib +import enum import functools import hashlib import logging @@ -30,6 +31,7 @@ if TYPE_CHECKING: from agent_env.artifact.artifacts.docker_image import DockerImageArtifact + from agent_env.providers.sandbox_providers.modal_vm_sandbox import ModalVmSandbox logger = logging.getLogger(__name__) @@ -95,14 +97,86 @@ def _tunnel_url(t) -> str: return f"https://{t.host}" + (f":{t.port}" if t.port != 443 else "") -async def _terminate_by_id(client, sandbox_id: str) -> None: +#: The Modal sandbox tag that marks a VM as a shared box, several tasks' slots on one VM; its value is the box's id. +SHARED_BOX_TAG = "agent_env_shared_box" +SHARED_BOX_TAG_READ_FAILED_EVENT = "agent_env.modal_shared_box_tag_read_failed" +_TAG_READ_ATTEMPTS, _TAG_READ_BACKOFF_SECONDS = 3, 1.0 + + +class _Unread(enum.Enum): + UNREAD = "unread" + + +#: A handle's ``shared_box_id`` before its tags are read: one this process reattached to by id. +UNREAD = _Unread.UNREAD +SharedBox = Optional[str] | _Unread + + +class SharedBoxTerminateRefused(Exception): + """A terminate that would have ended a shared box, or a ``terminate_shared_box`` naming a box the sandbox isn't; + the sandbox was left running.""" + + def __init__(self, sandbox_id: str, box_id: Optional[str], ending_box: Optional[str] = None): + self.sandbox_id, self.box_id = sandbox_id, box_id + if ending_box is None: + why = f"is shared box {box_id!r}, which only terminate_shared_box ends" + else: + why = f"is {f'shared box {box_id!r}' if box_id else 'no shared box'}, not shared box {ending_box!r}" + super().__init__(f"Modal sandbox {sandbox_id} {why}; it was not terminated") + + +async def _read_shared_box(sb: modal.Sandbox) -> Optional[str]: + """The shared box ``sb`` is tagged as, if any. A read that keeps failing raises, so a terminate fails closed; + NotFoundError raises at once.""" + attempt = 1 + while True: + try: + return (await sb.get_tags.aio()).get(SHARED_BOX_TAG) + except modal.exception.NotFoundError: + raise + except Exception as e: + if attempt == _TAG_READ_ATTEMPTS: + logger.warning(f"Modal sandbox {sb.object_id} was not terminated: its tags, which say whether it's a " + f"shared box, couldn't be read: {fmt_exc(e)}", + extra={"event": SHARED_BOX_TAG_READ_FAILED_EVENT, "modal_sandbox_id": sb.object_id}) + raise + await asyncio.sleep(_TAG_READ_BACKOFF_SECONDS * 2 ** (attempt - 1)) + attempt += 1 + + +async def _terminate(sb: modal.Sandbox, box: SharedBox, *, ending_box: Optional[str] = None) -> None: + """Terminate ``sb`` when it is the shared box ``ending_box``, or, with none, when it is no shared box; else raise + SharedBoxTerminateRefused. Every Modal terminate goes through here but the cleanup of a create that failed, whose + sandbox holds no slots yet. ``box`` is what the caller knows of ``sb``; UNREAD reads its tags, and one gone already + counts as terminated.""" + if box is UNREAD: + try: + box = await _read_shared_box(sb) + except modal.exception.NotFoundError: + logger.info("Modal sandbox %s was already gone at terminate", sb.object_id) + return + if box != ending_box: + raise SharedBoxTerminateRefused(sb.object_id, box, ending_box) + await sb.terminate.aio() + + +async def _terminate_by_id(client, sandbox_id: str, *, ending_box: Optional[str] = None) -> None: try: sb = await modal.Sandbox.from_id.aio(sandbox_id, client=client) - await sb.terminate.aio() + await _terminate(sb, UNREAD, ending_box=ending_box) except modal.exception.NotFoundError: logger.info("Modal sandbox %s was already gone at terminate", sandbox_id) +async def _terminate_handle(handle: ModalSandbox | ModalVmSandbox) -> None: + """Terminate a handle's sandbox through ``_terminate``, keeping the shared box a refusal found on the handle.""" + try: + await _terminate(handle._sb, handle.shared_box_id) + except SharedBoxTerminateRefused as refused: + handle.shared_box_id = refused.box_id + raise + + def _modal_network_kwargs(policy: NetworkPolicy) -> dict: """``policy`` as Modal sandbox creation kwargs. @@ -194,8 +268,9 @@ class ModalSandbox(Sandbox): type = "modal" def __init__(self, sb: modal.Sandbox, tunnel_urls: dict[int, str], i6pn_address: Optional[str] = None, - network_policy: NetworkPolicy | None = None): + network_policy: NetworkPolicy | None = None, shared_box_id: SharedBox = UNREAD): self._sb = sb + self.shared_box_id = shared_box_id self.sandbox_id = sb.object_id self.tunnel_urls = tunnel_urls self.i6pn_address = i6pn_address @@ -210,7 +285,7 @@ def private_host(self) -> str | None: return f"[{self.i6pn_address}]" if self.i6pn_address else None async def terminate(self) -> None: - await self._sb.terminate.aio() + await _terminate_handle(self) async def exit_status(self) -> Optional[int]: return await self._sb.poll.aio() @@ -511,6 +586,7 @@ async def create_rebuilding_once() -> modal.Sandbox: tunnel_urls, i6pn_address=i6pn_address, network_policy=effective, + shared_box_id=None, ) if vnc_port in tunnel_urls: sandbox.vnc_url = f"{tunnel_urls[vnc_port]}/vnc.html" @@ -589,6 +665,8 @@ def _attribution_tags(attribution: Attribution) -> dict[str, str]: continue if not _MODAL_TAG_KEY.fullmatch(key): raise ValueError(f"attribution key {key!r} can't be a Modal tag: use 1-63 of a-z A-Z 0-9 . _ -") + if key == SHARED_BOX_TAG: + raise ValueError(f"attribution key {key!r} is the tag that marks a shared box; only create_shared_box sets it") tags[key] = _modal_tag_value(value) return tags diff --git a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py index f54d90f1a..ec6df5558 100644 --- a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py +++ b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py @@ -34,6 +34,10 @@ import modal from agent_env.providers.sandbox_providers.modal_sandbox import ( + _MODAL_TAG_KEY, + SHARED_BOX_TAG, + UNREAD, + SharedBox, _ModalProcessAdapter, _attribution_tags, _ended_output, @@ -41,6 +45,7 @@ _log_sandbox_started, _resolve_app_base_name, _terminate_by_id, + _terminate_handle, _tunnel_url, _modal_network_kwargs, ) @@ -144,8 +149,9 @@ class ModalVmSandbox(VmSandbox): _WFT_CHUNK_BYTES = 32 * 1024 def __init__(self, sb: modal.Sandbox, tunnel_urls: dict[int, str], - network_policy: NetworkPolicy | None = None): + network_policy: NetworkPolicy | None = None, shared_box_id: SharedBox = UNREAD): self._sb = sb + self.shared_box_id = shared_box_id self.sandbox_id = sb.object_id self.tunnel_urls = tunnel_urls self.vnc_url = None @@ -155,7 +161,7 @@ def __init__(self, sb: modal.Sandbox, tunnel_urls: dict[int, str], self._ended: Optional[tuple[list[str], list[str]]] = None async def terminate(self) -> None: - await self._sb.terminate.aio() + await _terminate_handle(self) async def exit_status(self) -> Optional[int]: return await self._sb.poll.aio() @@ -399,6 +405,33 @@ async def create_vm( experimental_options={"enable_nested_virt": True}, secrets=[modal.Secret.from_dict(variables)], idle_timeout=self._idle_timeout or _DISK_IDLE_TIMEOUT_S) + async def create_shared_box( + self, + box_id: str, + *, + cpu: float = 0.5, + memory: int = 8192, + timeout: int = 3600 * 2, + exposed_ports: Optional[list[int]] = None, + setup_for_gateway: bool = True, + attribution: Optional[Attribution] = None, + network_policy: Optional[NetworkPolicy] = None, + ) -> ModalVmSandbox: + """A VM running Docker, as ``create_vm`` makes, tagged as shared box ``box_id`` at create, since a later + ``set_tags`` would replace its attribution tags. Its handle's terminate, and ``terminate_sandbox``, refuse to end + it: only ``terminate_shared_box`` does.""" + if not _MODAL_TAG_KEY.fullmatch(box_id): + raise ValueError(f"shared box id {box_id!r} can't be a Modal tag: use 1-63 of a-z A-Z 0-9 . _ -") + return await self._created(_KEEPALIVE_CMD, _VM_IMAGE, cpu=cpu, memory=memory, timeout=timeout, + ports=list(exposed_ports or []), attribution=attribution, + network_policy=network_policy, setup_for_gateway=setup_for_gateway, + idle_timeout=self._idle_timeout, runtime="vm", shared_box_id=box_id) + + async def terminate_shared_box(self, sandbox_id: str, box_id: str) -> None: + """End shared box ``box_id``, the sandbox ``sandbox_id``, and every slot on it. A sandbox tagged as another box, + or as none, raises SharedBoxTerminateRefused, and one whose tags can't be read raises; neither is terminated.""" + await _terminate_by_id(await self._get_client(), sandbox_id, ending_box=box_id) + async def reset_vm(self, sandbox: Sandbox, *, image: str, env: dict[str, str]) -> None: """The launcher in the sandbox booting its disk afresh with ``env``, at the same URLs.""" code, _, stderr = await sandbox._exec_with_stdin(shlex.join(RESET), _chunks(reset_input(env))) @@ -408,13 +441,16 @@ async def reset_vm(self, sandbox: Sandbox, *, image: str, env: dict[str, str]) - async def _created(self, command: tuple[str, ...], image: modal.Image, *, cpu: float, memory: int, timeout: int, ports: list[int], attribution: Optional[Attribution], network_policy: Optional[NetworkPolicy], - setup_for_gateway: bool, idle_timeout: Optional[int], **create) -> ModalVmSandbox: + setup_for_gateway: bool, idle_timeout: Optional[int], shared_box_id: Optional[str] = None, + **create) -> ModalVmSandbox: """A sandbox of ``image`` running ``command``, in the configured region, its ports' tunnels up, ended once idle - ``idle_timeout`` seconds when given, set up for a gateway when ``setup_for_gateway``; one that fails before - it's returned is terminated.""" + ``idle_timeout`` seconds when given, set up for a gateway when ``setup_for_gateway``, tagged as shared box + ``shared_box_id`` when given; one that fails before it's returned is terminated.""" attribution = dict(attribution or {}) app_tags = _attribution_tags({}) sandbox_tags = _attribution_tags(attribution) + if shared_box_id is not None: + sandbox_tags[SHARED_BOX_TAG] = shared_box_id app_name = self._app_name app = await self._get_app(app_name, app_tags) client = await self._get_client() @@ -449,7 +485,7 @@ async def _created(self, command: tuple[str, ...], image: modal.Image, *, cpu: f for p in ports: if p not in tunnel_urls: raise RuntimeError(f"No Modal tunnel for exposed port {p}; got {sorted(tunnel_urls)}") - sandbox = ModalVmSandbox(sb, tunnel_urls, network_policy=effective) + sandbox = ModalVmSandbox(sb, tunnel_urls, network_policy=effective, shared_box_id=shared_box_id) logger.info(f"Modal VM sandbox created: {sb.object_id} (tunnels={tunnel_urls})") await _log_sandbox_started( sb, app_name=app_name, sandbox_tags=sandbox_tags, diff --git a/src/agent_env/providers/sandbox_providers/sandbox_provider.py b/src/agent_env/providers/sandbox_providers/sandbox_provider.py index 0d314371c..a6f9f9ae4 100644 --- a/src/agent_env/providers/sandbox_providers/sandbox_provider.py +++ b/src/agent_env/providers/sandbox_providers/sandbox_provider.py @@ -97,6 +97,21 @@ async def create_vm( channel.""" raise NotImplementedError(f"{type(self).__name__} does not support create_vm") + async def create_shared_box( + self, + box_id: str, + *, + cpu: float = 1.0, + memory: int = 8192, + timeout: int = 3600 * 2, + exposed_ports: Optional[list[int]] = None, + setup_for_gateway: bool = True, + attribution: Optional[Attribution] = None, + network_policy: Optional[NetworkPolicy] = None, + ) -> VmSandbox: + """A VM for several tasks' slots, shared box ``box_id``, which no single task's terminate ends.""" + raise NotImplementedError(f"{type(self).__name__} does not support shared boxes") + async def create_container( self, *, diff --git a/tst/unit/env/envs/shared_box_close_test.py b/tst/unit/env/envs/shared_box_close_test.py new file mode 100644 index 000000000..26fbaa91b --- /dev/null +++ b/tst/unit/env/envs/shared_box_close_test.py @@ -0,0 +1,130 @@ +"""No way an env, its provider or a run's teardown closes reaches Modal's terminate for a shared box: each is refused, +logged, and, in a teardown, reported as not terminated.""" + +from __future__ import annotations + +from unittest.mock import AsyncMock, MagicMock + +import modal +import pytest + +from agent_env.env.env import DeployedGatewayEnv +from agent_env.env.envs._deployment import close_deployed, close_replaced +from agent_env.env.envs.computer.env import ComputerEnv +from agent_env.env.envs.mcp_server import MCPServerEnv +from agent_env.env.envs.multi_env import MultiEnv +from agent_env.env.envs.website import WebsiteEnv +from agent_env.providers.env_providers.env_gateway_provider import EnvironmentGatewayProvider +from agent_env.providers.sandbox_providers.modal_sandbox import SHARED_BOX_TAG, ModalSandbox, ModalSandboxProvider +from agent_env.providers.sandbox_providers.modal_vm_sandbox import ModalVmSandbox, ModalVmSandboxProvider +from agent_env.task import teardown +from agent_env.task.teardown import RecordedSandbox +from agent_env.task_step.context import TaskStepContext + + +@pytest.fixture +def box(monkeypatch) -> MagicMock: + """The Modal sandbox of shared box ``box-1``, which ``from_id`` finds, and Modal clients that never connect.""" + sb = MagicMock(object_id="sb-box") + sb.get_tags.aio = AsyncMock(return_value={SHARED_BOX_TAG: "box-1"}) + sb.terminate.aio = AsyncMock() + sb.tunnels.aio = AsyncMock(return_value={}) + sb.exec.aio = AsyncMock(side_effect=RuntimeError("no exec here")) + monkeypatch.setattr(modal.Sandbox, "from_id", MagicMock(aio=AsyncMock(return_value=sb))) + for cls in (ModalVmSandboxProvider, ModalSandboxProvider): + monkeypatch.setattr(cls, "_get_client", AsyncMock(return_value=MagicMock())) + return sb + + +HANDLES = { + "created vm": lambda sb: ModalVmSandbox(sb, {}, shared_box_id="box-1"), + "reattached vm": lambda sb: ModalVmSandbox(sb, {}), + "reattached container": lambda sb: ModalSandbox(sb, {}), +} + + +def _mcp() -> MCPServerEnv: + return MCPServerEnv(id="mcp-email", version=1, docker_image_artifact=None, environment_name="email") + + +def _website() -> WebsiteEnv: + return WebsiteEnv(id="web-email", version=1, backend_docker_image_artifact=None, + frontend_docker_image_artifact=None, environment_name="email") + + +def _multi() -> MultiEnv: + return MultiEnv(id="crm-suite", version=1, mcp_server_envs=[_mcp()]) + + +def _computer() -> ComputerEnv: + return ComputerEnv("desk", 1, "desk", MagicMock(), MagicMock()) + + +async def _env_close(make_env, handle): + env = make_env() + env._env_provider, env._sandbox = None, handle + await env.close() + + +async def _close_replaced(handle): + env = _mcp() + env._replaced = [(None, handle)] + await close_replaced(env) + + +async def _env_provider_close(handle): + provider = EnvironmentGatewayProvider() + provider._container_sandboxes = [handle] + await provider.close() + + +HANDLE_PATHS = { + "MCPServerEnv.close": lambda handle: _env_close(_mcp, handle), + "WebsiteEnv.close": lambda handle: _env_close(_website, handle), + "MultiEnv.close": lambda handle: _env_close(_multi, handle), + "ComputerEnv.close": lambda handle: _env_close(_computer, handle), + "close_replaced": _close_replaced, + "EnvProvider.close": _env_provider_close, +} + + +@pytest.mark.parametrize("handle", HANDLES.values(), ids=HANDLES.keys()) +@pytest.mark.parametrize("close", HANDLE_PATHS.values(), ids=HANDLE_PATHS.keys()) +@pytest.mark.asyncio +async def test_closing_a_handle_to_a_shared_box_leaves_it_running(box, close, handle): + await close(handle(box)) + + box.terminate.aio.assert_not_called() + + +@pytest.mark.parametrize("sandbox_type", ["modal_vm", "modal"]) +@pytest.mark.asyncio +async def test_close_deployed_of_a_plugins_deployment_on_a_shared_box_leaves_it_running(box, monkeypatch, sandbox_type): + env = _mcp() + env._env_provider = object() + monkeypatch.setattr(MCPServerEnv, "from_deployed_env", AsyncMock(return_value=env)) + deployed = DeployedGatewayEnv(env_id="mcp-email", env_version=1, gateway_url="http://g", sandbox_id="sb-box", + sandbox_type=sandbox_type) + + await close_deployed(deployed, MCPServerEnv) + + box.terminate.aio.assert_not_called() + + +@pytest.mark.parametrize("sandbox_type, default", [ + ("modal_vm", None), ("modal", None), (None, ModalVmSandboxProvider), (None, ModalSandboxProvider)], + ids=["by id on modal_vm", "by id on modal", "reattached on modal_vm", "reattached on modal"]) +@pytest.mark.asyncio +async def test_a_teardown_reports_a_shared_box_not_terminated_and_leaves_it_running(box, monkeypatch, sandbox_type, + default): + if default is not None: + monkeypatch.setitem(teardown._DEFAULT_PROVIDERS, "env", default) + context = TaskStepContext() + sandbox = RecordedSandbox("sb-box", sandbox_type, "env") + + report = await teardown.tear_down(context, [sandbox], [], timeout=5) + + box.terminate.aio.assert_not_called() + assert report.terminated == () + assert [(failed, "shared box 'box-1'" in why) for failed, why in report.failed] == [(sandbox, True)] + assert teardown.TORN_DOWN_KEY not in context.metadata diff --git a/tst/unit/providers/sandbox_providers/modal_sandbox_test.py b/tst/unit/providers/sandbox_providers/modal_sandbox_test.py index 5c745ec58..d24c42068 100644 --- a/tst/unit/providers/sandbox_providers/modal_sandbox_test.py +++ b/tst/unit/providers/sandbox_providers/modal_sandbox_test.py @@ -463,6 +463,7 @@ async def collect(chunks, destination_path): async def test_terminate_sandbox_terminates_by_id_without_reading_its_tunnels(_patched_provider): sb = MagicMock() sb.tunnels.aio = AsyncMock(side_effect=modal.exception.ConflictError("Sandbox has already finished with status terminated")) + sb.get_tags.aio = AsyncMock(return_value={}) sb.terminate.aio = AsyncMock() with patch("agent_env.providers.sandbox_providers.modal_sandbox.modal.Sandbox.from_id") as from_id: from_id.aio = AsyncMock(return_value=sb) diff --git a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py new file mode 100644 index 000000000..24e1f8654 --- /dev/null +++ b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py @@ -0,0 +1,269 @@ +"""A shared box, one Modal VM holding several tasks' slots, is ended only by ``terminate_shared_box``: every other Modal +terminate reads whether its sandbox is one, unless this process made it, and refuses to end one.""" + +from __future__ import annotations + +import ast +import logging +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock + +import modal +import pytest + +from agent_env.attribution import PIPELINE_STEP_KEY +from agent_env.config import get_config, reset_config +from agent_env.providers.sandbox_providers import modal_sandbox +from agent_env.providers.sandbox_providers.modal_sandbox import ( + SHARED_BOX_TAG, + SHARED_BOX_TAG_READ_FAILED_EVENT, + ModalSandboxProvider, + SharedBoxTerminateRefused, +) +from agent_env.providers.sandbox_providers.modal_vm_sandbox import ModalVmSandboxProvider +from tst.unit.store.fakes import FakeImageStore + +BOX = {SHARED_BOX_TAG: "box-1"} + + +@pytest.fixture(autouse=True) +def _offline(monkeypatch): + get_config().set_image_store(FakeImageStore()) + monkeypatch.setattr(modal_sandbox, "_TAG_READ_BACKOFF_SECONDS", 0) + yield + reset_config() + + +def modal_sb(tags=None, *, tag_reads=None, sandbox_id="sb-1") -> MagicMock: + """A Modal sandbox whose tags are ``tags``, or whose reads go as ``tag_reads``, recording its terminate.""" + sb = MagicMock(object_id=sandbox_id) + sb.get_tags.aio = AsyncMock(side_effect=tag_reads) if tag_reads else AsyncMock(return_value=dict(tags or {})) + sb.terminate.aio = AsyncMock() + sb.tunnels.aio = AsyncMock(return_value={}) + sb.wait_until_ready.aio = AsyncMock() + sb._get_task_id.aio = AsyncMock(return_value="ta-1") + sb.exec.aio = AsyncMock(side_effect=RuntimeError("no exec here")) + return sb + + +def provider(cls): + p = cls(app_name="agent-env-test") + p._get_app = AsyncMock(return_value=MagicMock()) + p._get_client = AsyncMock(return_value=MagicMock()) + return p + + +@pytest.fixture +def modal_api(monkeypatch): + """Patch Modal's create and from_id to hand out the sandbox a test sets as ``modal_api.sb``.""" + api = MagicMock() + api.create = AsyncMock(side_effect=lambda *a, **kw: api.sb) + api.from_id = AsyncMock(side_effect=lambda *a, **kw: api.sb) + monkeypatch.setattr(modal.Sandbox, "create", MagicMock(aio=api.create)) + monkeypatch.setattr(modal.Sandbox, "from_id", MagicMock(aio=api.from_id)) + return api + + +async def created_vm(p): + return await p.create_vm(setup_for_gateway=False) + + +async def created_container(p): + return await p.create_container(image_name="img:latest", port=8000, env={}, expose_externally=False) + + +PROVIDERS = pytest.mark.parametrize("cls", [ModalVmSandboxProvider, ModalSandboxProvider], ids=["vm", "container"]) + + +@pytest.mark.parametrize("create", [(ModalVmSandboxProvider, created_vm), (ModalSandboxProvider, created_container)], + ids=["vm", "container"]) +@pytest.mark.asyncio +async def test_a_handle_this_process_created_terminates_with_no_tag_read(modal_api, create): + cls, make = create + modal_api.sb = modal_sb() + handle = await make(provider(cls)) + + await handle.terminate() + + modal_api.sb.terminate.aio.assert_awaited_once() + modal_api.sb.get_tags.aio.assert_not_called() + + +@PROVIDERS +@pytest.mark.asyncio +async def test_terminate_sandbox_reads_the_tags_of_a_sandbox_that_is_no_box_then_terminates_it(modal_api, cls): + modal_api.sb = modal_sb({PIPELINE_STEP_KEY: "t_s"}) + + await provider(cls).terminate_sandbox("sb-1") + + modal_api.sb.get_tags.aio.assert_awaited_once() + modal_api.sb.terminate.aio.assert_awaited_once() + + +@pytest.mark.parametrize("gone_at", ["from_id", "get_tags"]) +@PROVIDERS +@pytest.mark.asyncio +async def test_terminate_sandbox_counts_a_sandbox_modal_no_longer_knows_as_gone(modal_api, cls, gone_at): + modal_api.sb = modal_sb(tag_reads=[modal.exception.NotFoundError("Sandbox not found")]) + if gone_at == "from_id": + modal_api.from_id.side_effect = modal.exception.NotFoundError("Sandbox not found") + + await provider(cls).terminate_sandbox("sb-1") + + modal_api.sb.terminate.aio.assert_not_called() + + +@PROVIDERS +@pytest.mark.asyncio +async def test_a_tag_read_that_fails_then_succeeds_terminates(modal_api, cls): + modal_api.sb = modal_sb(tag_reads=[modal.exception.ConnectionError("reset"), {}]) + + await provider(cls).terminate_sandbox("sb-1") + + modal_api.sb.terminate.aio.assert_awaited_once() + + +@PROVIDERS +@pytest.mark.asyncio +async def test_a_tag_read_that_keeps_failing_raises_terminates_nothing_and_says_so(modal_api, cls, caplog): + modal_api.sb = modal_sb(tag_reads=modal.exception.ConnectionError("reset")) + + with caplog.at_level(logging.WARNING, logger="agent_env"), pytest.raises(modal.exception.ConnectionError): + await provider(cls).terminate_sandbox("sb-1") + + modal_api.sb.terminate.aio.assert_not_called() + [warning] = [r for r in caplog.records if getattr(r, "event", None) == SHARED_BOX_TAG_READ_FAILED_EVENT] + assert warning.modal_sandbox_id == "sb-1" + + +@pytest.mark.asyncio +async def test_a_created_shared_box_handle_refuses_to_terminate(modal_api): + modal_api.sb = modal_sb(BOX) + handle = await provider(ModalVmSandboxProvider).create_shared_box("box-1", setup_for_gateway=False) + + with pytest.raises(SharedBoxTerminateRefused) as refused: + await handle.terminate() + + assert (refused.value.sandbox_id, refused.value.box_id) == ("sb-1", "box-1") + modal_api.sb.terminate.aio.assert_not_called() + + +@PROVIDERS +@pytest.mark.asyncio +async def test_a_reattached_handle_to_a_shared_box_refuses_to_terminate(modal_api, cls): + modal_api.sb = modal_sb(BOX) + handle = await provider(cls).get_sandbox("sb-1") + + for _ in range(2): + with pytest.raises(SharedBoxTerminateRefused): + await handle.terminate() + + assert handle.shared_box_id == "box-1" + modal_api.sb.terminate.aio.assert_not_called() + + +@PROVIDERS +@pytest.mark.asyncio +async def test_terminate_sandbox_refuses_a_shared_box(modal_api, cls): + modal_api.sb = modal_sb(BOX) + + with pytest.raises(SharedBoxTerminateRefused): + await provider(cls).terminate_sandbox("sb-1") + + modal_api.sb.terminate.aio.assert_not_called() + + +@pytest.mark.asyncio +async def test_terminate_shared_box_ends_the_box_it_names(modal_api): + modal_api.sb = modal_sb(BOX) + + await provider(ModalVmSandboxProvider).terminate_shared_box("sb-1", "box-1") + + modal_api.sb.terminate.aio.assert_awaited_once() + + +@pytest.mark.parametrize("sb", [ + pytest.param(lambda: modal_sb({SHARED_BOX_TAG: "box-2"}), id="another box"), + pytest.param(lambda: modal_sb({PIPELINE_STEP_KEY: "t_s"}), id="no box"), +]) +@pytest.mark.asyncio +async def test_terminate_shared_box_refuses_a_sandbox_that_isnt_that_box(modal_api, sb): + modal_api.sb = sb() + + with pytest.raises(SharedBoxTerminateRefused): + await provider(ModalVmSandboxProvider).terminate_shared_box("sb-1", "box-1") + + modal_api.sb.terminate.aio.assert_not_called() + + +@pytest.mark.asyncio +async def test_terminate_shared_box_raises_when_the_tags_cant_be_read(modal_api): + modal_api.sb = modal_sb(tag_reads=modal.exception.ConnectionError("reset")) + + with pytest.raises(modal.exception.ConnectionError): + await provider(ModalVmSandboxProvider).terminate_shared_box("sb-1", "box-1") + + modal_api.sb.terminate.aio.assert_not_called() + + +@pytest.mark.asyncio +async def test_create_shared_box_tags_the_vm_with_its_box_beside_its_attribution(modal_api): + modal_api.sb = modal_sb() + + handle = await provider(ModalVmSandboxProvider).create_shared_box( + "box-1", setup_for_gateway=False, attribution={PIPELINE_STEP_KEY: "t_s"}) + + assert modal_api.create.call_args.kwargs["tags"] == {PIPELINE_STEP_KEY: "t_s", SHARED_BOX_TAG: "box-1"} + assert handle.shared_box_id == "box-1" + + +@pytest.mark.parametrize("box_id, attribution", [ + pytest.param("box-1", {SHARED_BOX_TAG: "forged"}, id="attribution names the box tag"), + pytest.param("", {}, id="empty id"), + pytest.param("box 1", {}, id="id outside a tag's characters"), + pytest.param("b" * 64, {}, id="id longer than a tag"), +]) +@pytest.mark.asyncio +async def test_create_shared_box_refuses_before_creating(modal_api, box_id, attribution): + with pytest.raises(ValueError): + await provider(ModalVmSandboxProvider).create_shared_box(box_id, attribution=attribution) + + modal_api.create.assert_not_called() + + +@pytest.mark.asyncio +async def test_an_ordinary_vm_cant_be_given_the_box_tag_through_its_attribution(modal_api): + with pytest.raises(ValueError): + await provider(ModalVmSandboxProvider).create_vm(attribution={SHARED_BOX_TAG: "forged"}) + + modal_api.create.assert_not_called() + + +@pytest.mark.asyncio +async def test_providers_other_than_modal_vm_make_no_shared_box(): + with pytest.raises(NotImplementedError): + await ModalSandboxProvider().create_shared_box("box-1") + + +_ALLOWED = {"_terminate", "_terminate_created"} +_CREATE_CLEANUPS = {"create_container", "_created"} + + +def test_every_modal_terminate_goes_through_the_check_point_but_a_failed_creates_cleanup(): + """``terminate.aio(`` is called only in ``_terminate``, or where a create that failed ends its sandbox: the cancelled + create's cleanup, or an ``except`` in a create.""" + stray = [] + sources = Path(modal_sandbox.__file__).parent.glob("modal_*.py") + for source in sources: + tree = ast.parse(source.read_text()) + for function in (n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))): + in_handler = {id(c) for h in ast.walk(function) if isinstance(h, ast.ExceptHandler) for c in ast.walk(h)} + for call in (n for n in ast.walk(function) if isinstance(n, ast.Call)): + func = call.func + if not (isinstance(func, ast.Attribute) and func.attr == "aio" + and isinstance(func.value, ast.Attribute) and func.value.attr == "terminate"): + continue + if function.name in _ALLOWED or (function.name in _CREATE_CLEANUPS and id(call) in in_handler): + continue + stray.append(f"{source.name}:{call.lineno} in {function.name}") + assert stray == [] diff --git a/tst/unit/providers/sandbox_providers/modal_vm_sandbox_test.py b/tst/unit/providers/sandbox_providers/modal_vm_sandbox_test.py index 036351aa3..dafd91115 100644 --- a/tst/unit/providers/sandbox_providers/modal_vm_sandbox_test.py +++ b/tst/unit/providers/sandbox_providers/modal_vm_sandbox_test.py @@ -404,6 +404,7 @@ async def test_terminate_sandbox_terminates_a_vm_by_id_and_counts_one_modal_no_l provider = ModalVmSandboxProvider() provider._get_client = AsyncMock(return_value=MagicMock()) # type: ignore[method-assign] sb = MagicMock() + sb.get_tags.aio = AsyncMock(return_value={}) sb.terminate.aio = AsyncMock() with patch("agent_env.providers.sandbox_providers.modal_sandbox.modal.Sandbox.from_id") as from_id: from_id.aio = (AsyncMock(return_value=sb) if found diff --git a/tst/unit/task/teardown_test.py b/tst/unit/task/teardown_test.py index 6cc97c1a9..76aba5b56 100644 --- a/tst/unit/task/teardown_test.py +++ b/tst/unit/task/teardown_test.py @@ -312,6 +312,7 @@ async def terminate_sandbox(self, sandbox_id): def test_a_modal_sandbox_that_already_finished_is_counted_down_not_reported_up(monkeypatch): sb = MagicMock() sb.tunnels.aio = AsyncMock(side_effect=modal.exception.ConflictError("Sandbox has already finished with status terminated")) + sb.get_tags.aio = AsyncMock(return_value={}) sb.terminate.aio = AsyncMock() monkeypatch.setattr(modal.Sandbox, "from_id", MagicMock(aio=AsyncMock(return_value=sb))) monkeypatch.setattr(ModalSandboxProvider, "_get_client", AsyncMock(return_value=MagicMock())) From 35fbb0ce5ad1678e566fc828fd8bd5dee3f7207b Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Thu, 19 Nov 2026 18:47:32 -0500 Subject: [PATCH 03/15] fix(sandbox-providers): never reboot a shared box, and check every Modal SDK module for stray terminates reset_vm refuses a handle known to be a shared box, whose reboot would end every slot on it. The source check now covers every agent_env module that uses the Modal SDK and fails on a direct SandboxTerminate RPC anywhere. Co-Authored-By: Claude Opus 5.5 --- .../sandbox_providers/modal_vm_sandbox.py | 6 ++++- .../modal_shared_box_test.py | 22 +++++++++++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py index ec6df5558..8c88f1948 100644 --- a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py +++ b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py @@ -38,6 +38,7 @@ SHARED_BOX_TAG, UNREAD, SharedBox, + SharedBoxTerminateRefused, _ModalProcessAdapter, _attribution_tags, _ended_output, @@ -433,7 +434,10 @@ async def terminate_shared_box(self, sandbox_id: str, box_id: str) -> None: await _terminate_by_id(await self._get_client(), sandbox_id, ending_box=box_id) async def reset_vm(self, sandbox: Sandbox, *, image: str, env: dict[str, str]) -> None: - """The launcher in the sandbox booting its disk afresh with ``env``, at the same URLs.""" + """The launcher in the sandbox booting its disk afresh with ``env``, at the same URLs. Refused for a shared box, + whose reboot would end every slot on it.""" + if isinstance(getattr(sandbox, "shared_box_id", None), str): + raise SharedBoxTerminateRefused(sandbox.sandbox_id, sandbox.shared_box_id) code, _, stderr = await sandbox._exec_with_stdin(shlex.join(RESET), _chunks(reset_input(env))) if code: raise RuntimeError(f"the launcher in Modal sandbox {sandbox.sandbox_id} didn't boot its disk afresh " diff --git a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py index 24e1f8654..86864590f 100644 --- a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py +++ b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py @@ -4,6 +4,7 @@ from __future__ import annotations import ast +import re import logging from pathlib import Path from unittest.mock import AsyncMock, MagicMock @@ -251,9 +252,14 @@ async def test_providers_other_than_modal_vm_make_no_shared_box(): def test_every_modal_terminate_goes_through_the_check_point_but_a_failed_creates_cleanup(): """``terminate.aio(`` is called only in ``_terminate``, or where a create that failed ends its sandbox: the cancelled - create's cleanup, or an ``except`` in a create.""" + create's cleanup, or an ``except`` in a create. Every module of agent_env that uses the Modal SDK is checked, and no + module calls Modal's terminate RPC directly.""" stray = [] - sources = Path(modal_sandbox.__file__).parent.glob("modal_*.py") + package = Path(modal_sandbox.__file__).parents[2] + sources = [p for p in package.rglob("*.py") if re.search(r"^\s*(import modal|from modal)", p.read_text(), re.M)] + assert Path(modal_sandbox.__file__) in sources + for source in package.rglob("*.py"): + assert "SandboxTerminate" not in source.read_text(), f"{source} calls Modal's terminate RPC directly" for source in sources: tree = ast.parse(source.read_text()) for function in (n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))): @@ -267,3 +273,15 @@ def test_every_modal_terminate_goes_through_the_check_point_but_a_failed_creates continue stray.append(f"{source.name}:{call.lineno} in {function.name}") assert stray == [] + + +@pytest.mark.asyncio +async def test_a_shared_box_is_never_rebooted_under_its_slots(modal_api): + modal_api.sb = modal_sb() + vm_provider = provider(ModalVmSandboxProvider) + box = await vm_provider.create_shared_box("box-1", setup_for_gateway=False) + box._exec_with_stdin = AsyncMock() + + with pytest.raises(SharedBoxTerminateRefused): + await vm_provider.reset_vm(box, image="disk", env={}) + box._exec_with_stdin.assert_not_called() From 1e5da7adae7ce6c090c0d320b19309c4c7fe1c2b Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Thu, 19 Nov 2026 19:37:59 -0500 Subject: [PATCH 04/15] feat(sandbox-providers): a shared box runs gVisor behind slot walls, and a walls tag only its self-test may write A shared box now runs its own image: the VM image plus gVisor's runsc from the pinned release 20261116.0, its tarball checked against a SHA-512 pinned in source, and a dockerd config that runs every container under runsc in a user namespace with no-new-privileges, the userland proxy off, and address pools outside both the slot range and 172.16/12, where Modal's resolver is. Ordinary VMs keep today's image. Set up for a gateway, a shared box gets one idempotent firewall for all 46 slots: forwarded slot traffic may reach its own /23, the box's resolvers on port 53 and the internet; slot to slot, slot to private ranges and slot to box are dropped. The rules only drop or return, so Docker's own rules still apply, and a guard keeps every slot walled off while the chains are refilled. walls_verified is true only on a shared box tagged agent_env_walls at the current WALLS_VERSION. get_shared_box reads that tag and the box tag in one read. Nothing writes the tag yet: _mark_walls_verified is the only writer, for the self-test to call, and a static test fails on any other write. Co-Authored-By: Claude Opus 5.5 --- .../providers/sandbox_providers/AGENTS.md | 2 +- .../sandbox_providers/modal_sandbox.py | 42 ++- .../sandbox_providers/modal_vm_sandbox.py | 91 +++++- .../providers/sandbox_providers/sandbox.py | 2 +- .../sandbox_providers/shared_box_walls.py | 93 ++++++ .../env_providers/stack_layout_test.py | 5 +- .../modal_shared_box_test.py | 220 ++++++++++++++- .../shared_box_walls_test.py | 267 ++++++++++++++++++ 8 files changed, 698 insertions(+), 24 deletions(-) create mode 100644 src/agent_env/providers/sandbox_providers/shared_box_walls.py create mode 100644 tst/unit/providers/sandbox_providers/shared_box_walls_test.py diff --git a/src/agent_env/providers/sandbox_providers/AGENTS.md b/src/agent_env/providers/sandbox_providers/AGENTS.md index dc9e92321..a6494bdc6 100644 --- a/src/agent_env/providers/sandbox_providers/AGENTS.md +++ b/src/agent_env/providers/sandbox_providers/AGENTS.md @@ -54,7 +54,7 @@ with `exposed_ports=[port]` and returns the VM, and the deploy then loads and st | `create_sandbox(*, image_name, port, env, cpu, memory, disk_size_gb, timeout, attribution, network_policy) -> Sandbox` | yes (a VM backend wraps `create_vm`) | an agent's sandbox (`provider.create_sandbox`); `create_container` of a container-only backend | | `get_sandbox(sandbox_id) -> Sandbox` | yes | every step after the one that created the sandbox, and teardown | | `terminate_sandbox(sandbox_id)` | no | teardown. The default calls `get_sandbox` then `terminate()`, and treats `SandboxNotFoundError` as done; override when you can terminate without a live handle | -| `create_shared_box(box_id, *, cpu, memory, timeout, exposed_ports, setup_for_gateway, attribution, network_policy) -> VmSandbox` | no | nothing yet: a VM for several tasks' slots. The default raises `NotImplementedError`; `modal_vm` tags the VM with `SHARED_BOX_TAG` at create, refuses to end it from its handle's `terminate()` or `terminate_sandbox`, raising `SharedBoxTerminateRefused`, and ends it only through `terminate_shared_box(sandbox_id, box_id)` | +| `create_shared_box(box_id, *, cpu, memory, timeout, exposed_ports, setup_for_gateway, attribution, network_policy) -> VmSandbox` | no | nothing yet: a VM for several tasks' slots. The default raises `NotImplementedError`; `modal_vm` tags the VM with `SHARED_BOX_TAG` at create, refuses to end it from its handle's `terminate()` or `terminate_sandbox`, raising `SharedBoxTerminateRefused`, and ends it only through `terminate_shared_box(sandbox_id, box_id)`. Its VM runs `_SHARED_BOX_IMAGE`, every container under gVisor in a user namespace, and set up for a gateway it gets the firewall in `shared_box_walls.py` that walls its slots apart. `get_shared_box(sandbox_id, box_id)` reattaches to one; its handle's `walls_verified` is true only when the box carries `WALLS_TAG` at the current `WALLS_VERSION`, which nothing writes yet | | `create_container(...)` | inherited | containers that run an env or agent image. Override only when the platform boots images natively. Its `shm_mb` is the MiB the container's `/dev/shm` holds (`--shm-size` on the default VM path), passed only where `SHARED_MEMORY` is on | | `reset_container(sandbox, *, image_name, port, env, shm_mb)` | inherited | a computer env's reset, which replaces the container `create_container` ran with a fresh one on the same sandbox and port, its `/dev/shm` as before. The default works on a VM backend; one whose sandbox is the container itself raises `NotImplementedError` | | `native_platforms()` | no | a computer env's deploy and gate 3, which boot a build only on a provider that runs its arch without emulation. The default is `linux/amd64`; local Docker returns this machine's | diff --git a/src/agent_env/providers/sandbox_providers/modal_sandbox.py b/src/agent_env/providers/sandbox_providers/modal_sandbox.py index 4438d2b13..7002d638c 100644 --- a/src/agent_env/providers/sandbox_providers/modal_sandbox.py +++ b/src/agent_env/providers/sandbox_providers/modal_sandbox.py @@ -100,6 +100,10 @@ def _tunnel_url(t) -> str: #: The Modal sandbox tag that marks a VM as a shared box, several tasks' slots on one VM; its value is the box's id. SHARED_BOX_TAG = "agent_env_shared_box" SHARED_BOX_TAG_READ_FAILED_EVENT = "agent_env.modal_shared_box_tag_read_failed" +#: The Modal sandbox tag that says a shared box's walls between its slots passed their self-test; its value is the +#: WALLS_VERSION they passed. Only ``modal_vm_sandbox._mark_walls_verified`` writes it. +WALLS_TAG = "agent_env_walls" +WALLS_VERSION = "walls-v1" _TAG_READ_ATTEMPTS, _TAG_READ_BACKOFF_SECONDS = 3, 1.0 @@ -125,25 +129,44 @@ def __init__(self, sandbox_id: str, box_id: Optional[str], ending_box: Optional[ super().__init__(f"Modal sandbox {sandbox_id} {why}; it was not terminated") -async def _read_shared_box(sb: modal.Sandbox) -> Optional[str]: - """The shared box ``sb`` is tagged as, if any. A read that keeps failing raises, so a terminate fails closed; - NotFoundError raises at once.""" +class SharedBoxMismatch(LookupError): + """A sandbox reached as shared box ``expected`` is tagged as another box, or as none.""" + + def __init__(self, sandbox_id: str, box_id: Optional[str], expected: str): + self.sandbox_id, self.box_id, self.expected = sandbox_id, box_id, expected + found = f"shared box {box_id!r}" if box_id else "no shared box" + super().__init__(f"Modal sandbox {sandbox_id} is {found}, not shared box {expected!r}") + + +async def _read_tags(sb: modal.Sandbox) -> dict[str, str]: + """``sb``'s tags, the read retried; one that keeps failing raises, and NotFoundError raises at once.""" attempt = 1 while True: try: - return (await sb.get_tags.aio()).get(SHARED_BOX_TAG) + return dict(await sb.get_tags.aio()) except modal.exception.NotFoundError: raise - except Exception as e: + except Exception: if attempt == _TAG_READ_ATTEMPTS: - logger.warning(f"Modal sandbox {sb.object_id} was not terminated: its tags, which say whether it's a " - f"shared box, couldn't be read: {fmt_exc(e)}", - extra={"event": SHARED_BOX_TAG_READ_FAILED_EVENT, "modal_sandbox_id": sb.object_id}) raise await asyncio.sleep(_TAG_READ_BACKOFF_SECONDS * 2 ** (attempt - 1)) attempt += 1 +async def _read_shared_box(sb: modal.Sandbox) -> Optional[str]: + """The shared box ``sb`` is tagged as, if any. A read that keeps failing raises, so a terminate fails closed; + NotFoundError raises at once.""" + try: + return (await _read_tags(sb)).get(SHARED_BOX_TAG) + except modal.exception.NotFoundError: + raise + except Exception as e: + logger.warning(f"Modal sandbox {sb.object_id} was not terminated: its tags, which say whether it's a " + f"shared box, couldn't be read: {fmt_exc(e)}", + extra={"event": SHARED_BOX_TAG_READ_FAILED_EVENT, "modal_sandbox_id": sb.object_id}) + raise + + async def _terminate(sb: modal.Sandbox, box: SharedBox, *, ending_box: Optional[str] = None) -> None: """Terminate ``sb`` when it is the shared box ``ending_box``, or, with none, when it is no shared box; else raise SharedBoxTerminateRefused. Every Modal terminate goes through here but the cleanup of a create that failed, whose @@ -667,6 +690,9 @@ def _attribution_tags(attribution: Attribution) -> dict[str, str]: raise ValueError(f"attribution key {key!r} can't be a Modal tag: use 1-63 of a-z A-Z 0-9 . _ -") if key == SHARED_BOX_TAG: raise ValueError(f"attribution key {key!r} is the tag that marks a shared box; only create_shared_box sets it") + if key == WALLS_TAG: + raise ValueError(f"attribution key {key!r} is the tag that says a shared box's walls passed their " + "self-test; only that self-test sets it") tags[key] = _modal_tag_value(value) return tags diff --git a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py index 8c88f1948..4b68b0324 100644 --- a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py +++ b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py @@ -24,6 +24,7 @@ from __future__ import annotations import asyncio +import json import logging import os import re @@ -37,13 +38,17 @@ _MODAL_TAG_KEY, SHARED_BOX_TAG, UNREAD, + WALLS_TAG, + WALLS_VERSION, SharedBox, + SharedBoxMismatch, SharedBoxTerminateRefused, _ModalProcessAdapter, _attribution_tags, _ended_output, _last_lines, _log_sandbox_started, + _read_tags, _resolve_app_base_name, _terminate_by_id, _terminate_handle, @@ -58,6 +63,7 @@ from agent_env.providers.sandbox_providers.local_docker.disk import exported_disk from agent_env.providers.sandbox_providers.sandbox import NetworkPolicy, Sandbox, VmSandbox, push_object_over_stdin from agent_env.providers.sandbox_providers.sandbox_provider import SANDBOX_MODE_VM, SandboxProvider +from agent_env.providers.sandbox_providers.shared_box_walls import apply_walls_firewall if TYPE_CHECKING: from agent_env.store.object_store import ObjectStore @@ -85,6 +91,33 @@ ) ) +# A shared box's image: the VM image, plus gVisor's runsc from a pinned release, its tarball checked against a SHA-512 +# pinned here, the one gVisor publishes beside it, and a dockerd config that runs every container under runsc, in a user namespace, +# with no-new-privileges. The userland proxy is off, so a published port is reached only by DNAT through FORWARD, where +# the walls see it. Docker's own address pools include 172.16/12, where Modal's VM resolver is, so its networks come +# from 10.251/16 instead, outside the slot range. +_GVISOR_RELEASE = "20261116.0" +_GVISOR_TARBALL_SHA512 = ("c87d792d5842efb70c38ee822124cfe0821a547715e7abcf3f2b14997cd02784" + "edaa0b91e238ec5c27a25a1b9e00bf98113398eb62a0778d8d20d4e222f8b0e0") +_SHARED_BOX_DOCKERD_CONFIG = { + "default-runtime": "runsc", + "runtimes": {"runsc": {"path": "/usr/local/bin/runsc"}}, + "userns-remap": "default", + "no-new-privileges": True, + "userland-proxy": False, + "default-address-pools": [{"base": "10.251.0.0/16", "size": 24}], +} +_SHARED_BOX_BUILD = ( + f"curl -fsSL https://storage.googleapis.com/gvisor/releases/release/{_GVISOR_RELEASE}/x86_64/gvisor.tar.bz2" + " -o /tmp/gvisor.tar.bz2" + f" && echo '{_GVISOR_TARBALL_SHA512} /tmp/gvisor.tar.bz2' | sha512sum -c -" + " && tar -xjf /tmp/gvisor.tar.bz2 -C /usr/local/bin && rm /tmp/gvisor.tar.bz2" + " && /usr/local/bin/runsc --version", + f"mkdir -p /etc/docker && printf '%s\\n' {shlex.quote(json.dumps(_SHARED_BOX_DOCKERD_CONFIG))}" + " > /etc/docker/daemon.json", +) +_SHARED_BOX_IMAGE = _VM_IMAGE.apt_install("bzip2").run_commands(*_SHARED_BOX_BUILD) + # The sandbox MAIN process. Two decoupled parts, both for robustness: # 1. A best-effort log forwarder run as a *child* of this process — NOT a separate `exec`. # Modal reaps an exec'd process tree when the exec call returns (that killed an earlier @@ -150,9 +183,11 @@ class ModalVmSandbox(VmSandbox): _WFT_CHUNK_BYTES = 32 * 1024 def __init__(self, sb: modal.Sandbox, tunnel_urls: dict[int, str], - network_policy: NetworkPolicy | None = None, shared_box_id: SharedBox = UNREAD): + network_policy: NetworkPolicy | None = None, shared_box_id: SharedBox = UNREAD, + walls: Optional[str] = None): self._sb = sb self.shared_box_id = shared_box_id + self._walls = walls self.sandbox_id = sb.object_id self.tunnel_urls = tunnel_urls self.vnc_url = None @@ -161,6 +196,12 @@ def __init__(self, sb: modal.Sandbox, tunnel_urls: dict[int, str], self._download_slots = asyncio.Semaphore(max(1, _dl_setting("PARALLEL_FILES", _DL_PARALLEL_FILES))) self._ended: Optional[tuple[list[str], list[str]]] = None + @property + def walls_verified(self) -> bool: + """Whether this is a shared box whose walls passed the self-test of the current WALLS_VERSION, as this handle + read it: a handle from ``get_sandbox`` never says so, only one from ``create_shared_box`` or ``get_shared_box``.""" + return isinstance(self.shared_box_id, str) and self._walls == WALLS_VERSION + async def terminate(self) -> None: await _terminate_handle(self) @@ -201,15 +242,18 @@ async def setup_vm_for_gateway(self, exposed_ports: Optional[list[int]] = None) """Make the VM ready for the gateway deploy. Unlike a containerdisk image that auto-starts dockerd via systemd, a Modal VM - sandbox does not start dockerd on its own, so we start it here. No iptables step: - ports are exposed via Modal `encrypted_ports` at create time, and Modal has no - host INPUT chain to open (contrast VmSandbox.setup_vm_for_gateway). + sandbox does not start dockerd on its own, so we start it here. No iptables step to open + ports: they are exposed via Modal `encrypted_ports` at create time, and Modal has no + host INPUT chain to open (contrast VmSandbox.setup_vm_for_gateway). A shared box then + gets the firewall that walls its slots apart, which needs dockerd's DOCKER-USER chain. The container-log forwarder is NOT started here — it runs as a child of the sandbox main process (see `_MAIN_SCRIPT`) so Modal can't reap it the way it reaps a transient `exec`'d process when the exec call returns. """ await self._ensure_dockerd_running() + if isinstance(self.shared_box_id, str): + await apply_walls_firewall(self) async def wait_for_vm(self) -> None: # For a Modal VM, "ready" means the Docker daemon is reachable. @@ -418,12 +462,13 @@ async def create_shared_box( attribution: Optional[Attribution] = None, network_policy: Optional[NetworkPolicy] = None, ) -> ModalVmSandbox: - """A VM running Docker, as ``create_vm`` makes, tagged as shared box ``box_id`` at create, since a later - ``set_tags`` would replace its attribution tags. Its handle's terminate, and ``terminate_sandbox``, refuse to end - it: only ``terminate_shared_box`` does.""" + """A VM running Docker with every container under gVisor, tagged as shared box ``box_id`` at create, since a + later ``set_tags`` would replace its attribution tags; set up for a gateway, it has the walls between its slots + too, though not yet verified. Its handle's terminate, and ``terminate_sandbox``, refuse to end it: only + ``terminate_shared_box`` does.""" if not _MODAL_TAG_KEY.fullmatch(box_id): raise ValueError(f"shared box id {box_id!r} can't be a Modal tag: use 1-63 of a-z A-Z 0-9 . _ -") - return await self._created(_KEEPALIVE_CMD, _VM_IMAGE, cpu=cpu, memory=memory, timeout=timeout, + return await self._created(_KEEPALIVE_CMD, _SHARED_BOX_IMAGE, cpu=cpu, memory=memory, timeout=timeout, ports=list(exposed_ports or []), attribution=attribution, network_policy=network_policy, setup_for_gateway=setup_for_gateway, idle_timeout=self._idle_timeout, runtime="vm", shared_box_id=box_id) @@ -531,15 +576,39 @@ async def create_sandbox( async def get_sandbox(self, sandbox_id: str) -> ModalVmSandbox: client = await self._get_client() sb = await modal.Sandbox.from_id.aio(sandbox_id, client=client) - tunnels = await sb.tunnels.aio() - tunnel_urls = {p: _tunnel_url(t) for p, t in tunnels.items()} # dockerd is already running on a live sandbox; do not re-run setup here. - return ModalVmSandbox(sb, tunnel_urls) + return ModalVmSandbox(sb, await _tunnel_urls(sb)) + + async def get_shared_box(self, sandbox_id: str, box_id: str) -> ModalVmSandbox: + """The handle of shared box ``box_id``, the sandbox ``sandbox_id``, which knows from one read of its tags that it + is that box and whether its walls are verified. One tagged as another box, or as none, raises SharedBoxMismatch; + tags that can't be read raise.""" + sb = await modal.Sandbox.from_id.aio(sandbox_id, client=await self._get_client()) + tags = await _read_tags(sb) + if tags.get(SHARED_BOX_TAG) != box_id: + raise SharedBoxMismatch(sandbox_id, tags.get(SHARED_BOX_TAG), box_id) + return ModalVmSandbox(sb, await _tunnel_urls(sb), shared_box_id=box_id, walls=tags.get(WALLS_TAG)) async def terminate_sandbox(self, sandbox_id: str) -> None: await _terminate_by_id(await self._get_client(), sandbox_id) +async def _tunnel_urls(sb: modal.Sandbox) -> dict[int, str]: + return {p: _tunnel_url(t) for p, t in (await sb.tunnels.aio()).items()} + + +async def _mark_walls_verified(box: ModalVmSandbox) -> None: + """Tag shared box ``box`` as having walls that passed the current WALLS_VERSION's self-test, keeping its other tags, + as ``set_tags`` replaces them all. The one writer of WALLS_TAG, for the self-test to call once its probes pass.""" + if not isinstance(box.shared_box_id, str): + raise ValueError(f"Modal sandbox {box.sandbox_id} is no shared box this handle knows of; its walls aren't marked") + tags = await _read_tags(box._sb) + if tags.get(SHARED_BOX_TAG) != box.shared_box_id: + raise SharedBoxMismatch(box.sandbox_id, tags.get(SHARED_BOX_TAG), box.shared_box_id) + await box._sb.set_tags.aio({**tags, WALLS_TAG: WALLS_VERSION}) + box._walls = WALLS_VERSION + + async def _launcher() -> modal.Image: """The QEMU launcher, its ENTRYPOINT cleared, as Modal runs an image's before the sandbox's command: the image published for the sources installed, else built by Modal from its folder.""" diff --git a/src/agent_env/providers/sandbox_providers/sandbox.py b/src/agent_env/providers/sandbox_providers/sandbox.py index b784d21d8..311b417e3 100644 --- a/src/agent_env/providers/sandbox_providers/sandbox.py +++ b/src/agent_env/providers/sandbox_providers/sandbox.py @@ -177,7 +177,7 @@ class Sandbox(ABC): @property def walls_verified(self) -> bool: """Whether the framework itself set up and tested the walls between slots on this sandbox, so stacks of - different runs may share it. False for every sandbox today: nothing sets up those walls yet.""" + different runs may share it. False here; only a Modal VM shared box whose walls passed their self-test says so.""" return False def url_from_sandbox(self, url: str) -> str: diff --git a/src/agent_env/providers/sandbox_providers/shared_box_walls.py b/src/agent_env/providers/sandbox_providers/shared_box_walls.py new file mode 100644 index 000000000..92e4e6fb0 --- /dev/null +++ b/src/agent_env/providers/sandbox_providers/shared_box_walls.py @@ -0,0 +1,93 @@ +"""The walls between the slots of a shared box, the networks each slot owns and the firewall that keeps them apart. + +Slot ``n`` of a box owns the /23 ``10.250.2n.0/23``: ``10.250.2n.0/24`` for its env's network and ``10.250.2n+1.0/24`` +for its website's. The firewall is one root shell script for the whole box, every slot at once, applied once dockerd is +up and its ``DOCKER-USER`` chain exists. It only drops: what it lets through still meets Docker's own rules, so it never +opens a path Docker would close. Forwarded traffic from a slot may reach its own /23, the box's upstream resolvers on +port 53, and anything outside the private ranges; traffic from a slot to the box itself is dropped. +""" + +from __future__ import annotations + +import ipaddress +from ipaddress import IPv4Address, IPv4Network +from typing import NamedTuple, Sequence + +from agent_env.providers.sandbox_providers.sandbox import Sandbox + +SLOT_COUNT = 46 +SLOT_RANGE = IPv4Network("10.250.0.0/16") +_PRIVATE_RANGES = tuple(IPv4Network(n) for n in + ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", "100.64.0.0/10")) +FORWARD_CHAIN, INPUT_CHAIN = "AGENTENV-WALLS-FWD", "AGENTENV-WALLS-IN" +_ESTABLISHED = "-m conntrack --ctstate ESTABLISHED,RELATED" + + +class SlotNetworks(NamedTuple): + slot: IPv4Network + env: IPv4Network + website: IPv4Network + + +def slot_networks(index: int) -> SlotNetworks: + """The /23 slot ``index`` owns, and its env's and website's /24 in it.""" + if isinstance(index, bool) or not isinstance(index, int) or not 0 <= index < SLOT_COUNT: + raise ValueError(f"slot index {index!r} is not an int from 0 to {SLOT_COUNT - 1}") + env = IPv4Network(f"10.250.{2 * index}.0/24") + website = IPv4Network(f"10.250.{2 * index + 1}.0/24") + return SlotNetworks(env.supernet(), env, website) + + +def upstream_resolvers(resolv_conf: str) -> tuple[IPv4Address, ...]: + """The IPv4 nameservers of a resolv.conf, in order. IPv6 ones are skipped, as slots have no IPv6; a resolver in + the slot range, or none at all, raises.""" + resolvers = [] + for line in resolv_conf.splitlines(): + fields = line.split() + if len(fields) < 2 or fields[0] != "nameserver": + continue + address = ipaddress.ip_address(fields[1].split("%")[0]) + if address.version != 4: + continue + if address in SLOT_RANGE: + raise ValueError(f"nameserver {address} is in the slot range {SLOT_RANGE}") + if address not in resolvers: + resolvers.append(address) + if not resolvers: + raise ValueError(f"no IPv4 nameserver in resolv.conf: {resolv_conf!r}") + return tuple(resolvers) + + +def walls_firewall_script(resolvers: Sequence[IPv4Address]) -> str: + """A root shell script that sets the box's firewall to the walls for every slot, the same rules however often it + runs. While it refills the chains, a guard at the top of ``DOCKER-USER`` and ``INPUT`` drops all slot traffic, so + a run that fails part way leaves the walls closed, not open.""" + if not resolvers: + raise ValueError("the walls need at least one upstream resolver") + slots = str(SLOT_RANGE) + forward = [f"{_ESTABLISHED} -j RETURN"] + forward += [f"-s {n.slot} -d {n.slot} -j RETURN" for n in map(slot_networks, range(SLOT_COUNT))] + forward.append(f"-s {slots} -d {slots} -j DROP") + forward += [f"-s {slots} -d {r}/32 -p {proto} --dport 53 -j RETURN" for r in resolvers for proto in ("udp", "tcp")] + forward += [f"-s {slots} -d {n} -j DROP" for n in _PRIVATE_RANGES] + incoming = [f"{_ESTABLISHED} -j RETURN", f"-s {slots} -j DROP"] + guard = f"-s {slots} -j DROP" + lines = ["set -eu"] + for parent in ("DOCKER-USER", "INPUT"): + lines.append(f"iptables -C {parent} {guard} 2>/dev/null || iptables -I {parent} 1 {guard}") + for chain, parent, rules in ((FORWARD_CHAIN, "DOCKER-USER", forward), (INPUT_CHAIN, "INPUT", incoming)): + lines.append(f"iptables -N {chain} 2>/dev/null || iptables -F {chain}") + lines += [f"iptables -A {chain} {rule}" for rule in rules] + lines.append(f"iptables -C {parent} -j {chain} 2>/dev/null || iptables -I {parent} 1 -j {chain}") + for parent in ("DOCKER-USER", "INPUT"): + lines.append(f"iptables -D {parent} {guard}") + return "\n".join(lines) + "\n" + + +async def apply_walls_firewall(sandbox: Sandbox) -> None: + """Set the walls on ``sandbox``, a shared box whose dockerd is up, against the resolvers its resolv.conf names.""" + code, resolv_conf, stderr = await sandbox.exec_with_output("cat", "/etc/resolv.conf") + if code: + raise RuntimeError(f"couldn't read /etc/resolv.conf on {sandbox.sandbox_id} (exit {code}): {stderr.strip()}") + script = walls_firewall_script(upstream_resolvers(resolv_conf)) + await sandbox.exec_script(script, max_retries=1) diff --git a/tst/unit/providers/env_providers/stack_layout_test.py b/tst/unit/providers/env_providers/stack_layout_test.py index 199c71de4..37122fc10 100644 --- a/tst/unit/providers/env_providers/stack_layout_test.py +++ b/tst/unit/providers/env_providers/stack_layout_test.py @@ -197,7 +197,7 @@ async def test_a_slot_is_never_deployed_on_a_vm_whose_walls_are_not_verified(): assert vm.calls == [] -def test_no_sandbox_has_verified_walls_today(): +def test_only_a_modal_vm_sandbox_can_have_verified_walls(): import importlib import pkgutil @@ -214,7 +214,8 @@ def test_no_sandbox_has_verified_walls_today(): subclasses += (children := pending.pop().__subclasses__()) pending += children assert subclasses - assert [c.__name__ for c in subclasses if c.walls_verified is not Sandbox.walls_verified] == [] + ours = [c for c in subclasses if c.__module__.startswith(package.__name__)] + assert [c.__name__ for c in ours if "walls_verified" in vars(c)] == ["ModalVmSandbox"] def test_a_provider_subclass_that_skips_init_keeps_the_default_layout(): diff --git a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py index 86864590f..2e67a700a 100644 --- a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py +++ b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py @@ -4,8 +4,10 @@ from __future__ import annotations import ast +import json import re import logging +import shlex from pathlib import Path from unittest.mock import AsyncMock, MagicMock @@ -15,13 +17,22 @@ from agent_env.attribution import PIPELINE_STEP_KEY from agent_env.config import get_config, reset_config from agent_env.providers.sandbox_providers import modal_sandbox +from agent_env.providers.sandbox_providers import modal_vm_sandbox from agent_env.providers.sandbox_providers.modal_sandbox import ( SHARED_BOX_TAG, SHARED_BOX_TAG_READ_FAILED_EVENT, + UNREAD, + WALLS_TAG, + WALLS_VERSION, ModalSandboxProvider, + SharedBoxMismatch, SharedBoxTerminateRefused, ) -from agent_env.providers.sandbox_providers.modal_vm_sandbox import ModalVmSandboxProvider +from agent_env.providers.sandbox_providers.modal_vm_sandbox import ( + ModalVmSandbox, + ModalVmSandboxProvider, + _mark_walls_verified, +) from tst.unit.store.fakes import FakeImageStore BOX = {SHARED_BOX_TAG: "box-1"} @@ -40,6 +51,7 @@ def modal_sb(tags=None, *, tag_reads=None, sandbox_id="sb-1") -> MagicMock: sb = MagicMock(object_id=sandbox_id) sb.get_tags.aio = AsyncMock(side_effect=tag_reads) if tag_reads else AsyncMock(return_value=dict(tags or {})) sb.terminate.aio = AsyncMock() + sb.set_tags.aio = AsyncMock() sb.tunnels.aio = AsyncMock(return_value={}) sb.wait_until_ready.aio = AsyncMock() sb._get_task_id.aio = AsyncMock(return_value="ta-1") @@ -285,3 +297,209 @@ async def test_a_shared_box_is_never_rebooted_under_its_slots(modal_api): with pytest.raises(SharedBoxTerminateRefused): await vm_provider.reset_vm(box, image="disk", env={}) box._exec_with_stdin.assert_not_called() + + +WALLED = {**BOX, WALLS_TAG: WALLS_VERSION} + + +def test_a_shared_box_runs_from_the_vm_image_plus_a_pinned_checksummed_runsc_and_its_dockerd_config(): + [install, configure] = modal_vm_sandbox._SHARED_BOX_BUILD + tarball = (f"https://storage.googleapis.com/gvisor/releases/release/{modal_vm_sandbox._GVISOR_RELEASE}" + "/x86_64/gvisor.tar.bz2") + + assert re.fullmatch(r"\d{8}\.\d+", modal_vm_sandbox._GVISOR_RELEASE) + assert re.fullmatch(r"[0-9a-f]{128}", modal_vm_sandbox._GVISOR_TARBALL_SHA512) + assert install.index(tarball) < install.index(f"{modal_vm_sandbox._GVISOR_TARBALL_SHA512} /tmp/gvisor.tar.bz2' " + "| sha512sum -c -") < install.index("tar -xjf") + written = shlex.split(configure.split("printf '%s\\n' ", 1)[1].split(" > ")[0])[0] + assert configure.endswith("> /etc/docker/daemon.json") + assert json.loads(written) == { + "default-runtime": "runsc", + "runtimes": {"runsc": {"path": "/usr/local/bin/runsc"}}, + "userns-remap": "default", + "no-new-privileges": True, + "userland-proxy": False, + "default-address-pools": [{"base": "10.251.0.0/16", "size": 24}], + } + assert modal_vm_sandbox._SHARED_BOX_IMAGE is not modal_vm_sandbox._VM_IMAGE + + +@pytest.mark.asyncio +async def test_only_a_shared_box_gets_the_box_image(modal_api): + modal_api.sb = modal_sb() + p = provider(ModalVmSandboxProvider) + + await p.create_shared_box("box-1", setup_for_gateway=False) + await p.create_vm(setup_for_gateway=False) + + box, vm = (c.kwargs["image"] for c in modal_api.create.call_args_list) + assert (box, vm) == (modal_vm_sandbox._SHARED_BOX_IMAGE, modal_vm_sandbox._VM_IMAGE) + + +@pytest.mark.parametrize("shared_box_id, walled", [("box-1", True), (None, False), (UNREAD, False)]) +@pytest.mark.asyncio +async def test_setting_up_a_shared_box_walls_its_slots_once_dockerd_is_up(monkeypatch, shared_box_id, walled): + calls = [] + monkeypatch.setattr(modal_vm_sandbox, "apply_walls_firewall", AsyncMock(side_effect=lambda s: calls.append("walls"))) + handle = ModalVmSandbox(modal_sb(), {}, shared_box_id=shared_box_id) + handle._ensure_dockerd_running = AsyncMock(side_effect=lambda: calls.append("dockerd")) + + await handle.setup_vm_for_gateway([]) + + assert calls == (["dockerd", "walls"] if walled else ["dockerd"]) + + +@pytest.mark.parametrize("shared_box_id, walls, verified", [ + pytest.param("box-1", WALLS_VERSION, True, id="box with current walls"), + pytest.param("box-1", None, False, id="box, walls unread or untagged"), + pytest.param("box-1", "walls-v0", False, id="box with an older walls version"), + pytest.param(None, WALLS_VERSION, False, id="no box"), + pytest.param(UNREAD, WALLS_VERSION, False, id="box unread"), +]) +def test_walls_are_verified_only_on_a_shared_box_tagged_with_the_current_version(shared_box_id, walls, verified): + assert ModalVmSandbox(modal_sb(), {}, shared_box_id=shared_box_id, walls=walls).walls_verified is verified + + +@pytest.mark.asyncio +async def test_a_created_shared_box_has_walls_not_yet_verified(modal_api): + modal_api.sb = modal_sb(WALLED) + + handle = await provider(ModalVmSandboxProvider).create_shared_box("box-1", setup_for_gateway=False) + + assert handle.walls_verified is False + + +@pytest.mark.asyncio +async def test_get_shared_box_reads_the_tags_once_for_both_the_box_and_its_walls(modal_api): + modal_api.sb = modal_sb(WALLED) + + handle = await provider(ModalVmSandboxProvider).get_shared_box("sb-1", "box-1") + + assert (handle.shared_box_id, handle.walls_verified) == ("box-1", True) + modal_api.sb.get_tags.aio.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_get_shared_box_of_a_box_with_older_walls_is_unverified(modal_api): + modal_api.sb = modal_sb({**BOX, WALLS_TAG: "walls-v0"}) + + handle = await provider(ModalVmSandboxProvider).get_shared_box("sb-1", "box-1") + + assert (handle.shared_box_id, handle.walls_verified) == ("box-1", False) + + +@pytest.mark.parametrize("tags, found", [ + pytest.param({SHARED_BOX_TAG: "box-2", WALLS_TAG: WALLS_VERSION}, "box-2", id="another box"), + pytest.param({WALLS_TAG: WALLS_VERSION}, None, id="no box"), +]) +@pytest.mark.asyncio +async def test_get_shared_box_refuses_a_sandbox_that_isnt_that_box(modal_api, tags, found): + modal_api.sb = modal_sb(tags) + + with pytest.raises(SharedBoxMismatch) as mismatch: + await provider(ModalVmSandboxProvider).get_shared_box("sb-1", "box-1") + + assert (mismatch.value.box_id, mismatch.value.expected) == (found, "box-1") + + +@pytest.mark.asyncio +async def test_get_shared_box_raises_when_the_tags_cant_be_read(modal_api): + modal_api.sb = modal_sb(tag_reads=modal.exception.ConnectionError("reset")) + + with pytest.raises(modal.exception.ConnectionError): + await provider(ModalVmSandboxProvider).get_shared_box("sb-1", "box-1") + + +@pytest.mark.asyncio +async def test_a_box_reached_through_get_sandbox_never_claims_verified_walls(modal_api): + modal_api.sb = modal_sb(WALLED) + + handle = await provider(ModalVmSandboxProvider).get_sandbox("sb-1") + + assert handle.walls_verified is False + modal_api.sb.get_tags.aio.assert_not_called() + + +@pytest.mark.parametrize("create", [ + pytest.param(lambda p: p.create_vm(attribution={WALLS_TAG: WALLS_VERSION}), id="vm"), + pytest.param(lambda p: p.create_shared_box("box-1", attribution={WALLS_TAG: WALLS_VERSION}), id="shared box"), +]) +@pytest.mark.asyncio +async def test_no_sandbox_can_be_given_the_walls_tag_through_its_attribution(modal_api, create): + with pytest.raises(ValueError, match="walls"): + await create(provider(ModalVmSandboxProvider)) + + modal_api.create.assert_not_called() + + +@pytest.mark.asyncio +async def test_marking_the_walls_verified_keeps_every_other_tag(modal_api): + modal_api.sb = modal_sb({**BOX, PIPELINE_STEP_KEY: "t_s", WALLS_TAG: "walls-v0"}) + box = ModalVmSandbox(modal_api.sb, {}, shared_box_id="box-1") + + await _mark_walls_verified(box) + + modal_api.sb.set_tags.aio.assert_awaited_once_with({**BOX, PIPELINE_STEP_KEY: "t_s", WALLS_TAG: WALLS_VERSION}) + assert box.walls_verified is True + + +@pytest.mark.parametrize("shared_box_id, tags, error", [ + pytest.param(None, {}, ValueError, id="handle is no box"), + pytest.param(UNREAD, BOX, ValueError, id="handle's box unread"), + pytest.param("box-1", {SHARED_BOX_TAG: "box-2"}, SharedBoxMismatch, id="sandbox is another box"), + pytest.param("box-1", None, modal.exception.ConnectionError, id="tags can't be read"), +]) +@pytest.mark.asyncio +async def test_marking_the_walls_verified_writes_nothing_unless_the_sandbox_is_that_box(shared_box_id, tags, error): + sb = modal_sb(tags) if tags is not None else modal_sb(tag_reads=modal.exception.ConnectionError("reset")) + box = ModalVmSandbox(sb, {}, shared_box_id=shared_box_id) + + with pytest.raises(error): + await _mark_walls_verified(box) + + sb.set_tags.aio.assert_not_called() + assert box.walls_verified is False + + +_WALLS_WRITER = "_mark_walls_verified" +#: Functions that may name WALLS_TAG without writing it: its refusal in attribution and the reattach that reads it. +_WALLS_READERS = {"_attribution_tags", "get_shared_box"} + + +def test_only_the_walls_writer_writes_the_walls_tag_or_sets_a_sandboxs_tags(): + """WALLS_TAG is named only in its definition, in imports, by the functions that read or refuse it, and by its one + writer, the only one to put it in a dict or assign it. Its value is spelled nowhere else. ``set_tags`` is called + only on a Modal App, named ``app``, or by the writer.""" + package = Path(modal_sandbox.__file__).parents[2] + stray = [] + for source in package.rglob("*.py"): + text = source.read_text() + if f'"{WALLS_TAG}"' in text and source != Path(modal_sandbox.__file__): + stray.append(f"{source.name} spells the walls tag's value") + tree = ast.parse(text) + owner = {} + for function in (n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))): + for node in ast.walk(function): + owner.setdefault(id(node), function.name) + writes = set() + for node in ast.walk(tree): + if isinstance(node, ast.Dict): + writes |= {id(k) for k in node.keys if k is not None} + if isinstance(node, ast.Subscript) and isinstance(node.ctx, ast.Store): + writes.add(id(node.slice)) + for node in ast.walk(tree): + where = f"{source.name}:{getattr(node, 'lineno', '?')} in {owner.get(id(node), 'module scope')}" + if isinstance(node, ast.Name) and node.id == "WALLS_TAG": + function = owner.get(id(node)) + if function is None and isinstance(node.ctx, ast.Store): + continue + if function == _WALLS_WRITER or (function in _WALLS_READERS and id(node) not in writes): + continue + stray.append(f"{where} names WALLS_TAG") + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "aio" \ + and isinstance(node.func.value, ast.Attribute) and node.func.value.attr == "set_tags": + receiver = node.func.value.value + if owner.get(id(node)) == _WALLS_WRITER or (isinstance(receiver, ast.Name) and receiver.id == "app"): + continue + stray.append(f"{where} sets tags") + assert stray == [] diff --git a/tst/unit/providers/sandbox_providers/shared_box_walls_test.py b/tst/unit/providers/sandbox_providers/shared_box_walls_test.py new file mode 100644 index 000000000..4a6013ac2 --- /dev/null +++ b/tst/unit/providers/sandbox_providers/shared_box_walls_test.py @@ -0,0 +1,267 @@ +"""The walls between a shared box's slots: the networks each slot owns, the resolvers read from the box, and the +firewall script, run here against a small model of iptables that decides which packets the walls let through.""" + +from __future__ import annotations + +import itertools +import shlex +from dataclasses import dataclass +from ipaddress import IPv4Address, IPv4Network, ip_address, ip_network +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from agent_env.providers.sandbox_providers.shared_box_walls import ( + SLOT_COUNT, + SLOT_RANGE, + apply_walls_firewall, + slot_networks, + upstream_resolvers, + walls_firewall_script, +) + +MODAL_RESOLV_CONF = "nameserver 172.21.0.1\nnameserver 1.1.1.1\nnameserver 8.8.8.8\n" +RESOLVERS = upstream_resolvers(MODAL_RESOLV_CONF) + + +class IptablesFailed(Exception): + pass + + +class FakeIptables: + """The filter table as the script leaves it: chains of rules, run line by line as ``bash -e`` would. ``fail_on`` + makes the one command holding that text fail, as a broken iptables would.""" + + def __init__(self, *, docker_user: bool = True, fail_on: str | None = None): + self.chains: dict[str, list[tuple[str, ...]]] = {"INPUT": [], "FORWARD": []} + if docker_user: + self.chains["DOCKER-USER"] = [("-j", "RETURN")] + self.chains["FORWARD"].append(("-j", "DOCKER-USER")) + self.fail_on = fail_on + + def run(self, script: str) -> None: + for line in script.splitlines(): + if line == "set -eu": + continue + if not any(self._command(part.replace("2>/dev/null", "")) for part in line.split(" || ")): + raise IptablesFailed(line) + + def _command(self, command: str) -> bool: + argv = shlex.split(command) + assert argv[0] == "iptables" + if self.fail_on and self.fail_on in command: + return False + op, chain, rest = argv[1], argv[2], tuple(argv[3:]) + if op == "-N": + if chain in self.chains: + return False + self.chains[chain] = [] + return True + if chain not in self.chains: + return False + rules = self.chains[chain] + if op == "-F": + rules.clear() + elif op == "-A": + rules.append(rest) + elif op == "-I": + rules.insert(int(rest[0]) - 1, rest[1:]) + elif op == "-C": + return rest in rules + elif op == "-D": + if rest not in rules: + return False + rules.remove(rest) + else: + raise AssertionError(f"unexpected iptables {op}") + return True + + def verdict(self, packet: Packet, chain: str) -> str: + """``ACCEPT`` or ``DROP`` for ``packet`` entering ``chain``, whose policy, like every built-in chain's on the + box, accepts.""" + return "DROP" if self._walk(packet, chain) == "DROP" else "ACCEPT" + + def _walk(self, packet: Packet, chain: str) -> str: + for rule in self.chains[chain]: + options = dict(zip(rule[::2], rule[1::2])) + if not _matches(packet, rule, options): + continue + target = options["-j"] + if target in ("DROP", "RETURN"): + return target + if self._walk(packet, target) == "DROP": + return "DROP" + return "RETURN" + + +def _matches(packet: Packet, rule: tuple[str, ...], options: dict[str, str]) -> bool: + if "--ctstate" in rule and not packet.established: + return False + if "-s" in options and packet.src not in ip_network(options["-s"]): + return False + if "-d" in options and packet.dst not in ip_network(options["-d"]): + return False + if "-p" in options and packet.proto != options["-p"]: + return False + return "--dport" not in options or packet.dport == int(options["--dport"]) + + +@dataclass(frozen=True) +class Packet: + src: IPv4Address + dst: IPv4Address + proto: str = "tcp" + dport: int = 443 + established: bool = False + + +def packet(src: str, dst: str, **kw) -> Packet: + return Packet(ip_address(src), ip_address(dst), **kw) + + +@pytest.fixture +def walled() -> FakeIptables: + table = FakeIptables() + table.run(walls_firewall_script(RESOLVERS)) + return table + + +def host(network: IPv4Network, n: int = 2) -> str: + return str(network[n]) + + +def test_every_slot_owns_one_23_in_the_slot_range_split_into_its_env_and_website_24s_and_no_two_overlap(): + slots = [slot_networks(i) for i in range(SLOT_COUNT)] + + for i, s in enumerate(slots): + assert s.slot.prefixlen == 23 and s.slot.subnet_of(SLOT_RANGE) + assert list(s.slot.subnets(new_prefix=24)) == [s.env, s.website] + assert s.env == IPv4Network(f"10.250.{2 * i}.0/24") + assert not any(a.slot.overlaps(b.slot) for a, b in itertools.combinations(slots, 2)) + + +@pytest.mark.parametrize("index", [-1, SLOT_COUNT, True, "1", 1.0]) +def test_a_slot_index_outside_the_slots_or_not_an_int_is_refused(index): + with pytest.raises(ValueError): + slot_networks(index) + + +def test_the_resolvers_are_the_ipv4_nameservers_of_resolv_conf_in_order(): + conf = "# by Modal\nsearch modal.internal\nnameserver 172.21.0.1\noptions ndots:1\nnameserver fe80::1%eth0\n" \ + "nameserver 1.1.1.1\nnameserver 172.21.0.1\n" + + assert upstream_resolvers(conf) == (IPv4Address("172.21.0.1"), IPv4Address("1.1.1.1")) + assert RESOLVERS == tuple(map(IPv4Address, ("172.21.0.1", "1.1.1.1", "8.8.8.8"))) + + +@pytest.mark.parametrize("conf", ["", "search x\n", "nameserver ::1\n", "nameserver 10.250.3.1\n", "nameserver x\n"], + ids=["empty", "no nameserver", "only ipv6", "in the slot range", "not an address"]) +def test_a_resolv_conf_with_no_usable_resolver_is_refused(conf): + with pytest.raises(ValueError): + upstream_resolvers(conf) + + +def test_a_slot_reaches_both_halves_of_its_own_23_and_no_other_slot(walled): + for i in range(SLOT_COUNT): + own = slot_networks(i) + assert walled.verdict(packet(host(own.env), host(own.website)), "FORWARD") == "ACCEPT" + assert walled.verdict(packet(host(own.website), host(own.env, 3)), "FORWARD") == "ACCEPT" + for j in (j for j in range(SLOT_COUNT) if j != i): + other = slot_networks(j) + assert walled.verdict(packet(host(own.env), host(other.env)), "FORWARD") == "DROP" + assert walled.verdict(packet(host(own.website), host(other.website)), "FORWARD") == "DROP" + + +@pytest.mark.parametrize("resolver", [str(r) for r in RESOLVERS]) +def test_a_slot_reaches_each_resolver_on_port_53_only(walled, resolver): + slot = host(slot_networks(7).env) + + for proto in ("udp", "tcp"): + assert walled.verdict(packet(slot, resolver, proto=proto, dport=53), "FORWARD") == "ACCEPT" + if ip_address(resolver).is_private: + assert walled.verdict(packet(slot, resolver, dport=80), "FORWARD") == "DROP" + + +@pytest.mark.parametrize("dst", ["10.0.0.5", "10.251.0.2", "172.16.4.4", "172.21.0.2", "192.168.1.1", + "169.254.169.254", "100.64.0.1", "100.127.255.254"]) +def test_a_slot_reaches_no_private_link_local_or_carrier_address(walled, dst): + assert walled.verdict(packet(host(slot_networks(0).env), dst, proto="udp", dport=53), "FORWARD") == "DROP" + + +def test_a_slot_reaches_the_internet_and_replies_to_what_reached_it(walled): + slot = host(slot_networks(45).website) + + assert walled.verdict(packet(slot, "8.8.4.4"), "FORWARD") == "ACCEPT" + assert walled.verdict(packet(slot, "172.20.0.9", established=True), "FORWARD") == "ACCEPT" + + +def test_a_slot_reaches_nothing_on_the_box_but_replies_to_the_box(walled): + slot = host(slot_networks(3).env) + + assert walled.verdict(packet(slot, "10.250.6.1"), "INPUT") == "DROP" + assert walled.verdict(packet(slot, "172.21.0.9", dport=22), "INPUT") == "DROP" + assert walled.verdict(packet(slot, "10.250.6.1", established=True), "INPUT") == "ACCEPT" + + +def test_traffic_not_from_a_slot_is_left_to_docker(walled): + assert walled.verdict(packet("10.251.0.2", "172.21.0.9", dport=80), "FORWARD") == "ACCEPT" + assert walled.verdict(packet("172.21.0.9", host(slot_networks(0).env)), "FORWARD") == "ACCEPT" + assert walled.verdict(packet("10.251.0.2", "10.251.0.1"), "INPUT") == "ACCEPT" + + +def test_running_the_script_again_leaves_the_same_rules_and_no_guard(walled): + before = {chain: list(rules) for chain, rules in walled.chains.items()} + + walled.run(walls_firewall_script(RESOLVERS)) + + assert walled.chains == before + assert walled.chains["DOCKER-USER"][0] == ("-j", "AGENTENV-WALLS-FWD") + assert walled.chains["INPUT"] == [("-j", "AGENTENV-WALLS-IN")] + + +def test_a_run_that_fails_part_way_leaves_every_slot_walled_off(): + table = FakeIptables() + table.run(walls_firewall_script(RESOLVERS)) + table.fail_on = "-A AGENTENV-WALLS-FWD -s 10.250.0.0/16 -d 10.0.0.0/8" + + with pytest.raises(IptablesFailed): + table.run(walls_firewall_script(RESOLVERS)) + + slot = host(slot_networks(0).env) + assert table.verdict(packet(slot, host(slot_networks(0).website)), "FORWARD") == "DROP" + assert table.verdict(packet(slot, "8.8.4.4"), "FORWARD") == "DROP" + assert table.verdict(packet(slot, "10.250.0.1"), "INPUT") == "DROP" + + +def test_the_script_fails_before_dockerd_has_made_its_docker_user_chain(): + with pytest.raises(IptablesFailed): + FakeIptables(docker_user=False).run(walls_firewall_script(RESOLVERS)) + + +def test_the_script_needs_a_resolver(): + with pytest.raises(ValueError): + walls_firewall_script(()) + + +@pytest.mark.asyncio +async def test_applying_the_walls_reads_the_boxs_resolvers_and_runs_the_script_for_them(): + box = MagicMock(sandbox_id="sb-1") + box.exec_with_output = AsyncMock(return_value=(0, MODAL_RESOLV_CONF, "")) + box.exec_script = AsyncMock(return_value="") + + await apply_walls_firewall(box) + + box.exec_with_output.assert_awaited_once_with("cat", "/etc/resolv.conf") + assert box.exec_script.await_args.args == (walls_firewall_script(RESOLVERS),) + + +@pytest.mark.asyncio +async def test_applying_the_walls_raises_and_runs_nothing_when_resolv_conf_cant_be_read(): + box = MagicMock(sandbox_id="sb-1") + box.exec_with_output = AsyncMock(return_value=(1, "", "No such file")) + box.exec_script = AsyncMock() + + with pytest.raises(RuntimeError, match="resolv.conf"): + await apply_walls_firewall(box) + + box.exec_script.assert_not_called() From d8821a17e08c41818a0fa27fe16a6d4de09ca437 Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Sat, 21 Nov 2026 00:14:59 -0500 Subject: [PATCH 05/15] feat(env-providers): a slot's compose fits its walls, and every door into a slot takes a per-deploy token A slot's compose is the default stack's, refitted: every service under runsc at a fixed address on the slot's subnets, with fixed bridge names (aesenv, aesweb), peers named in extra_hosts on the networks they share, the box's resolvers in a read-only resolv.conf, and no published port but the door's. A validator refuses anything that reaches past the walls. The default stack's compose is unchanged, pinned by a golden file rendered from the previous commit. The door (python -m gateway.door, from the gateway image) forwards each of the slot's ports to its service, HTTP streamed both ways and WebSockets relayed, and lets a request in only with X-Agentenv-Slot-Token, which it strips. Each slot deploy draws a new token. The env's grant carries the header to the slot's own addresses, and the callers that sent no credential to them now send it; the default stack sends nothing new. Co-Authored-By: Claude Opus 5.5 --- .../src/agentenv_protocol/client.py | 10 +- src/agent_env/a2a_agent/a2a_agent.py | 12 +- src/agent_env/artifact/artifacts/cli.py | 3 + src/agent_env/env/door_headers.py | 28 ++ src/agent_env/env/env.py | 54 +++- src/agent_env/env/envs/multi_env.py | 3 +- src/agent_env/env/gateway/constants.py | 7 + src/agent_env/env/gateway/door.py | 190 ++++++++++++++ src/agent_env/env/legacy_protocol.py | 16 +- src/agent_env/explorer/routers/triggers.py | 27 +- .../providers/env_providers/constants.py | 4 + .../env_providers/env_gateway_provider.py | 74 ++++-- .../providers/env_providers/env_provider.py | 22 +- .../providers/env_providers/slot_compose.py | 163 ++++++++++++ .../providers/env_providers/stack_layout.py | 12 +- .../sandbox_providers/shared_box_walls.py | 14 + src/agent_env/task/task.py | 2 +- .../task_step/task_steps/deploy_agent.py | 3 +- .../env_card_validator/verify_env_card.py | 3 +- .../verify_env_core_protocol.py | 3 +- .../task_step/task_steps/load_artifact.py | 3 +- .../mcp_cli_builder/build_mcp_cli.py | 3 +- .../task_steps/mcp_cli_builder/codegen.py | 15 +- .../verify_mcp_tool_schema.py | 2 +- .../verify_spec_conformance.py | 2 +- .../task_step/task_steps/snapshot_env.py | 3 +- tst/unit/env/door_grant_test.py | 120 +++++++++ tst/unit/env/envs/test_multi_env_name.py | 2 +- tst/unit/env/gateway/door_test.py | 179 +++++++++++++ .../env/task_step/verify_env_card_test.py | 4 +- .../env_providers/compose_fixture.py | 60 +++++ .../env_gateway_provider_test.py | 48 +++- .../golden/default_stack_compose.yml | 240 ++++++++++++++++++ .../env_providers/slot_compose_test.py | 164 ++++++++++++ .../env_providers/stack_layout_test.py | 37 ++- .../shared_box_walls_test.py | 11 + .../task_step/local_container_urls_test.py | 2 +- .../task_step/test_apply_server_config.py | 2 +- .../task_step/test_deploy_agent_mcp_alias.py | 10 + .../task_step/test_snapshot_agent_state.py | 6 +- tst/unit/task_step/test_snapshot_env.py | 16 +- .../task_step/test_verify_spec_conformance.py | 16 +- 42 files changed, 1488 insertions(+), 107 deletions(-) create mode 100644 src/agent_env/env/door_headers.py create mode 100644 src/agent_env/env/gateway/door.py create mode 100644 src/agent_env/providers/env_providers/slot_compose.py create mode 100644 tst/unit/env/door_grant_test.py create mode 100644 tst/unit/env/gateway/door_test.py create mode 100644 tst/unit/providers/env_providers/compose_fixture.py create mode 100644 tst/unit/providers/env_providers/golden/default_stack_compose.yml create mode 100644 tst/unit/providers/env_providers/slot_compose_test.py diff --git a/packages/agentenv-protocol/src/agentenv_protocol/client.py b/packages/agentenv-protocol/src/agentenv_protocol/client.py index 0d76ad4aa..07e18f1c7 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/client.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/client.py @@ -120,16 +120,18 @@ async def get_data( return GetDataResponse.model_validate(await _rpc(base_url, METHOD_GET, params, timeout, verify, headers)) -async def get_card(base_url: str, timeout: int = 10, verify: bool = True) -> dict: +async def get_card(base_url: str, timeout: int = 10, verify: bool = True, *, + headers: dict[str, str] | None = None) -> dict: + """The env card at ``base_url``, read with ``headers`` alone: unlike an RPC, a card read takes nothing from a grant.""" async with httpx.AsyncClient(verify=verify) as client: - response = await client.get(f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=timeout) + response = await client.get(f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=timeout, headers=headers) response.raise_for_status() return response.json() -async def supports_v1(base_url: str, verify: bool = True) -> bool: +async def supports_v1(base_url: str, verify: bool = True, *, headers: dict[str, str] | None = None) -> bool: try: - await get_card(base_url, verify=verify) + await get_card(base_url, verify=verify, headers=headers) return True except httpx.HTTPStatusError as e: if e.response.status_code != 404: diff --git a/src/agent_env/a2a_agent/a2a_agent.py b/src/agent_env/a2a_agent/a2a_agent.py index 915375304..6a1011eb5 100644 --- a/src/agent_env/a2a_agent/a2a_agent.py +++ b/src/agent_env/a2a_agent/a2a_agent.py @@ -26,7 +26,7 @@ NetworkPolicyUnsupportedError, port_bindings, ) -from agent_env.artifact.artifacts.cli import GATEWAY_ENV_FILE +from agent_env.artifact.artifacts.cli import GATEWAY_ENV_FILE, SLOT_TOKEN_ENV_VAR from agent_env.artifact.artifacts.docker_image import DockerImageArtifact from agent_env.a2a_agent.object_transfer import ( TRANSFER_TIMEOUT_SECONDS, @@ -297,11 +297,12 @@ def _skill_extension(deployed: "DeployedA2AAgent") -> dict: @staticmethod async def install_cli( deployed: "DeployedA2AAgent", cli_artifact: "CliArtifact", gateway_url: str, container: str | None = None, - on_host: bool = False, + on_host: bool = False, slot_token: str | None = None, ) -> str: """Install a CliArtifact bundle into the agent's filesystem at /opt/cli//, in ``container`` when install_agent put the agent in one, or on the VM host, ``on_host``, when it put it there. Writes a sidecar - bin/.env with the gateway URL and chmod +x's the entrypoint. Idempotent. Returns the path to the entrypoint.""" + bin/.env with the gateway URL, and the door token of a gateway in a slot (``slot_token``), and chmod +x's + the entrypoint. Idempotent. Returns the path to the entrypoint.""" from agent_env.providers.sandbox_providers.sandbox import VmSandbox, into_container, stage_files_into_container from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider, get_agent_sandbox_provider provider = build_sandbox_provider(deployed.sandbox_type) if deployed.sandbox_type else get_agent_sandbox_provider() @@ -309,9 +310,10 @@ async def install_cli( target_root = f"/opt/cli/{cli_artifact.command_name}" entrypoint_path = f"{target_root}/{cli_artifact.entrypoint}" env_dir = posixpath.dirname(entrypoint_path) + env_file = f"AGENT_ENV_GATEWAY_URL={gateway_url}\n" + (f"{SLOT_TOKEN_ENV_VAR}={slot_token}\n" if slot_token else "") if on_host: - await sandbox.write_host_file(f"AGENT_ENV_GATEWAY_URL={gateway_url}\n".encode(), f"{env_dir}/{GATEWAY_ENV_FILE}") + await sandbox.write_host_file(env_file.encode(), f"{env_dir}/{GATEWAY_ENV_FILE}") await stage_files_into_container( sandbox, cli_artifact.get_cli_files().get_file_artifacts(), target_root, on_host=True) await sandbox.exec_script(f"chmod +x {shlex.quote(entrypoint_path)}") @@ -319,7 +321,7 @@ async def install_cli( return entrypoint_path # write .env first — write_file_from_text creates the parent dir; write_file_from_object does not. - await sandbox.write_file_from_text(f"AGENT_ENV_GATEWAY_URL={gateway_url}\n", f"{env_dir}/{GATEWAY_ENV_FILE}", + await sandbox.write_file_from_text(env_file, f"{env_dir}/{GATEWAY_ENV_FILE}", **into_container(container)) for rel_path, file_artifact in cli_artifact.get_cli_files().get_file_artifacts().items(): diff --git a/src/agent_env/artifact/artifacts/cli.py b/src/agent_env/artifact/artifacts/cli.py index be231e256..beafb2662 100644 --- a/src/agent_env/artifact/artifacts/cli.py +++ b/src/agent_env/artifact/artifacts/cli.py @@ -27,6 +27,9 @@ _COMMAND_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9._-]*") # The file installing a CLI writes the gateway URL to, beside its entrypoint. GATEWAY_ENV_FILE = ".env" +# The door token of a gateway in a slot of a shared VM, which an installed CLI sends as the door's header on every call; +# unset for the default stack. +SLOT_TOKEN_ENV_VAR = "AGENT_ENV_SLOT_TOKEN" class CliArtifact(Artifact): diff --git a/src/agent_env/env/door_headers.py b/src/agent_env/env/door_headers.py new file mode 100644 index 000000000..af6f0d11d --- /dev/null +++ b/src/agent_env/env/door_headers.py @@ -0,0 +1,28 @@ +"""The header a slot's door takes (``gateway.door``), picked out of what a call is granted. + +A slot's grant (``DeployedGatewayEnv.grants``) gives the door's header on every address of the slot, beside the +control token on the gateway's. A call that today sends no credential sends only the door's header, so the door lets +it in and the service behind it sees nothing it didn't before; outside a slot that is nothing at all. +""" + +from __future__ import annotations + +from agentenv_protocol import client as protocol_v1 + +from agent_env.env.gateway.constants import SLOT_TOKEN_HEADER + + +def slot_token_headers(token: str | None) -> dict[str, str]: + """The header that carries a slot's door token; none without one, as for the default stack.""" + return {SLOT_TOKEN_HEADER: token} if token else {} + + +def door_headers(headers: dict[str, str]) -> dict[str, str]: + """The slot door's header among ``headers``, alone; none when they don't carry it.""" + return {SLOT_TOKEN_HEADER: headers[SLOT_TOKEN_HEADER]} if SLOT_TOKEN_HEADER in headers else {} + + +def granted_door_headers(url: str) -> dict[str, str]: + """The slot door's header the running step's grant gives a call to ``url`` (``protocol_v1.authorized``); none + outside a slot or a grant.""" + return door_headers(protocol_v1.request_headers(url)) diff --git a/src/agent_env/env/env.py b/src/agent_env/env/env.py index 377bede5e..2d3b772ae 100644 --- a/src/agent_env/env/env.py +++ b/src/agent_env/env/env.py @@ -7,6 +7,7 @@ from abc import ABC from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Optional, Self +from urllib.parse import urlsplit from agentenv_protocol import client as protocol_v1 from agentenv_protocol.website import READY_TIMEOUT_S, WEBSITE_EXTENSION_URI, WEBSITE_READY_OP, WebsiteReadiness, env_readiness @@ -18,6 +19,7 @@ from agent_env.utils.paths import validate_relative_filename from .gateway import GatewayMode +from .door_headers import door_headers, slot_token_headers from .gateway.constants import WELL_KNOWN_PATH from .store import get_env_store @@ -118,10 +120,20 @@ def control_headers(self) -> dict[str, str]: """What a call to the env's framework-only routes sends: its control token, when it has one.""" return protocol_v1.control_headers(self.control_token) + @property + def grants(self) -> dict[str, dict[str, str]]: + """What a call under each of the env's addresses sends, by address: ``control_headers`` under its own, as a + step's grant (``protocol_v1.authorized``) gives them.""" + return {self.environment_url: self.control_headers} if self.environment_url and self.control_headers else {} + def control_headers_for(self, url: str) -> dict[str, str]: - """What a call to ``url`` sends of the env's control token: ``control_headers`` when ``url`` is the env's - address or under it, as a step's grant gives them, and none anywhere else, an override's address say.""" - return protocol_v1.granted_headers(url, {self.environment_url: self.control_headers}) + """What a call to ``url`` sends: what ``grants`` gives the address it is or is under, and none anywhere else, + an override's address say.""" + return protocol_v1.granted_headers(url, self.grants) + + def door_headers_for(self, url: str) -> dict[str, str]: + """The slot door's header of what a call to ``url`` sends (``door_headers``); none for an env not in a slot.""" + return door_headers(self.control_headers_for(url)) def supports(self, uri: str, method: str) -> bool: """Whether the stored env card offers `method` on the extension at `uri`; no network.""" @@ -181,7 +193,8 @@ async def readiness(self, timeout: float = READY_TIMEOUT_S) -> WebsiteReadiness: raise EnvCapabilityUnsupported(WEBSITE_EXTENSION_URI, WEBSITE_READY_OP, self.env_id, self.instance_id) card = self.environment_card if card is None: - card = await protocol_v1.get_card(self.environment_url, timeout=timeout) + card = await protocol_v1.get_card(self.environment_url, timeout=timeout, + headers=self.door_headers_for(self.environment_url)) return await env_readiness(self.environment_url, card, timeout=timeout, headers=self.control_headers) @classmethod @@ -241,6 +254,30 @@ class DeployedGatewayEnv(DeployedSandboxEnv): # Where the gateway's stack lives when it is one slot of a VM other runs share (StackLayout.to_record); None for # the default stack, which has the VM to itself. stack_layout: Optional[dict] = None + # The token the door of a slot's stack takes on every request to its addresses; None for the default stack. + door_token: Optional[str] = None + + @property + def control_headers(self) -> dict[str, str]: + """What a call to the env's framework-only routes sends: in a slot, the door's header too.""" + return {**self._door_header, **super().control_headers} + + @property + def grants(self) -> dict[str, dict[str, str]]: + """In a slot, every address the door publishes takes its header: the gateway's with the control token, and + pgweb's and db-mcp's with the door's alone.""" + grants = super().grants + if self._door_header: + if self.gateway_url: + grants.setdefault(self.gateway_url.rstrip("/"), self.control_headers) + for url in (self.db_web_url, self.db_mcp_url): + if url: + grants.setdefault(_origin(url), self._door_header) + return grants + + @property + def _door_header(self) -> dict[str, str]: + return slot_token_headers(self.door_token) @classmethod def _fields_from(cls, data: dict) -> dict: @@ -256,6 +293,7 @@ def _fields_from(cls, data: dict) -> dict: "env_state_instance_ids": data.get("env_state_instance_ids") or [], "child_envs": data.get("child_envs") or {}, "stack_layout": data.get("stack_layout"), + "door_token": data.get("door_token"), } @@ -572,6 +610,12 @@ def _mcp_url(url: str, card: dict) -> str: return f"{url.rstrip('/')}/{protocol_v1.mcp_path(card).lstrip('/')}" +def _origin(url: str) -> str: + """``scheme://host[:port]`` of ``url``: all a door guards, since it holds the whole port.""" + parts = urlsplit(url) + return f"{parts.scheme}://{parts.netloc}" + + def _record_class(data: dict) -> type[DeployedEnv]: """A stored record's class: its provider type's, else its shape's, so a record from before the type (or of one unknown here) keeps every field.""" from agent_env.providers.env_providers.env_provider import record_class_for # providers import this module @@ -588,4 +632,4 @@ def _record_class(data: dict) -> type[DeployedEnv]: # A record carrying any of these is a gateway's. Not gateway_mode: an older kernel writes its default into any record it round-trips. _GATEWAY_ONLY_FIELDS = ("gateway_url", "db_web_url", "db_mcp_url", "website_frontend_urls", "vnc_url", "env_state_instance_ids", - "child_envs", "stack_layout") + "child_envs", "stack_layout", "door_token") diff --git a/src/agent_env/env/envs/multi_env.py b/src/agent_env/env/envs/multi_env.py index 48840f37e..e44a83af3 100644 --- a/src/agent_env/env/envs/multi_env.py +++ b/src/agent_env/env/envs/multi_env.py @@ -1133,7 +1133,8 @@ def _record_grant(deployed: Optional[DeployedEnv]): name it shares with another keeps from the record (``_hand_record_to_child_envs``), whose calls go to the gateway.""" if deployed is None: return protocol_v1.authorized({}) - return protocol_v1.authorized({url: deployed.control_headers for url in (deployed.environment_url, gateway_url_of(deployed))}) + return protocol_v1.authorized({**{url: deployed.control_headers for url in (deployed.environment_url, gateway_url_of(deployed))}, + **deployed.grants}) def _hand_record_to_child_envs(env: MultiEnv, deployed: DeployedEnv) -> None: diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index 26e3133d9..39849060e 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -331,3 +331,10 @@ def random_mcp_server_name() -> str: "required": False, }, ] + +# A slot's door (``gateway.door``): the one container of a slot of a shared VM that publishes host ports. It takes a +# request only with the slot's token in this header, which it removes before forwarding, and refuses every other. +SLOT_TOKEN_HEADER = "X-Agentenv-Slot-Token" +# The door's token, and its routes: comma-separated ``=:``, one per port the slot publishes. +DOOR_TOKEN_ENV = "AGENTENV_SLOT_TOKEN" +DOOR_ROUTES_ENV = "AGENTENV_DOOR_ROUTES" diff --git a/src/agent_env/env/gateway/door.py b/src/agent_env/env/gateway/door.py new file mode 100644 index 000000000..5a97a4b9a --- /dev/null +++ b/src/agent_env/env/gateway/door.py @@ -0,0 +1,190 @@ +"""A slot's door: the one container of a slot of a shared VM that publishes ports, each forwarded to one of the slot's +services (``python -m gateway.door``). It runs from the gateway image, so it needs nothing the gateway doesn't. + +A request gets through only with the slot's token as the ``X-Agentenv-Slot-Token`` header, compared in constant time; +the door removes that header and forwards the rest, ``Authorization`` and ``Host`` included, untouched. HTTP bodies +stream both ways, so server-sent events and long downloads pass as they come, and WebSockets are relayed frame by +frame. Every other request gets 401. Browsers can't set the header, and no cookie or ticket sign-in exists yet, so a +browser is refused too. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import hmac +import logging +import os + +import httpx +import uvicorn +from websockets.asyncio.client import connect +from websockets.exceptions import ConnectionClosed + +from .constants import DOOR_ROUTES_ENV, DOOR_TOKEN_ENV, SLOT_TOKEN_HEADER + +logger = logging.getLogger(__name__) + +_TOKEN_HEADER = SLOT_TOKEN_HEADER.lower().encode() +# Headers that describe one connection, not the request, so a proxy never forwards them (RFC 9110 7.6.1). +_HOP_BY_HOP = frozenset({b"connection", b"keep-alive", b"proxy-authenticate", b"proxy-authorization", b"te", + b"trailer", b"transfer-encoding", b"upgrade", b"proxy-connection"}) +_REFUSAL = (f"401: this slot's door takes only the {SLOT_TOKEN_HEADER} header. Browser sign-in (a cookie or a " + f"ticket) isn't supported yet.\n").encode() +_UPSTREAM_CONNECT_TIMEOUT_S = 10.0 + + +def parse_routes(spec: str) -> dict[int, str]: + """``=:,...`` as each listen port's upstream ``host:port``.""" + routes: dict[int, str] = {} + for entry in filter(None, (part.strip() for part in spec.split(","))): + port, _, upstream = entry.partition("=") + host, _, upstream_port = upstream.rpartition(":") + if not (port.isdigit() and host and upstream_port.isdigit()) or int(port) in routes: + raise ValueError(f"bad or repeated door route {entry!r}; expected =:") + routes[int(port)] = upstream + if not routes: + raise ValueError("the door has no routes") + return routes + + +class Door: + """The ASGI app in front of one upstream ``host:port``, letting in only requests that carry ``token``.""" + + def __init__(self, upstream: str, token: str, client: httpx.AsyncClient): + if not token: + raise ValueError("a door needs a token") + self._upstream = upstream + self._token = token.encode() + self._client = client + + async def __call__(self, scope, receive, send) -> None: + admitted = self._admitted(scope["headers"]) + headers = [(k, v) for k, v in scope["headers"] if k != _TOKEN_HEADER and k not in _HOP_BY_HOP] + if scope["type"] == "websocket": + await self._websocket(scope, receive, send, headers, admitted) + elif admitted: + await self._http(scope, receive, send, headers) + else: + await _respond(send, 401, _REFUSAL) + + def _admitted(self, headers) -> bool: + tokens = [value for key, value in headers if key == _TOKEN_HEADER] + return len(tokens) == 1 and hmac.compare_digest(tokens[0], self._token) + + def _target(self, scope, scheme: str) -> str: + path = scope.get("raw_path") or scope["path"].encode() + query = f"?{scope['query_string'].decode('latin-1')}" if scope.get("query_string") else "" + return f"{scheme}://{self._upstream}{path.decode('latin-1')}{query}" + + async def _http(self, scope, receive, send, headers) -> None: + has_body = any(key in (b"content-length", b"transfer-encoding") for key, _ in scope["headers"]) + + async def body(): + while True: + message = await receive() + if message["type"] == "http.disconnect": + return + yield message.get("body", b"") + if not message.get("more_body"): + return + + request = self._client.build_request(scope["method"], self._target(scope, "http"), headers=headers, + content=body() if has_body else None) + try: + response = await self._client.send(request, stream=True) + except httpx.HTTPError as e: + logger.warning("door: upstream %s unreachable: %r", self._upstream, e) + await _respond(send, 502, b"502: the slot's service isn't answering\n") + return + try: + await send({"type": "http.response.start", "status": response.status_code, + "headers": [(k, v) for k, v in response.headers.raw if k.lower() not in _HOP_BY_HOP]}) + async for chunk in response.aiter_raw(): + await send({"type": "http.response.body", "body": chunk, "more_body": True}) + await send({"type": "http.response.body", "body": b"", "more_body": False}) + finally: + await response.aclose() + + async def _websocket(self, scope, receive, send, headers, admitted: bool) -> None: + if (await receive())["type"] != "websocket.connect": + return + if not admitted: + await _deny_websocket(scope, send, 401, _REFUSAL) + return + forwarded = [(k.decode("latin-1"), v.decode("latin-1")) for k, v in headers + if k != b"host" and not k.startswith(b"sec-websocket-")] + try: + upstream = await connect(self._target(scope, "ws"), additional_headers=forwarded, + subprotocols=scope.get("subprotocols") or None, max_size=None, + open_timeout=_UPSTREAM_CONNECT_TIMEOUT_S) + except Exception as e: + logger.warning("door: WebSocket to %s failed: %r", self._upstream, e) + await _deny_websocket(scope, send, 502, b"502: the slot's service refused the WebSocket\n") + return + await send({"type": "websocket.accept", "subprotocol": upstream.subprotocol}) + + async def downstream(): + with contextlib.suppress(ConnectionClosed): + async for frame in upstream: + await send({"type": "websocket.send", **({"text": frame} if isinstance(frame, str) else {"bytes": frame})}) + await send({"type": "websocket.close", "code": upstream.close_code or 1000}) + + async def upstream_bound(): + while (message := await receive())["type"] == "websocket.receive": + await upstream.send(message["text"] if message.get("text") is not None else message.get("bytes") or b"") + await upstream.close() + + tasks = [asyncio.ensure_future(downstream()), asyncio.ensure_future(upstream_bound())] + try: + await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + finally: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await upstream.close() + + +async def _respond(send, status: int, body: bytes) -> None: + await send({"type": "http.response.start", "status": status, + "headers": [(b"content-type", b"text/plain"), (b"content-length", str(len(body)).encode())]}) + await send({"type": "http.response.body", "body": body}) + + +async def _deny_websocket(scope, send, status: int, body: bytes) -> None: + """Refuse a WebSocket handshake with an HTTP ``status`` where the server can send one, else close it.""" + if "websocket.http.response" in (scope.get("extensions") or {}): + await send({"type": "websocket.http.response.start", "status": status, + "headers": [(b"content-type", b"text/plain")]}) + await send({"type": "websocket.http.response.body", "body": body}) + else: + await send({"type": "websocket.close", "code": 1008}) + + +def door_client() -> httpx.AsyncClient: + """The client a door forwards with: no timeout once connected, as a stream may stay open, no redirects followed, + and no proxy from the environment.""" + return httpx.AsyncClient(timeout=httpx.Timeout(None, connect=_UPSTREAM_CONNECT_TIMEOUT_S), + follow_redirects=False, trust_env=False) + + +async def serve(routes: dict[int, str], token: str) -> None: + async with door_client() as client: + servers = [uvicorn.Server(uvicorn.Config(Door(upstream, token, client), host="0.0.0.0", port=port, + lifespan="off", proxy_headers=False, server_header=False, + date_header=False, log_level="warning")) + for port, upstream in routes.items()] + await asyncio.gather(*(server.serve() for server in servers)) + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + routes = parse_routes(os.environ.get(DOOR_ROUTES_ENV, "")) + token = os.environ.get(DOOR_TOKEN_ENV, "") + if not token: + raise SystemExit(f"{DOOR_TOKEN_ENV} is unset, and a door without a token would let anyone in") + asyncio.run(serve(routes, token)) + + +if __name__ == "__main__": + main() diff --git a/src/agent_env/env/legacy_protocol.py b/src/agent_env/env/legacy_protocol.py index 18d78e234..1acf6eb81 100644 --- a/src/agent_env/env/legacy_protocol.py +++ b/src/agent_env/env/legacy_protocol.py @@ -19,6 +19,8 @@ from mcp.types import CallToolResult from mcp.client.streamable_http import streamable_http_client +from agent_env.env.door_headers import granted_door_headers + if TYPE_CHECKING: from agent_env.env.env import DeployedEnv @@ -119,7 +121,7 @@ async def backing_servers(deployed: Optional[DeployedEnv], gateway_url: Optional card, address = deployed.environment_card, deployed.environment_url elif deployed is not None and deployed.environment_card_url and gateway: try: - card, address = await protocol_v1.get_card(gateway, timeout=timeout), gateway + card, address = await protocol_v1.get_card(gateway, timeout=timeout, headers=granted_door_headers(gateway)), gateway except httpx.HTTPError as e: why = f"its card at {gateway} could not be read ({type(e).__name__})" elif deployed is not None: @@ -183,7 +185,7 @@ async def v1_base_url(deployed: Optional[DeployedEnv], gateway_url: Optional[str if not mcp: _, card = await child_env_card(None, gateway_url, environment_name, mcp=False) return base_url if card is not None else None - return base_url if await protocol_v1.supports_v1(base_url) else None + return base_url if await protocol_v1.supports_v1(base_url, headers=granted_door_headers(base_url)) else None child = deployed.child_env(environment_name, mcp=mcp) return child.base_url(deployed.environment_url) if child is not None else None @@ -197,7 +199,7 @@ async def child_env_card(deployed: Optional[DeployedEnv], gateway_url: Optional[ if deployed is None or not deployed.environment_card: base_url = environment_base_url((gateway_url or "").rstrip("/"), environment_name, mcp=mcp) try: - return base_url, await protocol_v1.get_card(base_url, timeout=timeout) + return base_url, await protocol_v1.get_card(base_url, timeout=timeout, headers=granted_door_headers(base_url)) except httpx.HTTPStatusError as e: if e.response.status_code == 404: return base_url, None @@ -213,7 +215,8 @@ async def reset_via_rest( """POST ``{base_url}/api/reset``. Sends the seed path when given. Raises on non-2xx.""" body = {"mock_data_path": mock_data_path} if mock_data_path is not None else None async with httpx.AsyncClient(verify=verify) as client: - response = await client.post(f"{base_url}/api/reset", json=body, timeout=timeout) + response = await client.post(f"{base_url}/api/reset", json=body, timeout=timeout, + headers=granted_door_headers(base_url)) response.raise_for_status() result = response.json() logger.info(f"load_environment_artifact: REST reset succeeded: {result}") @@ -223,7 +226,8 @@ async def reset_via_rest( async def add_via_rest(base_url: str, file_path: str, timeout: int = 120, verify: bool = True) -> dict: """POST ``{base_url}/api/add`` with a backend file path. Raises on non-2xx.""" async with httpx.AsyncClient(verify=verify) as client: - response = await client.post(f"{base_url}/api/add", json={"file_path": file_path}, timeout=timeout) + response = await client.post(f"{base_url}/api/add", json={"file_path": file_path}, timeout=timeout, + headers=granted_door_headers(base_url)) response.raise_for_status() result = response.json() logger.info(f"load_environment_artifact: add response: {result}") @@ -239,7 +243,7 @@ async def export_state( async def _export_state_at(base_url: str, timeout: int, verify: bool) -> dict: async with httpx.AsyncClient(verify=verify) as client: - response = await client.get(f"{base_url}/export-state", timeout=timeout) + response = await client.get(f"{base_url}/export-state", timeout=timeout, headers=granted_door_headers(base_url)) response.raise_for_status() return response.json() diff --git a/src/agent_env/explorer/routers/triggers.py b/src/agent_env/explorer/routers/triggers.py index a1c44148d..5485a73ac 100644 --- a/src/agent_env/explorer/routers/triggers.py +++ b/src/agent_env/explorer/routers/triggers.py @@ -11,6 +11,7 @@ from fastapi import APIRouter, HTTPException from agent_env.config import get_config +from agent_env.env.door_headers import slot_token_headers from agent_env.env.store import ENV_INSTANCES_COLLECTION from agent_env.explorer.entity_ids import EntityId from agent_env.explorer.routers.common import docs @@ -90,9 +91,10 @@ async def instance_triggers(task_id: EntityId, instance_id: EntityId) -> dict: return payload -def _live_gateways(deployed_envs: list) -> list[tuple[str, str | None]]: - """``(env_id, gateway_url or None)`` per deployed env, from the env-instance records the deploy - writes rather than the run context's own copy, which a run request can supply.""" +def _live_gateways(deployed_envs: list) -> list[tuple[str, str | None, dict[str, str]]]: + """``(env_id, gateway_url or None, headers)`` per deployed env, from the env-instance records the deploy + writes rather than the run context's own copy, which a run request can supply; ``headers`` carry a slot's door + token, and are empty for the default stack.""" pairs = [ (env["env_id"], env["instance_id"]) for env in deployed_envs @@ -102,39 +104,40 @@ def _live_gateways(deployed_envs: list) -> list[tuple[str, str | None]]: return [] records = docs().query(ENV_INSTANCES_COLLECTION, Filter().where("instance_id", In([iid for _, iid in pairs]))) urls = {record["instance_id"]: (record.get("gateway_url") or "").rstrip("/") or None for record in records} - return [(env_id, urls.get(instance_id)) for env_id, instance_id in pairs] + doors = {record["instance_id"]: slot_token_headers(record.get("door_token")) for record in records} + return [(env_id, urls.get(instance_id), doors.get(instance_id, {})) for env_id, instance_id in pairs] async def _live_trigger_state(deployed_envs: list) -> tuple[dict, dict]: """Each env's ``/triggers/state`` and gateway clock, read concurrently. An env with no reachable gateway maps to None, so "unreachable" never reads as "no triggers".""" targets = await asyncio.to_thread(_live_gateways, deployed_envs) - state: dict = {env_id: None for env_id, _ in targets} + state: dict = {env_id: None for env_id, _, _ in targets} meta: dict = {} - reachable = [(env_id, url) for env_id, url in targets if url] + reachable = [(env_id, url, headers) for env_id, url, headers in targets if url] if not reachable: return state, meta async with httpx.AsyncClient(timeout=TRIGGER_STATE_TIMEOUT_SECONDS) as client: - async def _get(url: str, env_id: str, what: str): + async def _get(url: str, env_id: str, what: str, headers: dict[str, str]): try: - response = await client.get(url) + response = await client.get(url, headers=headers) response.raise_for_status() return response.json() except Exception: logger.warning("live %s unavailable for %s", what, env_id, exc_info=True) return None - async def _one(env_id: str, gateway_url: str): + async def _one(env_id: str, gateway_url: str, headers: dict[str, str]): triggers, clock = await asyncio.gather( - _get(f"{gateway_url}/triggers/state", env_id, "trigger state"), - _get(f"{gateway_url}/clock/state", env_id, "clock state"), + _get(f"{gateway_url}/triggers/state", env_id, "trigger state", headers), + _get(f"{gateway_url}/clock/state", env_id, "clock state", headers), ) # Stamped at the read: at a high clock rate a second of drift is a virtual day. return env_id, triggers, {"clock": clock, "clock_read_at_utc": datetime.now(timezone.utc).isoformat()} - for env_id, triggers, env_meta in await asyncio.gather(*(_one(e, u) for e, u in reachable)): + for env_id, triggers, env_meta in await asyncio.gather(*(_one(e, u, h) for e, u, h in reachable)): state[env_id] = triggers if triggers is not None: meta[env_id] = env_meta diff --git a/src/agent_env/providers/env_providers/constants.py b/src/agent_env/providers/env_providers/constants.py index 301da78c9..0ae1adc20 100644 --- a/src/agent_env/providers/env_providers/constants.py +++ b/src/agent_env/providers/env_providers/constants.py @@ -10,6 +10,10 @@ # websites adds is checked against that deploy's own services, whatever it's named, when its compose is rendered. GATEWAY_SERVICE_NAMES = frozenset({GATEWAY_SERVICE_NAME, "servicedb", "pgweb", "db-mcp"}) GATEWAY_APP_DIR = "/app" +# The network a gateway stack's services share, and the only one its database is on. +ENV_NETWORK = "env-network" +# The network the website browser shares with the gateway and the sites, and with nothing else in the env. +SITES_NETWORK = "website-network" AGENT_ENV_WEBSITE_BACKEND_PORT = 8000 AGENT_ENV_WEBSITE_HEALTH_PATH = "/api/health" diff --git a/src/agent_env/providers/env_providers/env_gateway_provider.py b/src/agent_env/providers/env_providers/env_gateway_provider.py index c352bbfff..bf3ef70f6 100644 --- a/src/agent_env/providers/env_providers/env_gateway_provider.py +++ b/src/agent_env/providers/env_providers/env_gateway_provider.py @@ -32,6 +32,7 @@ from agent_env.artifact.artifacts.docker_image import pull_problem from agent_env.attribution import Attribution from agent_env.config import get_config +from agent_env.env.door_headers import slot_token_headers from agent_env.env.env import DeployedGatewayEnv, _mcp_url from agent_env.env.gateway import AGENT_ENV_GATEWAY_MCP_PORT, ExternalChild, GatewayMode from agent_env.env.gateway.constants import ( @@ -62,9 +63,12 @@ AGENT_ENV_WEBSITE_BACKEND_SUFFIX, AGENT_ENV_WEBSITE_FRONTEND_SUFFIX, AGENT_ENV_WEBSITE_HEALTH_PATH, + ENV_NETWORK as _ENV_NETWORK, GATEWAY_SERVICE_NAME, GATEWAY_SERVICE_NAMES, + SITES_NETWORK as _SITES_NETWORK, ) +from agent_env.providers.env_providers.slot_compose import resolv_conf_path, slot_compose, slot_resolv_conf from agent_env.providers.env_providers.stack_layout import DEFAULT_STACK_LAYOUT, StackLayout from agent_env.providers.env_providers.env_provider import ( DeployRefused, @@ -96,10 +100,6 @@ _TRAJECTORY_READ_ATTEMPTS = 3 -# The network the env's services share, and the only one its database is on. -_ENV_NETWORK = "env-network" -# The network the website browser shares with the gateway and the sites, and with nothing else in the env. -_SITES_NETWORK = "website-network" # A gateway deploy's website browser when its caller names none: the run's, for one with websites. _THE_RUNS = object() @@ -170,6 +170,8 @@ class DeployedGateway: environment_card_read_at_utc: str | None = None # The token the gateway's control routes take, which the record keeps; None for a gateway started without one. control_token: str | None = None + # The token a slot's door takes on every request to the slot's ports, which the record keeps; None for the default stack. + door_token: str | None = None @dataclass @@ -348,9 +350,14 @@ def create_docker_compose( mcp_server_name: str | None = None, external_children: tuple[ExternalChild, ...] = (), control_token: str | None = None, + stack_layout: StackLayout = DEFAULT_STACK_LAYOUT, + door_token: str | None = None, ) -> str: """Generate docker-compose.yml content for a gateway deployment onto a VM/laptop/arbitrary machine. + For a slot's ``stack_layout``, the default stack's file refitted to the slot's walls, its ports behind a door + that takes ``door_token`` (``slot_compose``). + Supports MCP servers, websites, or both. Website containers (backend + frontend) are added to the same docker network. The gateway receives WEBSITE_URLS env var for discovery. The website browser sits on a network of its own with the gateway and each site's frontend (its backend when it @@ -663,6 +670,8 @@ def create_docker_compose( "networks:", *(line for network in (_ENV_NETWORK, *sites_network) for line in (f" {network}:", " driver: bridge")), ]) + if stack_layout.is_slot: + return slot_compose("\n".join(lines), stack_layout, door_image=gateway_image, door_token=door_token) return "\n".join(lines) async def deploy( @@ -726,6 +735,7 @@ async def deploy( env_state_instance_ids=deployed.env_state_instance_ids, control_token=deployed.control_token, stack_layout=self._stack_layout.to_record(), + door_token=deployed.door_token, ) async def create_gateway( @@ -841,6 +851,8 @@ async def _deploy_via_vm( website_images = website_images or [] sidecars = sidecars or [] layout = self._stack_layout + door_token = secrets.token_urlsafe(32) if layout.is_slot else None + door = slot_token_headers(door_token) config = get_config() gateway_env = Env.get(gateway_env_id(config)) @@ -934,6 +946,8 @@ async def _stand_up(_spec): extra_hosts=sandbox.extra_hosts, mcp_server_name=mcp_server_name, control_token=control_token, + stack_layout=layout, + door_token=door_token, ) compose_content = compose() logger.info(f"Generated docker-compose.yml:\n{_redact_compose_secrets(compose_content)}") @@ -941,6 +955,11 @@ async def _stand_up(_spec): # Write files to VM logger.info("Writing files to VM...") await sandbox.exec_script(f"mkdir -p {layout.app_dir}", max_retries=2) + if layout.is_slot: + code, box_resolv_conf, stderr = await sandbox.exec_with_output("cat", "/etc/resolv.conf") + if code: + raise RuntimeError(f"couldn't read /etc/resolv.conf on {sandbox.sandbox_id} (exit {code}): {stderr.strip()}") + await self._write_file(sandbox, resolv_conf_path(layout), slot_resolv_conf(box_resolv_conf).rstrip("\n")) # Only local postgres needs its init script to be directly run by the gateway's servicedb # container; remote/external stores are already initialized upstream. @@ -988,7 +1007,7 @@ async def _stand_up(_spec): # Wait for gateway to be fully ready (needs time to discover internal servers) # Host-side port: exec_with_output runs inside the VM on per-VM backends but on # the host for LocalSandbox, where the gateway is published elsewhere. - gateway_ready = await self._wait_for_gateway(sandbox, publish(gateway_port)) + gateway_ready = await self._wait_for_gateway(sandbox, publish(gateway_port), headers=door) # Print gateway logs for debugging logger.info("Gateway logs:") @@ -1017,14 +1036,15 @@ async def _stand_up(_spec): logger.info(f"DB MCP endpoint: {db_mcp_url}") # Wait for the tunnel to serve the env card, which the deploy records - card = await self._wait_for_tunnel(gateway_url, timeout=120) + card = await self._wait_for_tunnel(gateway_url, timeout=120, headers=door) if card is None: raise RuntimeError("Tunnel did not become ready in time") if website_configs: - await _wait_for_websites(gateway_url, website_configs, headers=control_headers(control_token)) - card = await self._wait_for_tunnel(gateway_url, timeout=120) or card + await _wait_for_websites(gateway_url, website_configs, headers={**door, **control_headers(control_token)}, + door_headers=door) + card = await self._wait_for_tunnel(gateway_url, timeout=120, headers=door) or card card_read_at_utc = datetime.now(timezone.utc).isoformat() - await self._refuse_tool_name_clashes(gateway_url) + await self._refuse_tool_name_clashes(gateway_url, headers=door) mcp_url = _mcp_url(gateway_url, card) logger.info(f"MCP endpoint: {mcp_url}") @@ -1038,6 +1058,7 @@ async def _stand_up(_spec): website_frontend_urls=website_frontend_urls, mcp_server_name=mcp_server_name, env_state_instance_ids=[state_instance.instance_id], environment_card=card, environment_card_read_at_utc=card_read_at_utc, control_token=control_token, + door_token=door_token, ) async def _deploy_via_containers( @@ -1203,12 +1224,12 @@ async def _deploy_via_containers( await self.close() raise - async def _refuse_tool_name_clashes(self, gateway_url: str) -> None: + async def _refuse_tool_name_clashes(self, gateway_url: str, *, headers: dict[str, str] | None = None) -> None: """Refuse the deploy when the gateway reports tool names more than one of its sources serves, which leaves it serving none of its servers' tools. A gateway whose /state can't be read, or that doesn't report clashes (an image older than the report), is let through as before.""" try: - async with httpx.AsyncClient() as client: + async with httpx.AsyncClient(headers=headers) as client: response = await client.get(f"{gateway_url}/state", timeout=_STATE_READ_TIMEOUT_S) response.raise_for_status() clashes = response.json().get(STATE_TOOL_NAME_CLASHES_KEY) @@ -1221,8 +1242,10 @@ async def _refuse_tool_name_clashes(self, gateway_url: str) -> None: f"serves none of their tools: {tool_name_clashes_text(clashes)}. Rename the tools, or deploy those " f"servers in separate envs") - async def _wait_for_gateway(self, sandbox: VmSandbox, port: int, timeout: int = 300) -> bool: - """Wait for the gateway to answer on ``port``. + async def _wait_for_gateway(self, sandbox: VmSandbox, port: int, timeout: int = 300, *, + headers: dict[str, str] | None = None) -> bool: + """Wait for the gateway to answer on ``port``, sending ``headers``: a slot's door answers 401 without its + header, which would pass for the gateway being up. Probes the well-known document, not ``/mcp``: a healthy MCP endpoint replies with an open event-stream, which a readiness check has no business holding. Any status @@ -1233,9 +1256,10 @@ async def _wait_for_gateway(self, sandbox: VmSandbox, port: int, timeout: int = """ logger.info(f"Waiting for gateway to be ready (timeout={timeout}s)...") probe_url = f"http://localhost:{port}{WELL_KNOWN_PATH}" + header_args = [arg for name, value in (headers or {}).items() for arg in ("-H", f"{name}: {value}")] for i in range(timeout): exit_code, stdout, stderr = await sandbox.exec_with_output( - "curl", "-s", "--max-time", "5", "-o", "/dev/null", "-w", "%{http_code}", probe_url + "curl", "-s", "--max-time", "5", *header_args, "-o", "/dev/null", "-w", "%{http_code}", probe_url ) http_code = stdout.strip() if http_code.isdigit() and int(http_code) > 0 and int(http_code) < 500: @@ -1765,7 +1789,7 @@ def _compose_name_problems(mcp_servers: list[MCPServerConfig], website_configs: # rendered compose is logged. Matches the key to the left of the first '=' on an # ` - KEY=VALUE` env line. _SECRET_ENV_KEY_RE = re.compile(r"^(\s*-\s*)([A-Za-z0-9_]*(?:SECRET|PASSWORD|TOKEN|API_KEY)[A-Za-z0-9_]*)=.*$") -_SETTINGS_LINE_RE = re.compile(rf'^(\s*-\s*")({WEBSITE_SETTINGS_ENV})=.*$') +_SETTINGS_LINE_RE = re.compile(rf'^(\s*-\s*["\'])({WEBSITE_SETTINGS_ENV})=.*$') def _compose_ps_rows(text: str) -> list[dict]: @@ -1824,7 +1848,7 @@ def _network_lines(*networks: str) -> list[str]: def _redact_compose_secrets(compose_content: str) -> str: """Mask secret-valued env lines so the logged compose never carries a live secret, a site's settings among them.""" return "\n".join( - _SETTINGS_LINE_RE.sub(r'\1\2=***"', _SECRET_ENV_KEY_RE.sub(r"\1\2=***", line)) + _SETTINGS_LINE_RE.sub(lambda m: f"{m[1]}{m[2]}=***{m[1][-1]}", _SECRET_ENV_KEY_RE.sub(r"\1\2=***", line)) for line in compose_content.splitlines() ) @@ -1884,15 +1908,16 @@ class WebsiteContractError(RuntimeError): async def _wait_for_websites(gateway_url: str, website_configs: list[WebsiteConfig], *, - headers: dict[str, str] | None = None, timeout_s: float = WEBSITE_READY_TIMEOUT_S, - poll_s: float = WEBSITE_READY_POLL_S) -> None: + headers: dict[str, str] | None = None, door_headers: dict[str, str] | None = None, + timeout_s: float = WEBSITE_READY_TIMEOUT_S, poll_s: float = WEBSITE_READY_POLL_S) -> None: """Wait until each site is ready, as its card says through ``/svc//``, asked with the gateway's control ``headers``, since its data plane takes them: by ``website/v1``'s ``ready``, or, for a card without it or a site serving none, by its stored health path answering 200, which is deprecated. A site whose answer says how long it may take (``timeout_s``) is waited that long, or its own ``ready_timeout_s`` if longer, and ``WEBSITE_READY_MARGIN_S``; any other its ``ready_timeout_s`` and the margin, or ``timeout_s`` if longer. Raises naming each site still not ready, and why, once one is waited past its time, and at once, with - ``WebsiteContractError``, for a site that answers its card's path with something that isn't a card.""" + ``WebsiteContractError``, for a site that answers its card's path with something that isn't a card. A slot's + ``door_headers`` go on its card and health reads too.""" started = time.monotonic() waiting = {wc.environment_name: wc for wc in website_configs} own = {wc.environment_name: wc.ready_timeout_s or 0 for wc in website_configs} @@ -1901,7 +1926,8 @@ async def _wait_for_websites(gateway_url: str, website_configs: list[WebsiteConf warned: set[str] = set() while waiting: for name, wc in list(waiting.items()): - ready, why[name], declared = await _website_ready(f"{gateway_url}/svc/{name}", wc.health_path, headers=headers) + ready, why[name], declared = await _website_ready(f"{gateway_url}/svc/{name}", wc.health_path, headers=headers, + door_headers=door_headers) if declared is not None: limit[name] = max(declared, own[name]) + WEBSITE_READY_MARGIN_S if ready is None and name not in warned: @@ -1919,13 +1945,13 @@ async def _wait_for_websites(gateway_url: str, website_configs: list[WebsiteConf await asyncio.sleep(poll_s) -async def _website_ready(base_url: str, health_path: str, *, - headers: dict[str, str] | None = None) -> tuple[Optional[bool], str, Optional[float]]: +async def _website_ready(base_url: str, health_path: str, *, headers: dict[str, str] | None = None, + door_headers: dict[str, str] | None = None) -> tuple[Optional[bool], str, Optional[float]]: """Whether the site at ``base_url`` is ready, why not, and how long it says it may take: True or False by the ``WebsiteReadiness`` its card's ``website/v1`` ``ready`` answers, as the protocol's ``website_readiness`` reads it, an answer that isn't one False; with no card or no ``ready`` on it, None once its health path answers 200 and False before.""" - async with httpx.AsyncClient() as client: + async with httpx.AsyncClient(headers=door_headers) as client: try: card = _card_of(await client.get(base_url + WELL_KNOWN_PATH, timeout=10), base_url) readiness = None if card is None else await website_readiness(base_url, card, timeout=10, headers=headers) @@ -1974,7 +2000,7 @@ async def _probe_tools(env_id: str | None, gateway: DeployedGateway) -> None: cards = (gateway.environment_card or {}).get("children_environments") or [] children = ",".join(c.get("name") or "" for c in cards) async with asyncio.timeout(_TOOLS_PROBE_TIMEOUT_S): - tools = set(await _tool_names(gateway.mcp_url)) + tools = set(await _tool_names(gateway.mcp_url, headers=slot_token_headers(gateway.door_token) or None)) missing = [c.get("name") or "" for c in cards if not _card_tool_names(c) <= tools] except Exception as e: logger.warning(f"{head} status=failed duration_s={time.monotonic() - start:.1f} children={children} error_type={type(e).__name__} error={e!r}") diff --git a/src/agent_env/providers/env_providers/env_provider.py b/src/agent_env/providers/env_providers/env_provider.py index 3b71b1f0b..6ffe4889d 100644 --- a/src/agent_env/providers/env_providers/env_provider.py +++ b/src/agent_env/providers/env_providers/env_provider.py @@ -123,7 +123,7 @@ async def _reattach_containers(self, provider: SandboxProvider, gateway: Sandbox self._container_sandboxes = [server, *(db for db in dbs if not isinstance(db, BaseException)), gateway] return server - async def _wait_for_tunnel(self, url: str, timeout: int = 60) -> dict | None: + async def _wait_for_tunnel(self, url: str, timeout: int = 60, *, headers: dict[str, str] | None = None) -> dict | None: """Wait until the deployed env serves its card to this process; returns the card. Probes the well-known document rather than ``/mcp``, whose healthy endpoint holds the @@ -133,7 +133,7 @@ async def _wait_for_tunnel(self, url: str, timeout: int = 60) -> dict | None: probe_url = f"{url}{WELL_KNOWN_PATH}" logger.info(f"Waiting for tunnel to be ready (timeout={timeout}s) via {probe_url}...") last = "no response" - async with httpx.AsyncClient() as client: + async with httpx.AsyncClient(headers=headers) as client: for i in range(timeout): try: response = await client.get(probe_url, timeout=5) @@ -211,12 +211,18 @@ def _card_from(response: httpx.Response) -> dict | None: return card if isinstance(card, dict) and isinstance(card.get("name"), str) and card["name"] else None -async def _tool_names(mcp_url: str) -> list[str]: - """The server's tool names as it lists them, duplicates included.""" - async with streamable_http_client(mcp_url) as (read_stream, write_stream, _): - async with ClientSession(read_stream, write_stream) as session: - await session.initialize() - return [tool.name for tool in (await session.list_tools()).tools] +async def _tool_names(mcp_url: str, *, headers: dict[str, str] | None = None) -> list[str]: + """The server's tool names as it lists them, duplicates included; ``headers``, a slot door's, go on every request.""" + http_client = httpx.AsyncClient(headers=headers) if headers else None + try: + async with streamable_http_client(mcp_url, **({"http_client": http_client} if http_client else {})) as ( + read_stream, write_stream, _): + async with ClientSession(read_stream, write_stream) as session: + await session.initialize() + return [tool.name for tool in (await session.list_tools()).tools] + finally: + if http_client is not None: + await http_client.aclose() def _builtin_env_providers() -> dict[str, type[_SandboxEnvironmentProvider]]: diff --git a/src/agent_env/providers/env_providers/slot_compose.py b/src/agent_env/providers/env_providers/slot_compose.py new file mode 100644 index 000000000..0167ed605 --- /dev/null +++ b/src/agent_env/providers/env_providers/slot_compose.py @@ -0,0 +1,163 @@ +"""A slot's compose file: the default stack's, refitted to the walls of a shared box. + +Every service runs under gVisor (``runsc``) at a fixed address on its slot's networks, which have fixed subnets and +bridge names (``shared_box_walls``). Docker's embedded DNS doesn't answer under gVisor, so each service resolves the +services it shares a network with from ``extra_hosts``, exactly the names Docker's DNS would give it, and the internet +through the box's resolvers in a mounted resolv.conf. No service publishes a port but the door, which takes over every +port the stack would have published and lets in only requests carrying the slot's token (``gateway.door``). +""" + +from __future__ import annotations + +import posixpath +from collections.abc import Mapping +from ipaddress import IPv4Network + +import yaml + +from agent_env.env.gateway.constants import DOOR_ROUTES_ENV, DOOR_TOKEN_ENV +from agent_env.providers.env_providers.constants import ENV_NETWORK, SITES_NETWORK +from agent_env.providers.env_providers.stack_layout import StackLayout +from agent_env.providers.sandbox_providers.shared_box_walls import slot_bridges, slot_networks, upstream_resolvers + +DOOR_SERVICE_NAME = "agentenv-door" +DOOR_COMMAND = ["python", "-m", "gateway.door"] +SLOT_RUNTIME = "runsc" +_BRIDGE_NAME_OPTION = "com.docker.network.bridge.name" +# Compose keys that would let a slot's container reach past its walls: host devices and capabilities, another +# namespace than its own, a looser seccomp or AppArmor profile. +_REFUSED_KEYS = ("privileged", "cap_add", "devices", "device_cgroup_rules", "network_mode", "pid", "ipc", "uts", + "userns_mode", "cgroup_parent", "security_opt", "volumes_from", "sysctls") + + +def resolv_conf_path(layout: StackLayout) -> str: + return f"{layout.app_dir}/resolv.conf" + + +def slot_resolv_conf(box_resolv_conf: str) -> str: + """The resolv.conf a slot's services mount: the box's IPv4 resolvers, the only ones the walls let them reach.""" + return "".join(f"nameserver {resolver}\n" for resolver in upstream_resolvers(box_resolv_conf)) + + +def slot_compose(compose: str, layout: StackLayout, *, door_image: str, door_token: str) -> str: + """``compose``, a default-stack compose file, refitted for ``layout``'s slot (see the module doc), with a door run + from ``door_image`` that takes ``door_token``. Raises if the result breaks a wall (``slot_compose_problems``).""" + index = layout.slot_index + if index is None: + raise ValueError(f"only a layout made by StackLayout.for_slot has a slot's walls; got {layout}") + if not door_token: + raise ValueError("a slot's door needs a token") + networks = _slot_network_plan(index) + doc = yaml.safe_load(compose) + services: dict[str, dict] = doc["services"] + if DOOR_SERVICE_NAME in services: + raise ValueError(f"a service is already named {DOOR_SERVICE_NAME!r}, the slot's door") + for name, service in services.items(): + if unknown := [n for n in _service_networks(service) if n not in networks]: + raise ValueError(f"service {name!r} is on {unknown}, which a slot has no subnet for") + services[DOOR_SERVICE_NAME] = _door(services, door_image, door_token) + + addresses = _addresses(services, networks) + resolv_conf_mount = f"{resolv_conf_path(layout)}:/etc/resolv.conf:ro" + for name, service in services.items(): + service["runtime"] = SLOT_RUNTIME + service["networks"] = {network: {"ipv4_address": address} for network, address in addresses[name].items()} + peers: dict[str, str] = {} + for network in addresses[name]: + for peer, theirs in addresses.items(): + if peer != name and network in theirs: + peers.setdefault(peer, theirs[network]) + service["extra_hosts"] = [*(service.get("extra_hosts") or []), *(f"{peer}:{ip}" for peer, ip in peers.items())] + service["volumes"] = [*(service.get("volumes") or []), resolv_conf_mount] + used = {network for service_addresses in addresses.values() for network in service_addresses} + doc["networks"] = {network: { + "driver": "bridge", + "enable_ipv6": False, + "driver_opts": {_BRIDGE_NAME_OPTION: bridge}, + "ipam": {"config": [{"subnet": str(subnet)}]}, + } for network, (subnet, bridge) in networks.items() if network in used} + if problems := slot_compose_problems(doc, layout): + raise ValueError(f"slot {index}'s compose file breaks its walls: {'; '.join(problems)}") + return yaml.safe_dump(doc, sort_keys=False, width=float("inf")) + + +def slot_compose_problems(doc: Mapping, layout: StackLayout) -> list[str]: + """Why a slot's parsed compose file would let a container past its walls: a key in ``_REFUSED_KEYS``, a runtime + other than gVisor, a published port on any service but the door, the docker socket, or a bind mount from outside + ``layout.app_dir``. Empty when there is none.""" + problems = [] + for name, service in (doc.get("services") or {}).items(): + problems += [f"{name} sets {key}" for key in _REFUSED_KEYS if key in service] + if service.get("runtime") != SLOT_RUNTIME: + problems.append(f"{name} runs under {service.get('runtime')!r}, not {SLOT_RUNTIME}") + if service.get("ports") and name != DOOR_SERVICE_NAME: + problems.append(f"{name} publishes ports; only the door may") + for volume in service.get("volumes") or []: + if problem := _volume_problem(volume, layout.app_dir): + problems.append(f"{name} {problem}") + return problems + + +def _slot_network_plan(index: int) -> dict[str, tuple[IPv4Network, str]]: + """Each network a stack may use, with slot ``index``'s subnet and bridge name for it.""" + subnets, bridges = slot_networks(index), slot_bridges(index) + return {ENV_NETWORK: (subnets.env, bridges.env), SITES_NETWORK: (subnets.website, bridges.website)} + + +def _service_networks(service: Mapping) -> list[str]: + networks = service.get("networks") or [] + return list(networks) if isinstance(networks, (list, Mapping)) else [] + + +def _door(services: dict[str, dict], image: str, token: str) -> dict: + """The door service: every port the stack's services publish, taken off them, on the same host port, forwarded + to the service's container port. Its own container listens on the host port's number.""" + routes, ports = [], [] + for name, service in services.items(): + for spec in service.pop("ports", None) or []: + *host_ip, host_port, container_port = str(spec).split(":") + if ENV_NETWORK not in _service_networks(service): + raise ValueError(f"service {name!r} publishes {spec} but isn't on {ENV_NETWORK}, where the door is") + routes.append(f"{host_port}={name}:{container_port}") + ports.append(":".join([*host_ip, host_port, host_port])) + return { + "image": image, + "command": list(DOOR_COMMAND), + "environment": [f"{DOOR_ROUTES_ENV}={','.join(routes)}", f"{DOOR_TOKEN_ENV}={token}"], + "ports": ports, + "restart": "unless-stopped", + "networks": [ENV_NETWORK], + } + + +def _addresses(services: Mapping[str, Mapping], networks: Mapping[str, tuple[IPv4Network, str]]) -> dict[str, dict[str, str]]: + """Each service's address on each of its networks, handed out in service order from the subnet's second host; + the first is the bridge's own.""" + free = {network: iter(list(subnet.hosts())[1:]) for network, (subnet, _) in networks.items()} + addresses: dict[str, dict[str, str]] = {} + for name, service in services.items(): + try: + addresses[name] = {network: str(next(free[network])) for network in _service_networks(service)} + except StopIteration: + raise ValueError(f"slot networks have no address left for service {name!r}") from None + return addresses + + +def _volume_problem(volume: object, app_dir: str) -> str | None: + """Why a service's volume would reach past its slot: the docker socket, or a bind from outside ``app_dir``.""" + if isinstance(volume, Mapping): + source = str(volume.get("source") or "") + bind = volume.get("type") == "bind" + else: + source = str(volume).split(":", 1)[0] + bind = source.startswith(("/", ".", "~")) + if "docker.sock" in source: + return f"mounts the docker socket ({source})" + if not bind: + return None + if source.startswith("~"): + return f"bind-mounts {source}, outside {app_dir}" + resolved = posixpath.normpath(posixpath.join(app_dir, source)) + if resolved != app_dir and not resolved.startswith(f"{app_dir}/"): + return f"bind-mounts {source}, outside {app_dir}" + return None diff --git a/src/agent_env/providers/env_providers/stack_layout.py b/src/agent_env/providers/env_providers/stack_layout.py index 04ff5c723..b5001fd49 100644 --- a/src/agent_env/providers/env_providers/stack_layout.py +++ b/src/agent_env/providers/env_providers/stack_layout.py @@ -63,6 +63,14 @@ def is_slot(self) -> bool: """A slot names its compose project; only the default stack leaves it to compose.""" return self.compose_project is not None + @property + def slot_index(self) -> int | None: + """The index ``for_slot`` made this layout for; None for the default stack, or a slot layout built by hand.""" + index = (self.compose_project or "")[1:] + if not (self.is_slot and self.compose_project.startswith("s") and index.isascii() and index.isdigit()): + return None + return int(index) if self == StackLayout.for_slot(int(index)) else None + @classmethod def for_slot(cls, index: int) -> StackLayout: """Slot ``index`` of a shared VM: compose project ``s{index}`` names its dir and scratch files, its host ports are the index's block. @@ -143,9 +151,7 @@ def teardown_script(self) -> str: not made by ``for_slot``: a hand-built project such as ``s1-x`` would have its files caught by ``s1``'s glob.""" if not self.is_slot: raise ValueError("only a slot's stack is torn down on its own; the default stack ends with its VM") - index = self.compose_project[1:] - if not (self.compose_project.startswith("s") and index.isascii() and index.isdigit() - and self == StackLayout.for_slot(int(index))): + if self.slot_index is None: raise ValueError(f"only a layout made by StackLayout.for_slot is torn down, so its dir and scratch glob " f"can't reach another stack's files; got {self}") label = shlex.quote(f"label=com.docker.compose.project={self.compose_project}") diff --git a/src/agent_env/providers/sandbox_providers/shared_box_walls.py b/src/agent_env/providers/sandbox_providers/shared_box_walls.py index 92e4e6fb0..67b4b8f19 100644 --- a/src/agent_env/providers/sandbox_providers/shared_box_walls.py +++ b/src/agent_env/providers/sandbox_providers/shared_box_walls.py @@ -17,6 +17,9 @@ SLOT_COUNT = 46 SLOT_RANGE = IPv4Network("10.250.0.0/16") +# Every slot network's Linux bridge is named with this prefix, so the firewall can match slot traffic by the interface +# it arrived on, which a container can't spoof as it can a source address. +SLOT_BRIDGE_PREFIX = "aes" _PRIVATE_RANGES = tuple(IPv4Network(n) for n in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", "100.64.0.0/10")) FORWARD_CHAIN, INPUT_CHAIN = "AGENTENV-WALLS-FWD", "AGENTENV-WALLS-IN" @@ -38,6 +41,17 @@ def slot_networks(index: int) -> SlotNetworks: return SlotNetworks(env.supernet(), env, website) +class SlotBridges(NamedTuple): + env: str + website: str + + +def slot_bridges(index: int) -> SlotBridges: + """The Linux bridge names of slot ``index``'s env and website networks, at most 9 characters (Linux allows 15).""" + slot_networks(index) + return SlotBridges(f"{SLOT_BRIDGE_PREFIX}{index}env", f"{SLOT_BRIDGE_PREFIX}{index}web") + + def upstream_resolvers(resolv_conf: str) -> tuple[IPv4Address, ...]: """The IPv4 nameservers of a resolv.conf, in order. IPv6 ones are skipped, as slots have no IPv6; a resolver in the slot range, or none at all, raises.""" diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 8b761d893..234789fad 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -700,7 +700,7 @@ async def _run_one(step: TaskStep, idx: int, dispatch_epoch: int) -> None: started_mono = time.monotonic() started_utc = datetime.now(timezone.utc).isoformat() try: - with protocol_v1.authorized({d.environment_url: d.control_headers for d in context.deployed_envs}): + with protocol_v1.authorized({url: sent for d in context.deployed_envs for url, sent in d.grants.items()}): await step.execute(context) except asyncio.CancelledError: raise diff --git a/src/agent_env/task_step/task_steps/deploy_agent.py b/src/agent_env/task_step/task_steps/deploy_agent.py index cbb4adb95..f2c8c53e4 100644 --- a/src/agent_env/task_step/task_steps/deploy_agent.py +++ b/src/agent_env/task_step/task_steps/deploy_agent.py @@ -451,7 +451,8 @@ async def _execute(self, context: TaskStepContext, deployed_agents: list) -> Tas url = host_url_for(live_mcp_url(env_id), deployed.sandbox_type) card_name = None if mcp_ext: - body = _mcp_add_body(mcp_ext, url, sandbox_request_headers_for_url(url), card_name, self.role) + door = deployed_env.door_headers_for(deployed_env.mcp_url or "") if deployed_env is not None else {} + body = _mcp_add_body(mcp_ext, url, {**sandbox_request_headers_for_url(url), **door}, card_name, self.role) registrations.append((env_id, body)) identity_payload: dict[str, str] = {"name": self.agent_name} diff --git a/src/agent_env/task_step/task_steps/env_card_validator/verify_env_card.py b/src/agent_env/task_step/task_steps/env_card_validator/verify_env_card.py index fc32eace9..9ded9ea02 100644 --- a/src/agent_env/task_step/task_steps/env_card_validator/verify_env_card.py +++ b/src/agent_env/task_step/task_steps/env_card_validator/verify_env_card.py @@ -54,7 +54,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: card = None error = None try: - card = await protocol_v1.get_card(deployed.environment_url) + card = await protocol_v1.get_card(deployed.environment_url, + headers=deployed.door_headers_for(deployed.environment_url)) except Exception as e: error = f"{type(e).__name__}: {e}" logger.warning(f"env card for '{self.env_id}' inaccessible at {deployed.environment_url}: {error}") diff --git a/src/agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py b/src/agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py index c6358ac2b..7fe8a1054 100644 --- a/src/agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py +++ b/src/agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py @@ -59,7 +59,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: card = None try: - card = await protocol_v1.get_card(deployed.environment_url) + card = await protocol_v1.get_card(deployed.environment_url, + headers=deployed.door_headers_for(deployed.environment_url)) except Exception as e: logger.warning(f"env card for '{self.env_id}' inaccessible at {deployed.environment_url}: {type(e).__name__}: {e}") diff --git a/src/agent_env/task_step/task_steps/load_artifact.py b/src/agent_env/task_step/task_steps/load_artifact.py index 96657cbb1..f841de92c 100644 --- a/src/agent_env/task_step/task_steps/load_artifact.py +++ b/src/agent_env/task_step/task_steps/load_artifact.py @@ -625,7 +625,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: if not (agent.on_host and agent.sandbox_type == LocalSandbox.type): gateway_url = reachable_url(gateway_url, from_sandbox_type=deployed.sandbox_type, to_sandbox_type=agent.sandbox_type) - install_path = await A2AAgent.install_cli(deployed_agent, artifact, gateway_url, **_agent_files(agent)) + install_path = await A2AAgent.install_cli(deployed_agent, artifact, gateway_url, **_agent_files(agent), + slot_token=getattr(deployed, "door_token", None)) agent_clis = context.metadata.setdefault("installed_clis", {}).setdefault(self.agent_name, {}) agent_clis[artifact.id] = { "install_path": install_path, diff --git a/src/agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py b/src/agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py index afab39ad8..17cd3da06 100644 --- a/src/agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py +++ b/src/agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py @@ -17,6 +17,7 @@ from agent_env.artifact import CliArtifact from agent_env.artifact.store import artifact_write_lock from agent_env.env import Env +from agent_env.env.door_headers import granted_door_headers from agent_env.env.env import require_gateway_url, website_child from agent_env.store.ids import derive_id from agent_env.task_step.context import StepContextError, TaskStepContext @@ -35,7 +36,7 @@ async def _resolve_manifest_endpoint(gateway_url: str, environment_name: str) -> having nothing to advertise is the normal case, so these are debug-level. """ try: - card = await protocol_v1.get_card(gateway_url) + card = await protocol_v1.get_card(gateway_url, headers=granted_door_headers(gateway_url)) except (httpx.HTTPError, ValueError) as e: logger.debug("env card for %r unavailable (%s); constructing the manifest path", environment_name, e) return None diff --git a/src/agent_env/task_step/task_steps/mcp_cli_builder/codegen.py b/src/agent_env/task_step/task_steps/mcp_cli_builder/codegen.py index 4be0384b0..4bf5d4a12 100644 --- a/src/agent_env/task_step/task_steps/mcp_cli_builder/codegen.py +++ b/src/agent_env/task_step/task_steps/mcp_cli_builder/codegen.py @@ -14,7 +14,9 @@ from agentenv_protocol import MANIFEST_VERSION, manifest_compatible +from agent_env.artifact.artifacts.cli import SLOT_TOKEN_ENV_VAR from agent_env.env.gateway import AGENT_ENV_ROLE_HEADER +from agent_env.env.gateway.constants import SLOT_TOKEN_HEADER GATEWAY_URL_ENV_VAR = "AGENT_ENV_GATEWAY_URL" ROLE_ENV_VAR = "AGENT_ENV_ROLE" @@ -166,6 +168,8 @@ def generate_cli_script( role_env_var=ROLE_ENV_VAR, default_role=DEFAULT_CLI_ROLE, role_header=AGENT_ENV_ROLE_HEADER, + slot_token_env_var=SLOT_TOKEN_ENV_VAR, + slot_token_header=SLOT_TOKEN_HEADER, ) @@ -186,6 +190,8 @@ def generate_cli_script( ROLE_ENV = "{role_env_var}" DEFAULT_ROLE = "{default_role}" ROLE_HEADER = "{role_header}" +SLOT_TOKEN_ENV = "{slot_token_env_var}" +SLOT_TOKEN_HEADER = "{slot_token_header}" SERVICE_NAME = {environment_name} INTERFACE_MANIFEST = {interface_manifest_literal} _CONFIG_FILE_NAME = ".env" @@ -226,11 +232,16 @@ def _role(): return os.environ.get(ROLE_ENV, DEFAULT_ROLE) +def _headers(): + token = os.environ.get(SLOT_TOKEN_ENV) + return {{ROLE_HEADER: _role(), **({{SLOT_TOKEN_HEADER: token}} if token else {{}})}} + + def _post_step(payload): response = httpx.post( f"{{_gateway_url()}}/step", json=payload, - headers={{ROLE_HEADER: _role()}}, + headers=_headers(), timeout=120, ) response.raise_for_status() @@ -248,7 +259,7 @@ def _list_tools(): allowed_names = {{t.get("name") for t in (role_filtered.get("tools") or []) if t.get("name")}} state_resp = httpx.get( f"{{_gateway_url()}}/state", - headers={{ROLE_HEADER: _role()}}, + headers=_headers(), timeout=120, ) state_resp.raise_for_status() diff --git a/src/agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py b/src/agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py index 8366ac898..c79a4f557 100644 --- a/src/agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py +++ b/src/agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py @@ -127,7 +127,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: mcp_url = deployed.mcp_url logger.info(f"Connecting to MCP at {mcp_url} to verify tool schemas") - http_client = httpx.AsyncClient() + http_client = httpx.AsyncClient(headers=deployed.door_headers_for(mcp_url or "")) try: async with streamable_http_client(mcp_url, http_client=http_client) as (read_stream, write_stream, _): async with ClientSession(read_stream, write_stream) as session: diff --git a/src/agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py b/src/agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py index f9c69919d..9532fc0dd 100644 --- a/src/agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py +++ b/src/agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py @@ -417,7 +417,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: spec_url = f"{base_url}/openapi.yaml" logger.info(f"Fetching OpenAPI spec for '{environment_name}' at {spec_url}") async with httpx.AsyncClient(timeout=_HTTP_TIMEOUT_S) as client: - resp = await client.get(spec_url) + resp = await client.get(spec_url, headers=deployed.door_headers_for(spec_url)) if resp.status_code in _SPEC_ABSENT_STATUSES: return self._record( context, env, environment_name, diff --git a/src/agent_env/task_step/task_steps/snapshot_env.py b/src/agent_env/task_step/task_steps/snapshot_env.py index 64284ea91..f81fef173 100644 --- a/src/agent_env/task_step/task_steps/snapshot_env.py +++ b/src/agent_env/task_step/task_steps/snapshot_env.py @@ -25,6 +25,7 @@ from agentenv_protocol.types import FileWithBytes from agent_env.a2a_agent.object_transfer import ObjectLimits, namespace_grant +from agent_env.env.door_headers import granted_door_headers from agent_env.env.gateway.constants import CHANGES_PAGE_MAX, EXT_CHANGES_URI, EXT_TRAJECTORY_URI from agent_env.store import get_config from agent_env.store.base import GrantUnavailableError @@ -582,7 +583,7 @@ async def _export_environment_to_file( raise ValueError( f"FilePart for '{environment_name}' names {uri!r}, which is not on its service's address {base_url}" ) - async with httpx.AsyncClient() as client: + async with httpx.AsyncClient(headers=granted_door_headers(uri)) as client: async with client.stream( "GET", uri, diff --git a/tst/unit/env/door_grant_test.py b/tst/unit/env/door_grant_test.py new file mode 100644 index 000000000..ea35d35e0 --- /dev/null +++ b/tst/unit/env/door_grant_test.py @@ -0,0 +1,120 @@ +"""A slot's door token rides the env's grant to the slot's own addresses, and every caller that sends no credential of +its own sends it there; the default stack's grant and calls are what they always were.""" + +from __future__ import annotations + +import functools +from types import SimpleNamespace +from unittest.mock import patch + +import httpx +import pytest +from agentenv_protocol import client as protocol_v1 + +from agent_env.env import legacy_protocol +from agent_env.env.env import DeployedEnv, DeployedGatewayEnv +from agent_env.env.gateway.constants import SLOT_TOKEN_HEADER +from agent_env.explorer.routers import triggers +from agent_env.task_step.task_steps.mcp_cli_builder.build_mcp_cli import _resolve_manifest_endpoint +from agent_env.task_step.task_steps.mcp_cli_builder.codegen import generate_cli_script + +GATEWAY = "https://s1-gw.modal.host" +PGWEB = "https://s1-pgweb.modal.host/" +DB_MCP = "https://s1-dbmcp.modal.host/mcp" +DOOR = {SLOT_TOKEN_HEADER: "door-tok"} +CONTROL = {"Authorization": "Bearer ctl"} + + +def _record(door_token: str | None) -> DeployedGatewayEnv: + return DeployedGatewayEnv(env_id="crm", env_version=1, sandbox_id="vm", gateway_url=GATEWAY, db_web_url=PGWEB, + db_mcp_url=DB_MCP, environment_card_url=f"{GATEWAY}/.well-known/agent-env.json", + control_token="ctl", door_token=door_token) + + +def test_the_default_stacks_grant_is_its_control_token_on_its_address_alone(): + record = _record(None) + assert record.grants == {GATEWAY: CONTROL} + assert record.control_headers == CONTROL + for url in (GATEWAY, PGWEB, DB_MCP): + assert record.door_headers_for(url) == {} + + +def test_a_slots_grant_carries_the_door_header_to_each_of_its_addresses_and_nowhere_else(): + record = _record("door-tok") + assert record.grants == {GATEWAY: {**DOOR, **CONTROL}, "https://s1-pgweb.modal.host": DOOR, + "https://s1-dbmcp.modal.host": DOOR} + assert record.control_headers == {**DOOR, **CONTROL} + assert record.control_headers_for(f"{GATEWAY}/svc/mcp-slack/api/reset") == {**DOOR, **CONTROL} + assert record.control_headers_for("https://s1-dbmcp.modal.host/") == DOOR + assert record.control_headers_for(f"{PGWEB}api/query") == DOOR + for elsewhere in ("https://s2-gw.modal.host", "https://s1-gw.modal.host.evil.example", "https://example.com"): + assert record.control_headers_for(elsewhere) == {} + assert record.door_headers_for(f"{GATEWAY}/mcp") == DOOR + + +def test_the_door_token_survives_the_record_round_trip(): + record = DeployedEnv.from_dict({"env_id": "crm", "env_version": 1, "sandbox_id": "vm", "door_token": "door-tok", + "gateway_url": GATEWAY}) + assert isinstance(record, DeployedGatewayEnv) and record.door_token == "door-tok" + assert DeployedEnv.from_dict({"env_id": "crm", "env_version": 1, "door_token": "t"}).door_token == "t" + + +@pytest.fixture +def seen(monkeypatch) -> list[httpx.Request]: + """Every request any httpx client sends, answered 200 with a card-shaped body.""" + requests: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request) + return httpx.Response(200, json={"name": "crm", "ok": True}) + + monkeypatch.setattr(httpx, "AsyncClient", functools.partial(httpx.AsyncClient, transport=httpx.MockTransport(handler))) + return requests + + +async def _legacy_calls(base: str) -> None: + await legacy_protocol.reset_via_rest(base) + await legacy_protocol.add_via_rest(base, "/data/x.json") + await legacy_protocol._export_state_at(base, timeout=5, verify=True) + await legacy_protocol.v1_base_url(None, GATEWAY, "slack") + await _resolve_manifest_endpoint(base, "slack") + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("door_token", "sent"), [(None, {}), ("door-tok", DOOR)]) +async def test_legacy_calls_under_a_grant_send_the_door_header_alone(seen, door_token, sent): + with protocol_v1.authorized(_record(door_token).grants): + await _legacy_calls(f"{GATEWAY}/svc/mcp-slack") + assert len(seen) == 5 + for request in seen: + assert {k: v for k, v in request.headers.items() if k in (SLOT_TOKEN_HEADER.lower(), "authorization")} == \ + {k.lower(): v for k, v in sent.items()} + + +@pytest.mark.asyncio +async def test_a_card_read_sends_only_what_it_is_given(seen): + await protocol_v1.get_card(GATEWAY) + await protocol_v1.get_card(GATEWAY, headers=DOOR) + assert SLOT_TOKEN_HEADER.lower() not in seen[0].headers + assert seen[1].headers[SLOT_TOKEN_HEADER] == "door-tok" and "authorization" not in seen[1].headers + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("door_token", "sent"), [(None, None), ("door-tok", "door-tok")]) +async def test_the_explorer_reads_live_trigger_state_with_the_records_door_token(seen, door_token, sent): + record = {"instance_id": "i1", "gateway_url": GATEWAY, **({"door_token": door_token} if door_token else {})} + with patch.object(triggers, "docs", return_value=SimpleNamespace(query=lambda *a, **k: [record])): + await triggers._live_trigger_state([{"env_id": "crm", "instance_id": "i1"}]) + assert [r.url.path for r in seen] == ["/triggers/state", "/clock/state"] + assert all(r.headers.get(SLOT_TOKEN_HEADER) == sent for r in seen) + + +@pytest.mark.parametrize(("token", "sent"), [(None, None), ("door-tok", "door-tok")]) +def test_a_generated_cli_sends_the_slot_token_it_was_installed_with(monkeypatch, token, sent): + namespace: dict = {"__name__": "generated_cli", "__file__": "/nonexistent/bin/crm"} + exec(compile(generate_cli_script("crm"), "cli", "exec"), namespace) + monkeypatch.delenv(namespace["SLOT_TOKEN_ENV"], raising=False) + if token: + monkeypatch.setenv(namespace["SLOT_TOKEN_ENV"], token) + assert namespace["_headers"]().get(SLOT_TOKEN_HEADER) == sent + assert namespace["ROLE_HEADER"] in namespace["_headers"]() diff --git a/tst/unit/env/envs/test_multi_env_name.py b/tst/unit/env/envs/test_multi_env_name.py index 35d78b764..457a70c61 100644 --- a/tst/unit/env/envs/test_multi_env_name.py +++ b/tst/unit/env/envs/test_multi_env_name.py @@ -67,7 +67,7 @@ async def test_a_deploy_records_the_mcp_url_and_name_its_gateway_card_gives(): card = {"name": "crm", "additionalInterfaces": [{"url": "/mcp", "transport": "mcp"}]} result = SimpleNamespace(gateway_url="https://gw.example", mcp_url="https://gw.example/mcp", db_web_url=None, db_mcp_url=None, website_frontend_urls=None, environment_card=card, environment_card_read_at_utc="t", - env_state_instance_ids=[], mcp_server_name="crm", control_token="t0k") + env_state_instance_ids=[], mcp_server_name="crm", control_token="t0k", door_token=None) async def deploy_gateway(self, sandbox_provider, **kwargs): self._sandbox = SimpleNamespace(sandbox_id="gw", type="modal_vm") diff --git a/tst/unit/env/gateway/door_test.py b/tst/unit/env/gateway/door_test.py new file mode 100644 index 000000000..f0e68dedb --- /dev/null +++ b/tst/unit/env/gateway/door_test.py @@ -0,0 +1,179 @@ +"""A slot's door, in front of a live upstream on loopback: it lets in only requests with the slot's token, takes the +token off them, and passes everything else through, streams and WebSockets included.""" + +from __future__ import annotations + +import asyncio +import json +import socket +import time + +import httpx +import pytest +import pytest_asyncio +import uvicorn +from pytest_socket import enable_socket +from starlette.applications import Starlette +from starlette.requests import Request +from starlette.responses import JSONResponse, StreamingResponse +from starlette.routing import Route, WebSocketRoute +from starlette.websockets import WebSocket +from websockets.asyncio.client import connect +from websockets.exceptions import InvalidStatus + +from agent_env.env.gateway import door +from agent_env.env.gateway.constants import DOOR_ROUTES_ENV, DOOR_TOKEN_ENV, SLOT_TOKEN_HEADER + +TOKEN = "the-slots-token" +STREAM_GAP_S = 0.6 + + +async def _echo(request: Request) -> JSONResponse: + return JSONResponse({"method": request.method, "path": request.url.path, "query": request.url.query, + "headers": dict(request.headers), "body": (await request.body()).decode()}) + + +async def _stream(_: Request) -> StreamingResponse: + async def chunks(): + yield b"data: first\n\n" + await asyncio.sleep(STREAM_GAP_S) + yield b"data: second\n\n" + return StreamingResponse(chunks(), media_type="text/event-stream") + + +async def _ws(websocket: WebSocket) -> None: + await websocket.accept(subprotocol=(websocket.scope.get("subprotocols") or [None])[0]) + await websocket.send_json({"headers": dict(websocket.headers)}) + async for message in websocket.iter_text(): + await websocket.send_text(f"echo {message}") + + +_UPSTREAM = Starlette(routes=[Route("/echo", _echo, methods=["GET", "POST"]), Route("/stream", _stream), + WebSocketRoute("/ws", _ws)]) + + +async def _serve(app) -> tuple[uvicorn.Server, int]: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.bind(("127.0.0.1", 0)) + config = uvicorn.Config(app, log_level="critical", access_log=False, lifespan="off") + config.load() + server = uvicorn.Server(config) + server.lifespan = config.lifespan_class(config) + await server.startup(sockets=[sock]) + return server, sock.getsockname()[1] + + +@pytest_asyncio.fixture +async def door_port(): + enable_socket() # loopback only + upstream, upstream_port = await _serve(_UPSTREAM) + async with door.door_client() as client: + front, port = await _serve(door.Door(f"127.0.0.1:{upstream_port}", TOKEN, client)) + try: + yield port + finally: + await front.shutdown() + await upstream.shutdown() + + +def _token(value: str = TOKEN) -> dict[str, str]: + return {SLOT_TOKEN_HEADER: value} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("headers", [{}, _token("wrong"), _token(TOKEN[:-1]), {"Authorization": f"Bearer {TOKEN}"}]) +async def test_a_request_without_the_slots_token_gets_401(door_port, headers): + async with httpx.AsyncClient() as client: + response = await client.get(f"http://127.0.0.1:{door_port}/echo", headers=headers) + assert response.status_code == 401 + assert SLOT_TOKEN_HEADER in response.text and "Browser sign-in" in response.text + + +@pytest.mark.asyncio +async def test_the_token_twice_is_refused(door_port): + async with httpx.AsyncClient() as client: + response = await client.get(f"http://127.0.0.1:{door_port}/echo", + headers=[(SLOT_TOKEN_HEADER, TOKEN), (SLOT_TOKEN_HEADER, TOKEN)]) + assert response.status_code == 401 + + +@pytest.mark.asyncio +async def test_with_the_token_a_request_passes_without_it_and_with_everything_else(door_port): + async with httpx.AsyncClient() as client: + response = await client.post(f"http://127.0.0.1:{door_port}/echo?a=1&b=2", content=b"payload", + headers={**_token(), "Authorization": "Bearer control", "Host": "shop.example.com", + "X-Other": "kept"}) + assert response.status_code == 200 + seen = response.json() + assert (seen["method"], seen["path"], seen["query"], seen["body"]) == ("POST", "/echo", "a=1&b=2", "payload") + assert SLOT_TOKEN_HEADER.lower() not in seen["headers"] + assert seen["headers"]["authorization"] == "Bearer control" + assert seen["headers"]["host"] == "shop.example.com" + assert seen["headers"]["x-other"] == "kept" + + +@pytest.mark.asyncio +async def test_a_stream_passes_as_it_comes(door_port): + async with httpx.AsyncClient() as client: + async with client.stream("GET", f"http://127.0.0.1:{door_port}/stream", headers=_token()) as response: + assert response.status_code == 200 + assert response.headers["content-type"].startswith("text/event-stream") + started = time.monotonic() + chunks = [] + async for chunk in response.aiter_text(): + chunks.append((chunk, time.monotonic() - started)) + assert "".join(chunk for chunk, _ in chunks) == "data: first\n\ndata: second\n\n" + assert chunks[0][1] < STREAM_GAP_S / 2 + + +@pytest.mark.asyncio +async def test_a_websocket_is_relayed_without_the_token(door_port): + async with connect(f"ws://127.0.0.1:{door_port}/ws", additional_headers={**_token(), "Authorization": "Bearer c"}, + subprotocols=["mcp"]) as ws: + assert ws.subprotocol == "mcp" + hello = json.loads(await ws.recv()) + assert SLOT_TOKEN_HEADER.lower() not in hello["headers"] + assert hello["headers"]["authorization"] == "Bearer c" + await ws.send("ping") + assert await ws.recv() == "echo ping" + + +@pytest.mark.asyncio +async def test_a_websocket_without_the_token_gets_401(door_port): + with pytest.raises(InvalidStatus) as refused: + async with connect(f"ws://127.0.0.1:{door_port}/ws"): + pass + assert refused.value.response.status_code == 401 + + +@pytest.mark.asyncio +async def test_an_upstream_that_isnt_up_is_a_502_not_a_pass(): + enable_socket() + with socket.socket() as free: + free.bind(("127.0.0.1", 0)) + dead = free.getsockname()[1] + async with door.door_client() as client: + front, port = await _serve(door.Door(f"127.0.0.1:{dead}", TOKEN, client)) + try: + async with httpx.AsyncClient() as caller: + response = await caller.get(f"http://127.0.0.1:{port}/", headers=_token()) + finally: + await front.shutdown() + assert response.status_code == 502 + + +def test_routes_parse_and_bad_ones_are_refused(): + assert door.parse_routes("19765=gateway:18765,9081=pgweb:8081") == {19765: "gateway:18765", 9081: "pgweb:8081"} + for bad in ("", "19765", "x=gateway:1", "1=gateway", "1=a:2,1=b:3"): + with pytest.raises(ValueError): + door.parse_routes(bad) + + +def test_a_door_never_starts_without_a_token(monkeypatch): + monkeypatch.setenv(DOOR_ROUTES_ENV, "19765=gateway:18765") + monkeypatch.delenv(DOOR_TOKEN_ENV, raising=False) + with pytest.raises(SystemExit, match=DOOR_TOKEN_ENV): + door.main() + with pytest.raises(ValueError): + door.Door("gateway:18765", "", httpx.AsyncClient()) + diff --git a/tst/unit/env/task_step/verify_env_card_test.py b/tst/unit/env/task_step/verify_env_card_test.py index 359275014..dcc337d45 100644 --- a/tst/unit/env/task_step/verify_env_card_test.py +++ b/tst/unit/env/task_step/verify_env_card_test.py @@ -57,7 +57,7 @@ def _run(step, ctx, *, card=None, exc=None, env_name="items"): class TestExecute: def test_available_card(self): result_ctx, env, get_card = _run(_make_step(), _make_context(), card=CARD) - get_card.assert_awaited_once_with("https://gw") + get_card.assert_awaited_once_with("https://gw", headers={}) update = env.update_metadata.call_args[0][0] assert update["environment_card"] == CARD v = update["validated_environment_card"] @@ -75,7 +75,7 @@ def test_a_server_record_persists_the_servers_own_card(self): environment_card_url=f"https://srv{WELL_KNOWN_PATH}", sandbox_id="srv")] leaf = {**{k: v for k, v in CARD.items() if k != "children_environments"}, "name": "items"} _, env, get_card = _run(_make_step(), ctx, card=leaf) - get_card.assert_awaited_once_with("https://srv") + get_card.assert_awaited_once_with("https://srv", headers={}) update = env.update_metadata.call_args[0][0] assert update["environment_card"] == leaf and update["validated_environment_card"]["accessible"] is True diff --git a/tst/unit/providers/env_providers/compose_fixture.py b/tst/unit/providers/env_providers/compose_fixture.py new file mode 100644 index 000000000..8c2cbc956 --- /dev/null +++ b/tst/unit/providers/env_providers/compose_fixture.py @@ -0,0 +1,60 @@ +"""One gateway topology with every kind of service a compose file renders, for the default-stack golden and the slot +compose tests: MCP servers on and off the database, a website browser on the sites network, websites with and without +a frontend, a live site, a sidecar, an external child, pgweb and db-mcp.""" + +from __future__ import annotations + +from unittest.mock import patch + +from agent_env.env.envs.service_db import ServiceDBConfig +from agent_env.env.gateway import ExternalChild +from agent_env.providers.env_providers import env_gateway_provider +from agent_env.providers.env_providers.env_gateway_provider import ( + EnvironmentGatewayProvider, + MCPServerConfig, + SidecarConfig, + WebsiteConfig, +) +from agent_env.providers.env_state import LocalPostgresStateProvider + +# A website backend's session secret is drawn per render; the golden holds this one. +FIXED_SESSION_SECRET = "0" * 64 + + +class _Image: + def __init__(self, image_name: str): + self.image_name = image_name + + +def render(**overrides) -> str: + """The fixture topology's compose, as ``create_docker_compose`` renders it with ``overrides``.""" + kwargs = dict( + mcp_servers=[ + MCPServerConfig(image="mcp-slack", environment_name="slack", extra_env_vars={"SLACK_MODE": "mock"}), + MCPServerConfig(image="mcp-calc", environment_name="calc"), + MCPServerConfig(image="playwright-mcp", environment_name="browser", networks=("website-network",)), + ], + gateway_image="agent-gateway", + gateway_port=18765, + website_configs=[ + WebsiteConfig(backend_image="shop-be", frontend_image="shop-fe", environment_name="shop", + domains=("shop.example.com",), listed_by_name=True), + WebsiteConfig(backend_image="blog-be", frontend_image=None, environment_name="blog", shm_mb=256), + WebsiteConfig(backend_image="feed-be", frontend_image=None, environment_name="feed", live=True, + settings={"mode": "live"}), + ], + sidecars=[SidecarConfig(environment_name="relay", image_artifact=_Image("ecr/relay:1.0.4"), + container_port=8000, host_port=18768, env={"RELAY_MODE": "remote"})], + state_provider=LocalPostgresStateProvider(service_db_config=ServiceDBConfig(db_web_image="agent-env-db-web", db_mcp_image="agent-env-db-mcp")), + state_instance=LocalPostgresStateProvider.default_instance(), + host_port=lambda port: port + 1000, + host_ips=("10.0.0.5",), + extra_hosts=("host.docker.internal:host-gateway",), + mcp_server_name="crm1234", + external_children=(ExternalChild(name="desk", mcp_url="https://desk.example.com/mcp", + base_url="https://desk.example.com"),), + control_token="ctl-token", + ) + kwargs.update(overrides) + with patch.object(env_gateway_provider.secrets, "token_hex", return_value=FIXED_SESSION_SECRET): + return EnvironmentGatewayProvider().create_docker_compose(**kwargs) diff --git a/tst/unit/providers/env_providers/env_gateway_provider_test.py b/tst/unit/providers/env_providers/env_gateway_provider_test.py index d8df4242a..b9a87b550 100644 --- a/tst/unit/providers/env_providers/env_gateway_provider_test.py +++ b/tst/unit/providers/env_providers/env_gateway_provider_test.py @@ -1894,10 +1894,10 @@ async def test_probe_compares_the_gateway_tools_with_the_stored_card(monkeypatch assert record.levelno == (logging.INFO if status == "ok" else logging.WARNING) assert f"env_id=crm-suite status={status} tools={len(tools)} " in record.getMessage() assert record.getMessage().endswith(f" children=a,b missing={missing}") - env_gateway_provider._tool_names.assert_awaited_once_with("https://gw.example/mcp") + env_gateway_provider._tool_names.assert_awaited_once_with("https://gw.example/mcp", headers=None) -async def _never_answers(_mcp_url: str) -> set[str]: +async def _never_answers(_mcp_url: str, **_) -> set[str]: await asyncio.sleep(60) return set() @@ -2092,7 +2092,7 @@ async def test_deploy_returns_the_gateway_record_for_the_env(caplog): record = await gp.deploy(env, _vm_provider(create_vm=AsyncMock(return_value=vm)), gateway_mode=GatewayMode.CONSISTENT, ttl_seconds=60, env_state_type="remote") - clashes_checked.assert_awaited_once_with("https://vm.example") + clashes_checked.assert_awaited_once_with("https://vm.example", headers={}) acquire.assert_awaited_once_with(env_state_type="remote", ttl_seconds=60, name_hint="crm-env", env_state_instance_id=None) [server] = compose.call_args.kwargs["mcp_servers"] @@ -3149,3 +3149,45 @@ def test_a_gateway_record_keeps_its_slot_layout_through_storage_and_an_older_rec assert DeployedEnv.from_dict(dataclasses.asdict(record)).stack_layout == StackLayout.for_slot(4).to_record() older = {k: v for k, v in dataclasses.asdict(_multi_record([])).items() if k != "stack_layout"} assert DeployedEnv.from_dict(older).stack_layout is None + + +class _ComposeRendered(Exception): + pass + + +async def _door_token_of_a_deploy(layout: StackLayout) -> str | None: + """The door token a VM deploy in ``layout`` hands its compose file, the deploy stopped right there.""" + from agent_env.env.gateway import GatewayMode + + gp = EnvironmentGatewayProvider() + gp._stack_layout = layout + tokens = [] + + def compose(**kwargs): + tokens.append(kwargs["door_token"]) + raise _ComposeRendered + + box = MagicMock(sandbox_id="box", ON_THIS_MACHINE=False, load_docker_images=AsyncMock()) + with patch("agent_env.env.env.Env.get", MagicMock(return_value=MagicMock(docker_image_artifact=_loadable("gw")))), \ + patch("agent_env.config.get_config", return_value=MagicMock(default_gateway_env_id="gw-id")), \ + patch.object(gp, "create_docker_compose", side_effect=compose), pytest.raises(_ComposeRendered): + await gp._deploy_via_vm(_vm_provider(), [], [], 18765, None, None, GatewayMode.PERFORMANCE, 60, 10, + existing_sandbox=box) + [token] = tokens + return token + + +@pytest.mark.asyncio +async def test_every_slot_deploy_draws_a_door_token_no_deploy_had_and_the_default_stack_none(): + tokens = [await _door_token_of_a_deploy(StackLayout.for_slot(2)) for _ in range(3)] + assert len(set(tokens)) == 3 and all(len(token) >= 43 for token in tokens) + assert await _door_token_of_a_deploy(DEFAULT_STACK_LAYOUT) is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("headers", "sent"), [(None, []), ({"X-Agentenv-Slot-Token": "tok"}, ["-H", "X-Agentenv-Slot-Token: tok"])]) +async def test_the_gateway_wait_sends_a_slots_door_header_and_nothing_new_for_the_default_stack(headers, sent): + sandbox = MagicMock(exec_with_output=AsyncMock(return_value=(0, "200", ""))) + assert await EnvironmentGatewayProvider()._wait_for_gateway(sandbox, 19765, headers=headers) + argv = sandbox.exec_with_output.await_args.args + assert [a for i, a in enumerate(argv) if a == "-H" or argv[i - 1] == "-H"] == sent diff --git a/tst/unit/providers/env_providers/golden/default_stack_compose.yml b/tst/unit/providers/env_providers/golden/default_stack_compose.yml new file mode 100644 index 000000000..f4ef237cb --- /dev/null +++ b/tst/unit/providers/env_providers/golden/default_stack_compose.yml @@ -0,0 +1,240 @@ +services: + servicedb: + image: public.ecr.aws/docker/library/postgres:16-alpine + environment: + - POSTGRES_USER=agentenv + - POSTGRES_PASSWORD=agentenv + - POSTGRES_DB=agentenv + healthcheck: + test: ['CMD-SHELL', 'pg_isready -U agentenv'] + interval: 5s + timeout: 5s + retries: 5 + volumes: + - ./init-schemas.sql:/docker-entrypoint-initdb.d/init-schemas.sql + networks: + - env-network + + pgweb: + image: agent-env-db-web + restart: unless-stopped + depends_on: + servicedb: + condition: service_healthy + environment: + - PGWEB_DATABASE_URL=postgres://agentenv:agentenv@servicedb:5432/agentenv?sslmode=disable + - PGWEB_LOCK_SESSION=true + ports: + - "10.0.0.5:9081:8081" + networks: + - env-network + + db-mcp: + image: agent-env-db-mcp + restart: unless-stopped + depends_on: + servicedb: + condition: service_healthy + environment: + - DATABASE_URI=postgresql://agentenv:agentenv@servicedb:5432/agentenv + command: --transport=streamable-http --streamable-http-host=0.0.0.0 --access-mode=unrestricted + ports: + - "10.0.0.5:19767:8000" + networks: + - env-network + + slack: + image: mcp-slack + depends_on: + servicedb: + condition: service_healthy + environment: + - MCP_HOST=0.0.0.0 + - MCP_PORT=18765 + - SERVICE_NAME=slack + - ENVIRONMENT_NAME=slack + - DATABASE_URL=postgresql://agentenv:agentenv@servicedb:5432/agentenv?options=-c%20search_path%3D%22slack%22,public + - SLACK_MODE=mock + healthcheck: + test: ["CMD-SHELL", "python3 -c \"import socket; s=socket.create_connection(('localhost',18765),2); s.close()\""] + interval: 5s + timeout: 5s + retries: 30 + start_period: 60s + networks: + - env-network + + calc: + image: mcp-calc + depends_on: + servicedb: + condition: service_healthy + environment: + - MCP_HOST=0.0.0.0 + - MCP_PORT=18765 + - SERVICE_NAME=calc + - ENVIRONMENT_NAME=calc + - DATABASE_URL=postgresql://agentenv:agentenv@servicedb:5432/agentenv?options=-c%20search_path%3D%22calc%22,public + healthcheck: + test: ["CMD-SHELL", "python3 -c \"import socket; s=socket.create_connection(('localhost',18765),2); s.close()\""] + interval: 5s + timeout: 5s + retries: 30 + start_period: 60s + networks: + - env-network + + browser: + image: playwright-mcp + environment: + - MCP_HOST=0.0.0.0 + - MCP_PORT=18765 + - SERVICE_NAME=browser + - ENVIRONMENT_NAME=browser + healthcheck: + test: ["CMD-SHELL", "python3 -c \"import socket; s=socket.create_connection(('localhost',18765),2); s.close()\""] + interval: 5s + timeout: 5s + retries: 30 + start_period: 60s + networks: + - website-network + + gateway: + image: agent-gateway + depends_on: + servicedb: + condition: service_healthy + slack: + condition: service_healthy + calc: + condition: service_healthy + browser: + condition: service_healthy + shop-website-backend: + condition: service_healthy + blog-website-backend: + condition: service_healthy + feed-website-backend: + condition: service_healthy + environment: + - MCP_HOST=0.0.0.0 + - MCP_PORT=18765 + - MCP_SERVER_NAME=crm1234 + - INTERNAL_MCP_SERVERS=slack,calc,browser,desk=https://desk.example.com/mcp + - INTERNAL_MCP_PORT=18765 + - GATEWAY_TRAJECTORY_FILE=/var/log/agentenv/trajectory.jsonl + - WEBSITE_URLS=shop=http://shop-website-frontend:80,blog=http://blog-website-backend:8000 + - WEBSITE_NAMES=shop=shop.example.com + - WEBSITE_LISTED_BY_NAME=shop + - REST_PROXY_URLS=mcp-slack=http://slack:18765,mcp-calc=http://calc:18765,mcp-browser=http://browser:18765,shop=http://shop-website-backend:8000,blog=http://blog-website-backend:8000,feed=http://feed-website-backend:8000,desk=https://desk.example.com + - GATEWAY_MODE=performance + - SERVICE_DB_URL=postgresql://agentenv:agentenv@servicedb:5432/agentenv + - AGENTENV_CONTROL_TOKEN=ctl-token + - CONTROL_TOKEN_CHILDREN=desk + - COMPUTERS=desk + ports: + - "10.0.0.5:19765:18765" + extra_hosts: + - "host.docker.internal:host-gateway" + restart: on-failure + healthcheck: + test: ["CMD-SHELL", "python3 -c \"import socket; s=socket.create_connection(('localhost',18765),2); s.close()\""] + interval: 15s + timeout: 5s + retries: 10 + start_period: 15s + networks: + - env-network + - website-network + + shop-website-backend: + image: shop-be + depends_on: + servicedb: + condition: service_healthy + environment: + - DATABASE_URL=postgresql://agentenv:agentenv@servicedb:5432/agentenv?options=-c%20search_path%3D%22shop%22,public + - SERVICE_NAME=shop + - ENVIRONMENT_NAME=shop + - PORT=8000 + - WEBSITE_SESSION_SECRET=0000000000000000000000000000000000000000000000000000000000000000 + - PYTHONUNBUFFERED=1 + healthcheck: + test: ["CMD-SHELL", "if command -v curl >/dev/null 2>&1; then get() { curl -sf --max-time 2 -o /dev/null \"$$1\"; }; elif command -v wget >/dev/null 2>&1; then get() { wget -q -T 2 -O /dev/null \"$$1\"; }; elif command -v python3 >/dev/null 2>&1; then get() { python3 -c 'import sys, urllib.request; urllib.request.urlopen(sys.argv[1], timeout=2)' \"$$1\"; }; elif command -v node >/dev/null 2>&1; then get() { node -e 'fetch(process.argv[1], {signal: AbortSignal.timeout(2000)}).then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))' \"$$1\"; }; else exit 1; fi; for u in http://localhost:8000/.well-known/agent-env.json http://localhost:8000/api/health; do get \"$$u\" 2>/dev/null && exit 0; done; exit 1"] + interval: 10s + timeout: 5s + start_period: 30s + retries: 3 + networks: + - env-network + + shop-website-frontend: + image: shop-fe + depends_on: + shop-website-backend: + condition: service_healthy + networks: + - env-network + - website-network + + blog-website-backend: + image: blog-be + depends_on: + servicedb: + condition: service_healthy + environment: + - DATABASE_URL=postgresql://agentenv:agentenv@servicedb:5432/agentenv?options=-c%20search_path%3D%22blog%22,public + - SERVICE_NAME=blog + - ENVIRONMENT_NAME=blog + - PORT=8000 + - WEBSITE_SESSION_SECRET=0000000000000000000000000000000000000000000000000000000000000000 + - PYTHONUNBUFFERED=1 + healthcheck: + test: ["CMD-SHELL", "if command -v curl >/dev/null 2>&1; then get() { curl -sf --max-time 2 -o /dev/null \"$$1\"; }; elif command -v wget >/dev/null 2>&1; then get() { wget -q -T 2 -O /dev/null \"$$1\"; }; elif command -v python3 >/dev/null 2>&1; then get() { python3 -c 'import sys, urllib.request; urllib.request.urlopen(sys.argv[1], timeout=2)' \"$$1\"; }; elif command -v node >/dev/null 2>&1; then get() { node -e 'fetch(process.argv[1], {signal: AbortSignal.timeout(2000)}).then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))' \"$$1\"; }; else exit 1; fi; for u in http://localhost:8000/.well-known/agent-env.json http://localhost:8000/api/health; do get \"$$u\" 2>/dev/null && exit 0; done; exit 1"] + interval: 10s + timeout: 5s + start_period: 30s + retries: 3 + shm_size: 256m + networks: + - env-network + - website-network + + feed-website-backend: + image: feed-be + depends_on: + servicedb: + condition: service_healthy + environment: + - DATABASE_URL=postgresql://agentenv:agentenv@servicedb:5432/agentenv?options=-c%20search_path%3D%22feed%22,public + - SERVICE_NAME=feed + - ENVIRONMENT_NAME=feed + - PORT=8000 + - WEBSITE_SESSION_SECRET=0000000000000000000000000000000000000000000000000000000000000000 + - PYTHONUNBUFFERED=1 + - "AGENTENV_WEBSITE_SETTINGS={\"mode\": \"live\"}" + healthcheck: + test: ["CMD-SHELL", "if command -v curl >/dev/null 2>&1; then get() { curl -sf --max-time 2 -o /dev/null \"$$1\"; }; elif command -v wget >/dev/null 2>&1; then get() { wget -q -T 2 -O /dev/null \"$$1\"; }; elif command -v python3 >/dev/null 2>&1; then get() { python3 -c 'import sys, urllib.request; urllib.request.urlopen(sys.argv[1], timeout=2)' \"$$1\"; }; elif command -v node >/dev/null 2>&1; then get() { node -e 'fetch(process.argv[1], {signal: AbortSignal.timeout(2000)}).then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))' \"$$1\"; }; else exit 1; fi; for u in http://localhost:8000/.well-known/agent-env.json http://localhost:8000/api/health; do get \"$$u\" 2>/dev/null && exit 0; done; exit 1"] + interval: 10s + timeout: 5s + start_period: 30s + retries: 3 + networks: + - env-network + + relay: + image: ecr/relay:1.0.4 + environment: + - RELAY_MODE=remote + ports: + - "10.0.0.5:19768:8000" + restart: unless-stopped + networks: + - env-network + +networks: + env-network: + driver: bridge + website-network: + driver: bridge \ No newline at end of file diff --git a/tst/unit/providers/env_providers/slot_compose_test.py b/tst/unit/providers/env_providers/slot_compose_test.py new file mode 100644 index 000000000..41f7e48e3 --- /dev/null +++ b/tst/unit/providers/env_providers/slot_compose_test.py @@ -0,0 +1,164 @@ +"""A slot's compose file fits its walls, and the default stack's is the file it has always been.""" + +from __future__ import annotations + +import copy +import re +from ipaddress import ip_address +from pathlib import Path + +import pytest +import yaml + +from agent_env.env.gateway.constants import DOOR_ROUTES_ENV, DOOR_TOKEN_ENV +from agent_env.providers.env_providers.slot_compose import ( + DOOR_COMMAND, + DOOR_SERVICE_NAME, + slot_compose, + slot_compose_problems, + slot_resolv_conf, +) +from agent_env.providers.env_providers.stack_layout import DEFAULT_STACK_LAYOUT, StackLayout +from agent_env.providers.sandbox_providers.shared_box_walls import slot_bridges, slot_networks +from tst.unit.providers.env_providers.compose_fixture import render + +GOLDEN = Path(__file__).parent / "golden" / "default_stack_compose.yml" +SLOT = StackLayout.for_slot(3) +TOKEN = "door-token-value" +# A URL's host, as a service's settings name the service they reach: http://gateway:18765, postgres://u:p@servicedb:5432. +_URL_HOST = re.compile(r"[a-z]+://(?:[^@/\s,]*@)?([A-Za-z0-9.-]+):\d+") + + +def test_the_default_stack_renders_byte_for_byte_as_before(): + assert render() == GOLDEN.read_text() + assert render(stack_layout=DEFAULT_STACK_LAYOUT, door_token=None) == GOLDEN.read_text() + + +@pytest.fixture(scope="module") +def slot() -> dict: + return yaml.safe_load(render(stack_layout=SLOT, door_token=TOKEN)) + + +def _networks(service: dict) -> dict[str, str]: + return {network: config["ipv4_address"] for network, config in service["networks"].items()} + + +def _extra_hosts(service: dict) -> dict[str, str]: + return dict(entry.split(":", 1) for entry in service.get("extra_hosts") or []) + + +def _names_used(name: str, service: dict) -> set[str]: + """The hosts a service's settings reach other services by: URL hosts, the gateway's bare internal server names, + the door's upstreams.""" + env = dict(entry.split("=", 1) for entry in service.get("environment") or []) + used = {host for value in env.values() for host in _URL_HOST.findall(value)} + used |= {entry for entry in env.get("INTERNAL_MCP_SERVERS", "").split(",") if entry and "=" not in entry} + used |= {route.split("=", 1)[1].rsplit(":", 1)[0] for route in env.get(DOOR_ROUTES_ENV, "").split(",") if route} + return {host for host in used if "." not in host and host != name} + + +def test_every_service_runs_under_gvisor_with_the_slots_resolvers(slot): + for service in slot["services"].values(): + assert service["runtime"] == "runsc" + assert f"{SLOT.app_dir}/resolv.conf:/etc/resolv.conf:ro" in service["volumes"] + + +def test_the_slots_networks_have_its_subnets_and_bridges_and_no_ipv6(slot): + subnets, bridges = slot_networks(3), slot_bridges(3) + assert slot["networks"] == { + "env-network": {"driver": "bridge", "enable_ipv6": False, + "driver_opts": {"com.docker.network.bridge.name": bridges.env}, + "ipam": {"config": [{"subnet": str(subnets.env)}]}}, + "website-network": {"driver": "bridge", "enable_ipv6": False, + "driver_opts": {"com.docker.network.bridge.name": bridges.website}, + "ipam": {"config": [{"subnet": str(subnets.website)}]}}, + } + + +def test_every_service_has_its_own_fixed_address_in_the_slots_subnets(slot): + subnet = {"env-network": slot_networks(3).env, "website-network": slot_networks(3).website} + seen = [address for service in slot["services"].values() for address in _networks(service).values()] + assert len(seen) == len(set(seen)) + for service in slot["services"].values(): + for network, address in _networks(service).items(): + assert ip_address(address) in subnet[network] and ip_address(address) != subnet[network][1] + + +def test_extra_hosts_name_every_service_a_service_reaches_and_only_on_a_network_they_share(slot): + services = slot["services"] + for name, service in services.items(): + hosts = _extra_hosts(service) + missing = _names_used(name, service) - set(hosts) + assert not missing, f"{name} can't resolve {missing}" + for peer, address in hosts.items(): + if peer == "host.docker.internal": + continue + shared = set(_networks(service)) & set(_networks(services[peer])) + assert address in {_networks(services[peer])[network] for network in shared}, (name, peer) + assert set(_extra_hosts(services["browser"])) == {"gateway", "shop-website-frontend", "blog-website-backend"} + assert "servicedb" not in _extra_hosts(services["browser"]) + + +def test_only_the_door_publishes_and_it_takes_every_port_the_default_stack_published(slot): + default = yaml.safe_load(GOLDEN.read_text())["services"] + published = {name: service["ports"] for name, service in default.items() if "ports" in service} + assert [name for name, service in slot["services"].items() if "ports" in service] == [DOOR_SERVICE_NAME] + door = slot["services"][DOOR_SERVICE_NAME] + expected_ports, expected_routes = [], [] + for name, specs in published.items(): + for spec in specs: + ip, host_port, container_port = spec.split(":") + expected_ports.append(f"{ip}:{host_port}:{host_port}") + expected_routes.append(f"{host_port}={name}:{container_port}") + assert door["ports"] == expected_ports + assert door["command"] == DOOR_COMMAND + assert door["image"] == "agent-gateway" + assert door["environment"] == [f"{DOOR_ROUTES_ENV}={','.join(expected_routes)}", f"{DOOR_TOKEN_ENV}={TOKEN}"] + assert list(door["networks"]) == ["env-network"] + + +def test_the_slots_compose_passes_its_own_wall_check(slot): + assert slot_compose_problems(slot, SLOT) == [] + + +@pytest.mark.parametrize(("change", "problem"), [ + (lambda s: s["gateway"].update(privileged=True), "gateway sets privileged"), + (lambda s: s["gateway"].update(cap_add=["NET_ADMIN"]), "gateway sets cap_add"), + (lambda s: s["gateway"].update(devices=["/dev/kvm"]), "gateway sets devices"), + (lambda s: s["gateway"].update(network_mode="host"), "gateway sets network_mode"), + (lambda s: s["gateway"].update(pid="host"), "gateway sets pid"), + (lambda s: s["gateway"].update(ipc="host"), "gateway sets ipc"), + (lambda s: s["gateway"].update(userns_mode="host"), "gateway sets userns_mode"), + (lambda s: s["gateway"].update(security_opt=["seccomp=unconfined"]), "gateway sets security_opt"), + (lambda s: s["gateway"].update(runtime="runc"), "gateway runs under 'runc'"), + (lambda s: s["gateway"].update(ports=["18765:18765"]), "gateway publishes ports"), + (lambda s: s["gateway"]["volumes"].append("/var/run/docker.sock:/var/run/docker.sock"), "docker socket"), + (lambda s: s["gateway"]["volumes"].append({"type": "bind", "source": "/run/docker.sock", "target": "/s"}), "docker socket"), + (lambda s: s["gateway"]["volumes"].append("/etc:/host-etc:ro"), "bind-mounts /etc"), + (lambda s: s["gateway"]["volumes"].append("../s4:/other"), "bind-mounts ../s4"), + (lambda s: s["gateway"]["volumes"].append("~/x:/x"), "bind-mounts ~/x"), + (lambda s: s["gateway"]["volumes"].append({"type": "bind", "source": "/app", "target": "/a"}), "bind-mounts /app"), +]) +def test_the_wall_check_refuses_whatever_would_reach_past_the_slot(slot, change, problem): + broken = copy.deepcopy(slot) + change(broken["services"]) + assert any(problem in found for found in slot_compose_problems(broken, SLOT)) + + +def test_named_volumes_and_binds_inside_the_slots_dir_pass(slot): + fine = copy.deepcopy(slot) + fine["services"]["gateway"]["volumes"] += ["logs:/var/log", "./data:/data", f"{SLOT.app_dir}/x:/x"] + assert slot_compose_problems(fine, SLOT) == [] + + +def test_a_slot_compose_needs_a_slot_layout_and_a_token(): + with pytest.raises(ValueError, match="for_slot"): + slot_compose(render(), DEFAULT_STACK_LAYOUT, door_image="gw", door_token=TOKEN) + with pytest.raises(ValueError, match="needs a token"): + render(stack_layout=SLOT, door_token=None) + + +def test_a_slot_mounts_the_boxs_ipv4_resolvers(): + assert slot_resolv_conf("search x\nnameserver 172.21.0.1\nnameserver fd00::1\n") == "nameserver 172.21.0.1\n" + with pytest.raises(ValueError): + slot_resolv_conf("nameserver fd00::1\n") diff --git a/tst/unit/providers/env_providers/stack_layout_test.py b/tst/unit/providers/env_providers/stack_layout_test.py index 37122fc10..544cff003 100644 --- a/tst/unit/providers/env_providers/stack_layout_test.py +++ b/tst/unit/providers/env_providers/stack_layout_test.py @@ -6,10 +6,12 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest +import yaml from agent_env.env import snapshot_store from agent_env.env.envs.service_db import DB_MCP_PORT, DB_WEB_PORT, ServiceDBConfig from agent_env.env.gateway import AGENT_ENV_GATEWAY_MCP_PORT +from agent_env.env.gateway.constants import SLOT_TOKEN_HEADER from agent_env.providers.env_providers.env_gateway_provider import ( TEARDOWN_RETRIES, EnvironmentGatewayProvider, @@ -17,6 +19,7 @@ SidecarConfig, tear_down_slot, ) +from agent_env.providers.env_providers.slot_compose import DOOR_SERVICE_NAME from agent_env.providers.env_providers.stack_layout import DEFAULT_STACK_LAYOUT, StackLayout SIDECAR_HOST_PORT = 9100 @@ -57,6 +60,8 @@ async def exec_with_output(self, *args: str) -> tuple[int, str, str]: self.calls.append(("exec", args)) if args[0] == "curl": return 0, "200", "" + if args == ("cat", "/etc/resolv.conf"): + return 0, "nameserver 172.21.0.1\nnameserver fd00::1\n", "" if args == ("sudo", "docker", "ps"): return 0, "\n".join(f"{p or 'app'}-gateway-1" for p in self.running), "" if "--status" in args: @@ -148,6 +153,19 @@ async def test_default_deploy_runs_todays_commands_on_todays_paths_and_ports(): assert result.gateway_url == f"https://tunnel-{AGENT_ENV_GATEWAY_MCP_PORT}" assert result.db_web_url == f"https://tunnel-{DB_WEB_PORT}/" assert result.db_mcp_url == f"https://tunnel-{DB_MCP_PORT}/mcp" + assert result.door_token is None + assert not any("-H" in c[1] for c in vm.calls if c[0] == "exec" and c[1][0] == "curl") + assert ("cat", "/etc/resolv.conf") not in execs + + +@pytest.mark.asyncio +async def test_every_slot_deploy_draws_a_new_door_token(): + tokens = [] + for _ in range(2): + _, result, _ = await _deploy(stack_layout=StackLayout.for_slot(1), existing_sandbox=_walled_vm({None, "s1"})) + tokens.append(result.door_token) + assert all(len(token) >= 43 for token in tokens) + assert tokens[0] != tokens[1] SLOT_1_PORTS = [p + 2000 for p in (AGENT_ENV_GATEWAY_MCP_PORT, DB_WEB_PORT, DB_MCP_PORT, SIDECAR_HOST_PORT)] @@ -165,14 +183,21 @@ async def test_slot_deploy_uses_its_own_dir_project_and_host_ports(): scripts = _scripts(vm) assert scripts[0] == "mkdir -p /app/s1" - assert _written(scripts[1])[0] == "/app/s1/init-schemas.sql" - path, compose = _written(scripts[2]) + assert _written(scripts[1]) == ("/app/s1/resolv.conf", "nameserver 172.21.0.1") + assert _written(scripts[2])[0] == "/app/s1/init-schemas.sql" + path, compose = _written(scripts[3]) assert path == "/app/s1/docker-compose.yml" - assert f'"{AGENT_ENV_GATEWAY_MCP_PORT + 2000}:{AGENT_ENV_GATEWAY_MCP_PORT}"' in compose - assert f'"{DB_WEB_PORT + 2000}:{DB_WEB_PORT}"' in compose - assert f'"{SIDECAR_HOST_PORT + 2000}:80"' in compose + services = yaml.safe_load(compose)["services"] + assert [name for name, service in services.items() if "ports" in service] == [DOOR_SERVICE_NAME] + shifted = [p + 2000 for p in (DB_WEB_PORT, DB_MCP_PORT, AGENT_ENV_GATEWAY_MCP_PORT, SIDECAR_HOST_PORT)] + assert services[DOOR_SERVICE_NAME]["ports"] == [f"{p}:{p}" for p in shifted] assert f"MCP_PORT={AGENT_ENV_GATEWAY_MCP_PORT}" in compose - assert scripts[3:] == ["cd /app/s1 && docker compose -p s1 up -d"] + assert scripts[4:] == ["cd /app/s1 && docker compose -p s1 up -d"] + door = {SLOT_TOKEN_HEADER: result.door_token} + curl = next(c[1] for c in vm.calls if c[0] == "exec" and c[1][0] == "curl") + assert curl[curl.index("-H") + 1] == f"{SLOT_TOKEN_HEADER}: {result.door_token}" + assert gp._wait_for_tunnel.await_args.kwargs["headers"] == door + assert gp._refuse_tool_name_clashes.await_args.kwargs["headers"] == door compose_ps = ("sudo", "docker", "compose", "-f", "/app/s1/docker-compose.yml", "-p", "s1", "ps") assert (*compose_ps, "--status", "running", "-q", "gateway") in _execs(vm) assert (*compose_ps, "-a", "-q", "gateway") in _execs(vm) diff --git a/tst/unit/providers/sandbox_providers/shared_box_walls_test.py b/tst/unit/providers/sandbox_providers/shared_box_walls_test.py index 4a6013ac2..8e1fc0666 100644 --- a/tst/unit/providers/sandbox_providers/shared_box_walls_test.py +++ b/tst/unit/providers/sandbox_providers/shared_box_walls_test.py @@ -12,9 +12,11 @@ import pytest from agent_env.providers.sandbox_providers.shared_box_walls import ( + SLOT_BRIDGE_PREFIX, SLOT_COUNT, SLOT_RANGE, apply_walls_firewall, + slot_bridges, slot_networks, upstream_resolvers, walls_firewall_script, @@ -265,3 +267,12 @@ async def test_applying_the_walls_raises_and_runs_nothing_when_resolv_conf_cant_ await apply_walls_firewall(box) box.exec_script.assert_not_called() + + +def test_every_slot_network_has_its_own_bridge_name_that_linux_accepts(): + names = [name for index in range(SLOT_COUNT) for name in slot_bridges(index)] + assert len(set(names)) == len(names) == 2 * SLOT_COUNT + assert all(name.startswith(SLOT_BRIDGE_PREFIX) and len(name) <= 15 for name in names) + assert slot_bridges(7) == ("aes7env", "aes7web") + with pytest.raises(ValueError): + slot_bridges(SLOT_COUNT) diff --git a/tst/unit/task_step/local_container_urls_test.py b/tst/unit/task_step/local_container_urls_test.py index f054a3631..757725d83 100644 --- a/tst/unit/task_step/local_container_urls_test.py +++ b/tst/unit/task_step/local_container_urls_test.py @@ -350,4 +350,4 @@ async def install_cli(deployed, cli_artifact, gateway_url, **placed): await LoadArtifactTaskStep(id="cli", version=None, env_id="env-x", artifact_id=cli.id, artifact_version=cli.version, agent_name="solver").execute(context) - assert installed == [(expected, {"on_host": True} if on_host else {})] + assert installed == [(expected, {"on_host": True, "slot_token": None} if on_host else {"slot_token": None})] diff --git a/tst/unit/task_step/test_apply_server_config.py b/tst/unit/task_step/test_apply_server_config.py index 9df2a67ec..304b85118 100644 --- a/tst/unit/task_step/test_apply_server_config.py +++ b/tst/unit/task_step/test_apply_server_config.py @@ -600,7 +600,7 @@ def _fake_multi_env(mcp_names, website_names): class _KeyedGateway(_MockGateway): """A gateway serving each card at /svc//.well-known/agent-env.json, where a website's key is its bare name.""" - async def get(self, url, *, timeout=None, params=None): + async def get(self, url, *, timeout=None, params=None, headers=None): self.get_calls.append(url) for key, card in self.cards.items(): if url.endswith(f"/svc/{key}/.well-known/agent-env.json"): diff --git a/tst/unit/task_step/test_deploy_agent_mcp_alias.py b/tst/unit/task_step/test_deploy_agent_mcp_alias.py index 89fa22ba6..3c1bad79f 100644 --- a/tst/unit/task_step/test_deploy_agent_mcp_alias.py +++ b/tst/unit/task_step/test_deploy_agent_mcp_alias.py @@ -9,6 +9,7 @@ from agent_env.a2a_agent.a2a_agent import A2AAgent from agent_env.env.env import DeployedEnv, DeployedGatewayEnv +from agent_env.env.gateway.constants import SLOT_TOKEN_HEADER from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_steps.deploy_agent import DeployAgentTaskStep, _mcp_add_body @@ -58,6 +59,15 @@ async def test_a_record_without_a_stored_card_relays_no_name_and_warns(monkeypat assert "Env crm has no env card name; the agent will pick its own MCP alias" in caplog.messages +@pytest.mark.asyncio +@pytest.mark.parametrize(("door_token", "headers"), [(None, None), ("door-tok", {SLOT_TOKEN_HEADER: "door-tok"})]) +async def test_a_slots_mcp_registration_carries_its_door_header_and_the_default_stacks_none(monkeypatch, door_token, headers): + deployed = _deployed_env({"name": "env5647"}) + deployed.door_token = door_token + [request] = await _deploy_agent_against(monkeypatch, deployed) + assert json.loads(request.content).get("headers") == headers + + _MCP_URL = "https://gw.example/mcp" _LOGGER = "agent_env.task_step.task_steps.deploy_agent" diff --git a/tst/unit/task_step/test_snapshot_agent_state.py b/tst/unit/task_step/test_snapshot_agent_state.py index 551f1cd26..f1db3c80f 100644 --- a/tst/unit/task_step/test_snapshot_agent_state.py +++ b/tst/unit/task_step/test_snapshot_agent_state.py @@ -102,7 +102,7 @@ def get_object_store_at(self, object_url): monkeypatch.setattr(config_mod, "get_config", lambda: _Cfg()) - async def _supports_v1(_base): + async def _supports_v1(_base, **_): return False monkeypatch.setattr(protocol_v1, "supports_v1", _supports_v1) @@ -136,7 +136,7 @@ def put(self, *a, **kw): monkeypatch.setattr(artifact_mod, "EnvironmentUniverseArtifact", type("U", (), {"get": staticmethod(lambda _id: _StubUniverse())})) monkeypatch.setattr(config_mod, "get_config", lambda: type("Cfg", (), {"get_object_store_at": lambda self, object_url: store})()) - async def _no_v1(_base): + async def _no_v1(_base, **_): return False async def _export_state(_gw, name): @@ -162,7 +162,7 @@ async def test_capture_reads_child_envs_on_the_stored_card_and_takes_legacy_for_ monkeypatch.setattr(artifact_mod, "EnvironmentUniverseArtifact", type("U", (), {"get": staticmethod(lambda _id: _StubUniverse())})) monkeypatch.setattr(config_mod, "get_config", lambda: type("Cfg", (), {"get_object_store_at": lambda self, object_url: store})()) - async def _no_probe(_base): + async def _no_probe(_base, **_): raise AssertionError("a stored card means no live probe") got, legacy = [], [] diff --git a/tst/unit/task_step/test_snapshot_env.py b/tst/unit/task_step/test_snapshot_env.py index cf75fb7ca..ea7c74f4b 100644 --- a/tst/unit/task_step/test_snapshot_env.py +++ b/tst/unit/task_step/test_snapshot_env.py @@ -742,13 +742,13 @@ async def test_export_service_to_file_materializes_filepart_zip(monkeypatch, tmp } ) - async def fake_supports_v1(base_url): + async def fake_supports_v1(base_url, **_): return True async def fake_get_data(base_url, timeout=None, headers=None): return GetDataResponse(parts=[part]) - async def fake_get_card(base_url, timeout=10): + async def fake_get_card(base_url, timeout=10, **_): return {} # no s3-credentials extension -> _push_s3_credentials no-ops from agentenv_protocol import client as protocol_v1 @@ -788,13 +788,13 @@ async def test_export_service_to_file_resolves_relative_uri_and_streams( file={"uri": uri, "name": "gdrive.zip", "mimeType": "application/zip"} ) - async def fake_supports_v1(base_url): + async def fake_supports_v1(base_url, **_): return True async def fake_get_data(base_url, timeout=None, headers=None): return GetDataResponse(parts=[part]) - async def fake_get_card(base_url, timeout=10): + async def fake_get_card(base_url, timeout=10, **_): return {} # no s3-credentials extension -> _push_s3_credentials no-ops monkeypatch.setattr(protocol_v1, "supports_v1", fake_supports_v1) @@ -846,13 +846,13 @@ def stream(self, method, url, timeout=None, headers=None): def _serve_filepart_uri(monkeypatch, uri): part = FilePart(file={"uri": uri, "name": "gdrive.zip", "mimeType": "application/zip"}) - async def fake_supports_v1(base_url): + async def fake_supports_v1(base_url, **_): return True async def fake_get_data(base_url, timeout=None, headers=None): return GetDataResponse(parts=[part]) - async def fake_get_card(base_url, timeout=10): + async def fake_get_card(base_url, timeout=10, **_): return {} def no_http(*a, **k): @@ -981,13 +981,13 @@ async def test_export_service_to_file_filepart_without_bytes_or_uri_raises_value part = FilePart(file={"uri": "http://x", "name": "slack.zip", "mimeType": "application/zip"}) part.file.uri = None - async def fake_supports_v1(base_url): + async def fake_supports_v1(base_url, **_): return True async def fake_get_data(base_url, timeout=None, headers=None): return GetDataResponse(parts=[part]) - async def fake_get_card(base_url, timeout=10): + async def fake_get_card(base_url, timeout=10, **_): return {} # no s3-credentials extension -> _push_s3_credentials no-ops monkeypatch.setattr(protocol_v1, "supports_v1", fake_supports_v1) diff --git a/tst/unit/task_step/test_verify_spec_conformance.py b/tst/unit/task_step/test_verify_spec_conformance.py index 40a2ebedf..8f6492e5c 100644 --- a/tst/unit/task_step/test_verify_spec_conformance.py +++ b/tst/unit/task_step/test_verify_spec_conformance.py @@ -14,7 +14,7 @@ import pytest from agent_env.env.env import DeployedGatewayEnv -from agent_env.env.gateway.constants import WELL_KNOWN_PATH +from agent_env.env.gateway.constants import SLOT_TOKEN_HEADER, WELL_KNOWN_PATH from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_steps.mcp_env_validator.verify_spec_conformance import ( VerifySpecConformanceTaskStep, @@ -613,17 +613,27 @@ def test_a_record_without_a_stored_card_reads_the_servers_card_first(self): sent, _ = self._run("https://gw", None) assert sent == [("GET", f"https://gw/svc/mcp-items{WELL_KNOWN_PATH}"), ("GET", "https://gw/svc/mcp-items/openapi.yaml")] + @pytest.mark.parametrize(("door_token", "door"), [(None, None), ("door-tok", "door-tok")]) + def test_a_slots_spec_fetch_carries_its_door_header_and_the_default_stacks_none(self, door_token, door): + card = {"name": "gw", "url": "/agentenv", "children_environments": [{"name": "items", "url": "/svc/mcp-items/agentenv"}]} + headers = [] + self._run("https://gw", card, door_token=door_token, headers=headers) + assert [(h.get(SLOT_TOKEN_HEADER), h.get("authorization")) for h in headers] == [(door, None)] + @staticmethod - def _run(gateway_url, card): + def _run(gateway_url, card, *, door_token=None, headers=None): """Execute against a spec endpoint that 404s, so the step records a skip before any MCP call.""" sent, real = [], httpx.AsyncClient def handle(request): sent.append((request.method, str(request.url))) + if headers is not None: + headers.append(request.headers) return httpx.Response(200, json={"name": "items"}) if request.url.path.endswith(WELL_KNOWN_PATH) else httpx.Response(404) record = DeployedGatewayEnv(env_id="e1", env_version=1, gateway_url=gateway_url, mcp_url="", db_web_url=None, sandbox_id="sb", - environment_card_url=f"{gateway_url}{WELL_KNOWN_PATH}", environment_card=card) + environment_card_url=f"{gateway_url}{WELL_KNOWN_PATH}", environment_card=card, + control_token="ctl", door_token=door_token) env = MagicMock(environment_name="items") with patch.object(httpx, "AsyncClient", lambda *a, **k: real(transport=httpx.MockTransport(handle))), \ patch("agent_env.env.env.Env.get", return_value=env): From ecf36a81c9b9704f649476dd0d0cea401a6dbf5d Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Sat, 21 Nov 2026 00:27:49 -0500 Subject: [PATCH 06/15] fix(sandbox-providers): the walls apply atomically, match slots by bridge, wall off IPv6, and the tag guard sees every write Re-applying the walls no longer flushes and refills chains one command at a time behind a temporary guard. One iptables-restore --noflush transaction empties and fills AGENTENV-WALLS-FWD and AGENTENV-WALLS-IN, so a failure keeps the old rules and the script exits non-zero; the jumps into DOCKER-USER and INPUT are then added once with -C || -I. Rules match the bridge a packet came in on (-i aes+), not its source address, which a slot could spoof. A slot may reach only its own two bridges, its upstream resolvers on port 53 and non-private addresses; INPUT from a slot is dropped unless established. ip6tables gets the same atomic restore and drops all IPv6 forwarded or input from aes+, hooked into FORWARD and INPUT; a box without ip6tables fails the script. The walls-tag guard now also fails on WALLS_TAG as an attribute, any .set_tags reference (sync or not), getattr or setattr by string, a _walls assignment other than __init__'s passthrough, and walls= or unnamed walls passed to ModalVmSandbox. Each is proved by a planted snippet. Co-Authored-By: Claude Opus 5.5 --- .../sandbox_providers/shared_box_walls.py | 58 ++-- .../modal_shared_box_test.py | 121 +++++-- .../shared_box_walls_test.py | 307 ++++++++++++++---- 3 files changed, 371 insertions(+), 115 deletions(-) diff --git a/src/agent_env/providers/sandbox_providers/shared_box_walls.py b/src/agent_env/providers/sandbox_providers/shared_box_walls.py index 67b4b8f19..f8e7c1b96 100644 --- a/src/agent_env/providers/sandbox_providers/shared_box_walls.py +++ b/src/agent_env/providers/sandbox_providers/shared_box_walls.py @@ -1,10 +1,12 @@ """The walls between the slots of a shared box, the networks each slot owns and the firewall that keeps them apart. Slot ``n`` of a box owns the /23 ``10.250.2n.0/23``: ``10.250.2n.0/24`` for its env's network and ``10.250.2n+1.0/24`` -for its website's. The firewall is one root shell script for the whole box, every slot at once, applied once dockerd is -up and its ``DOCKER-USER`` chain exists. It only drops: what it lets through still meets Docker's own rules, so it never -opens a path Docker would close. Forwarded traffic from a slot may reach its own /23, the box's upstream resolvers on -port 53, and anything outside the private ranges; traffic from a slot to the box itself is dropped. +for its website's, on the bridges ``aesenv`` and ``aesweb``. The firewall is one root shell script for the whole +box, every slot at once, applied once dockerd is up and its ``DOCKER-USER`` chain exists. It matches slot traffic by +the bridge it came in on, which a container can't spoof as it can a source address. It only drops: what it lets +through still meets Docker's own rules, so it never opens a path Docker would close. Forwarded traffic from a slot may +reach its own two bridges, the box's upstream resolvers on port 53, and anything outside the private ranges; traffic +from a slot to the box itself, and any IPv6 from a slot, is dropped. """ from __future__ import annotations @@ -24,6 +26,10 @@ ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", "100.64.0.0/10")) FORWARD_CHAIN, INPUT_CHAIN = "AGENTENV-WALLS-FWD", "AGENTENV-WALLS-IN" _ESTABLISHED = "-m conntrack --ctstate ESTABLISHED,RELATED" +# Where each walls chain is jumped to. The box's dockerd isn't set up for IPv6, so it may make no ip6tables +# DOCKER-USER; the IPv6 walls hook into FORWARD itself. +_HOOKS = (("iptables", "DOCKER-USER", FORWARD_CHAIN), ("iptables", "INPUT", INPUT_CHAIN), + ("ip6tables", "FORWARD", FORWARD_CHAIN), ("ip6tables", "INPUT", INPUT_CHAIN)) class SlotNetworks(NamedTuple): @@ -72,29 +78,39 @@ def upstream_resolvers(resolv_conf: str) -> tuple[IPv4Address, ...]: return tuple(resolvers) +def _restore_input(chains: dict[str, list[str]]) -> str: + """``iptables-restore --noflush`` input that empties ``chains``, creating any that are missing, and fills them with + their rules, in one transaction: it changes every chain or, if any line fails, none.""" + lines = ["*filter", *(f":{chain} - [0:0]" for chain in chains)] + for chain, rules in chains.items(): + lines.append(f"-F {chain}") + lines += [f"-A {chain} {rule}" for rule in rules] + lines.append("COMMIT") + return "\n".join(lines) + "\n" + + def walls_firewall_script(resolvers: Sequence[IPv4Address]) -> str: """A root shell script that sets the box's firewall to the walls for every slot, the same rules however often it - runs. While it refills the chains, a guard at the top of ``DOCKER-USER`` and ``INPUT`` drops all slot traffic, so - a run that fails part way leaves the walls closed, not open.""" + runs. Each of iptables and ip6tables refills the walls' chains in one transaction, so a run that fails leaves the + walls as they were, then each chain is hooked in once. A box without ip6tables fails the script.""" if not resolvers: raise ValueError("the walls need at least one upstream resolver") - slots = str(SLOT_RANGE) + from_slot = f"-i {SLOT_BRIDGE_PREFIX}+" forward = [f"{_ESTABLISHED} -j RETURN"] - forward += [f"-s {n.slot} -d {n.slot} -j RETURN" for n in map(slot_networks, range(SLOT_COUNT))] - forward.append(f"-s {slots} -d {slots} -j DROP") - forward += [f"-s {slots} -d {r}/32 -p {proto} --dport 53 -j RETURN" for r in resolvers for proto in ("udp", "tcp")] - forward += [f"-s {slots} -d {n} -j DROP" for n in _PRIVATE_RANGES] - incoming = [f"{_ESTABLISHED} -j RETURN", f"-s {slots} -j DROP"] - guard = f"-s {slots} -j DROP" + for bridges in map(slot_bridges, range(SLOT_COUNT)): + forward += [f"-i {a} -o {b} -j RETURN" for a in bridges for b in bridges] + forward.append(f"{from_slot} -o {SLOT_BRIDGE_PREFIX}+ -j DROP") + forward += [f"{from_slot} -d {r}/32 -p {proto} --dport 53 -j RETURN" for r in resolvers for proto in ("udp", "tcp")] + forward += [f"{from_slot} -d {n} -j DROP" for n in _PRIVATE_RANGES] + tables = { + "iptables": {FORWARD_CHAIN: forward, INPUT_CHAIN: [f"{_ESTABLISHED} -j RETURN", f"{from_slot} -j DROP"]}, + "ip6tables": {FORWARD_CHAIN: [f"{from_slot} -j DROP"], INPUT_CHAIN: [f"{from_slot} -j DROP"]}, + } lines = ["set -eu"] - for parent in ("DOCKER-USER", "INPUT"): - lines.append(f"iptables -C {parent} {guard} 2>/dev/null || iptables -I {parent} 1 {guard}") - for chain, parent, rules in ((FORWARD_CHAIN, "DOCKER-USER", forward), (INPUT_CHAIN, "INPUT", incoming)): - lines.append(f"iptables -N {chain} 2>/dev/null || iptables -F {chain}") - lines += [f"iptables -A {chain} {rule}" for rule in rules] - lines.append(f"iptables -C {parent} -j {chain} 2>/dev/null || iptables -I {parent} 1 -j {chain}") - for parent in ("DOCKER-USER", "INPUT"): - lines.append(f"iptables -D {parent} {guard}") + for tool, chains in tables.items(): + lines += [f"{tool}-restore -w --noflush <<'WALLS'", _restore_input(chains) + "WALLS"] + for tool, parent, chain in _HOOKS: + lines.append(f"{tool} -w -C {parent} -j {chain} 2>/dev/null || {tool} -w -I {parent} 1 -j {chain}") return "\n".join(lines) + "\n" diff --git a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py index 2e67a700a..58294543b 100644 --- a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py +++ b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py @@ -462,44 +462,105 @@ async def test_marking_the_walls_verified_writes_nothing_unless_the_sandbox_is_t _WALLS_WRITER = "_mark_walls_verified" -#: Functions that may name WALLS_TAG without writing it: its refusal in attribution and the reattach that reads it. +#: Functions that may name WALLS_TAG without writing it: its refusal in attribution and the reattach that reads it, +#: which alone passes what it read to a handle's ``walls``. _WALLS_READERS = {"_attribution_tags", "get_shared_box"} +#: Names whose spelling as a string would reach the walls tag or the tags around getattr and setattr. +_WALLS_NAMES = {"WALLS_TAG", "set_tags", "_walls"} + + +def _walls_tag_strays(name: str, text: str) -> list[str]: + """Each place in the module ``text`` that writes the walls tag, or a handle's record of it, outside its one writer. + + WALLS_TAG, bare or as an attribute, is named only in its definition, by the functions that read or refuse it, and + by the writer, the only one to put it in a dict or assign it. ``set_tags`` is reached, called or not, only on a + Modal App, named ``app``, or by the writer. A handle's ``_walls`` is assigned only by the writer, or from the + ``walls`` argument in ``__init__``, and ``walls=`` is passed only by the readers. None of these names is spelled + as a string, as for getattr, except by the writer.""" + tree = ast.parse(text) + owner = {} + for function in (n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))): + for node in ast.walk(function): + owner.setdefault(id(node), function.name) + writes, passthrough = set(), set() + for node in ast.walk(tree): + if isinstance(node, ast.Dict): + writes |= {id(k) for k in node.keys if k is not None} + if isinstance(node, ast.Subscript) and isinstance(node.ctx, ast.Store): + writes.add(id(node.slice)) + if isinstance(node, ast.Assign) and owner.get(id(node)) == "__init__" \ + and isinstance(node.value, ast.Name) and node.value.id == "walls": + passthrough |= {id(t) for t in node.targets} + stray = [] + for node in ast.walk(tree): + function = owner.get(id(node)) + if function == _WALLS_WRITER: + continue + where = f"{name}:{getattr(node, 'lineno', '?')} in {function or 'module scope'}" + if (isinstance(node, ast.Name) and node.id == "WALLS_TAG") or \ + (isinstance(node, ast.Attribute) and node.attr == "WALLS_TAG"): + if function is None and isinstance(node.ctx, ast.Store): + continue + if function not in _WALLS_READERS or id(node) in writes: + stray.append(f"{where} names WALLS_TAG") + if isinstance(node, ast.Attribute) and node.attr == "set_tags" \ + and not (isinstance(node.value, ast.Name) and node.value.id == "app"): + stray.append(f"{where} sets tags") + if isinstance(node, ast.Attribute) and node.attr == "_walls" and not isinstance(node.ctx, ast.Load) \ + and id(node) not in passthrough: + stray.append(f"{where} assigns _walls") + if isinstance(node, ast.keyword) and node.arg == "walls" and function not in _WALLS_READERS: + stray.append(f"{where} passes walls=") + callee = getattr(node, "func", None) + if isinstance(node, ast.Call) and getattr(callee, "id", getattr(callee, "attr", None)) == "ModalVmSandbox" \ + and (len(node.args) > 4 or any(k.arg is None for k in node.keywords)): + stray.append(f"{where} may pass walls to ModalVmSandbox unnamed") + if isinstance(node, ast.Constant) and node.value in _WALLS_NAMES: + stray.append(f"{where} spells {node.value!r}") + return stray def test_only_the_walls_writer_writes_the_walls_tag_or_sets_a_sandboxs_tags(): - """WALLS_TAG is named only in its definition, in imports, by the functions that read or refuse it, and by its one - writer, the only one to put it in a dict or assign it. Its value is spelled nowhere else. ``set_tags`` is called - only on a Modal App, named ``app``, or by the writer.""" package = Path(modal_sandbox.__file__).parents[2] stray = [] for source in package.rglob("*.py"): text = source.read_text() if f'"{WALLS_TAG}"' in text and source != Path(modal_sandbox.__file__): stray.append(f"{source.name} spells the walls tag's value") - tree = ast.parse(text) - owner = {} - for function in (n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))): - for node in ast.walk(function): - owner.setdefault(id(node), function.name) - writes = set() - for node in ast.walk(tree): - if isinstance(node, ast.Dict): - writes |= {id(k) for k in node.keys if k is not None} - if isinstance(node, ast.Subscript) and isinstance(node.ctx, ast.Store): - writes.add(id(node.slice)) - for node in ast.walk(tree): - where = f"{source.name}:{getattr(node, 'lineno', '?')} in {owner.get(id(node), 'module scope')}" - if isinstance(node, ast.Name) and node.id == "WALLS_TAG": - function = owner.get(id(node)) - if function is None and isinstance(node.ctx, ast.Store): - continue - if function == _WALLS_WRITER or (function in _WALLS_READERS and id(node) not in writes): - continue - stray.append(f"{where} names WALLS_TAG") - if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "aio" \ - and isinstance(node.func.value, ast.Attribute) and node.func.value.attr == "set_tags": - receiver = node.func.value.value - if owner.get(id(node)) == _WALLS_WRITER or (isinstance(receiver, ast.Name) and receiver.id == "app"): - continue - stray.append(f"{where} sets tags") + stray += _walls_tag_strays(source.name, text) assert stray == [] + + +_PLANTED_WALLS_WRITES = { + "tag in a dict, async set_tags": ("def f(sb):\n sb.set_tags.aio({WALLS_TAG: WALLS_VERSION})", "names WALLS_TAG"), + "sync set_tags": ("def f(sb, tags):\n sb.set_tags(tags)", "sets tags"), + "getattr set_tags": ("def f(sb, tags):\n getattr(sb, 'set_tags').aio(tags)", "spells 'set_tags'"), + "set_tags held for later": ("def f(sb):\n write = sb.set_tags\n return write", "sets tags"), + "WALLS_TAG as an attribute": ("def f(m, tags):\n tags[m.WALLS_TAG] = 'walls-v1'", "names WALLS_TAG"), + "reader writes the tag": ("def get_shared_box(m, tags):\n tags[m.WALLS_TAG] = 'v'", "names WALLS_TAG"), + "getattr WALLS_TAG": ("def f(m):\n return getattr(m, 'WALLS_TAG')", "spells 'WALLS_TAG'"), + "constructor walls=": ("def f(sb):\n return ModalVmSandbox(sb, {}, walls=WALLS_VERSION)", "passes walls="), + "constructor positional": ("def f(sb):\n return ModalVmSandbox(sb, {}, None, 'b', WALLS_VERSION)", "unnamed"), + "constructor **kwargs": ("def f(sb, kw):\n return ModalVmSandbox(sb, {}, **kw)", "unnamed"), + "_walls assigned": ("def f(box):\n box._walls = WALLS_VERSION", "assigns _walls"), + "_walls set in __init__ to a constant": ("def __init__(self):\n self._walls = WALLS_VERSION", "assigns _walls"), + "setattr _walls": ("def f(box):\n setattr(box, '_walls', WALLS_VERSION)", "spells '_walls'"), +} + + +@pytest.mark.parametrize("snippet, reason", _PLANTED_WALLS_WRITES.values(), ids=_PLANTED_WALLS_WRITES.keys()) +def test_the_walls_guard_catches_each_way_to_write_the_walls_outside_its_writer(snippet, reason): + assert any(reason in stray for stray in _walls_tag_strays("planted.py", snippet)) + + +def test_the_walls_guard_lets_the_writer_readers_and_handle_do_their_part(): + clean = ( + "WALLS_TAG = 'x'\n" + "def _mark_walls_verified(box, tags):\n" + " box._sb.set_tags.aio({**tags, WALLS_TAG: WALLS_VERSION})\n box._walls = WALLS_VERSION\n" + "def get_shared_box(sb, tags):\n return ModalVmSandbox(sb, {}, walls=tags.get(WALLS_TAG))\n" + "def _attribution_tags(key):\n return key == WALLS_TAG\n" + "def __init__(self, walls):\n self._walls = walls\n" + "def f(app, tags):\n app.set_tags.aio(tags)\n" + ) + assert _walls_tag_strays("clean.py", clean) == [] diff --git a/tst/unit/providers/sandbox_providers/shared_box_walls_test.py b/tst/unit/providers/sandbox_providers/shared_box_walls_test.py index 8e1fc0666..df163b7f8 100644 --- a/tst/unit/providers/sandbox_providers/shared_box_walls_test.py +++ b/tst/unit/providers/sandbox_providers/shared_box_walls_test.py @@ -1,10 +1,14 @@ """The walls between a shared box's slots: the networks each slot owns, the resolvers read from the box, and the -firewall script, run here against a small model of iptables that decides which packets the walls let through.""" +firewall script, run here against a small model of iptables and ip6tables that decides which packets the walls let +through, and once under real bash.""" from __future__ import annotations +import copy import itertools import shlex +import shutil +import subprocess from dataclasses import dataclass from ipaddress import IPv4Address, IPv4Network, ip_address, ip_network from unittest.mock import AsyncMock, MagicMock @@ -24,6 +28,7 @@ MODAL_RESOLV_CONF = "nameserver 172.21.0.1\nnameserver 1.1.1.1\nnameserver 8.8.8.8\n" RESOLVERS = upstream_resolvers(MODAL_RESOLV_CONF) +TOOLS = {"iptables": 4, "ip6tables": 6} class IptablesFailed(Exception): @@ -31,49 +36,83 @@ class IptablesFailed(Exception): class FakeIptables: - """The filter table as the script leaves it: chains of rules, run line by line as ``bash -e`` would. ``fail_on`` - makes the one command holding that text fail, as a broken iptables would.""" + """The filter tables of iptables and ip6tables as the script leaves them, the script run line by line as + ``bash -e`` would, each restore all or nothing. ``fail_on`` makes the one command or restore line holding that text + fail, and ``missing`` names tools the box lacks. ``calls`` is every command run, in order.""" - def __init__(self, *, docker_user: bool = True, fail_on: str | None = None): - self.chains: dict[str, list[tuple[str, ...]]] = {"INPUT": [], "FORWARD": []} + def __init__(self, *, docker_user: bool = True, fail_on: str | None = None, missing: tuple[str, ...] = ()): + self.tables: dict[int, dict[str, list[tuple[str, ...]]]] = { + family: {"INPUT": [], "FORWARD": []} for family in TOOLS.values()} if docker_user: - self.chains["DOCKER-USER"] = [("-j", "RETURN")] - self.chains["FORWARD"].append(("-j", "DOCKER-USER")) - self.fail_on = fail_on + self.tables[4]["DOCKER-USER"] = [("-j", "RETURN")] + self.tables[4]["FORWARD"].append(("-j", "DOCKER-USER")) + self.fail_on, self.missing = fail_on, missing + self.calls: list[str] = [] + + @property + def chains(self) -> dict[str, list[tuple[str, ...]]]: + return self.tables[4] def run(self, script: str) -> None: - for line in script.splitlines(): + lines = iter(script.splitlines()) + for line in lines: if line == "set -eu": continue - if not any(self._command(part.replace("2>/dev/null", "")) for part in line.split(" || ")): + if "<<'WALLS'" in line: + body = list(itertools.takewhile(lambda body_line: body_line != "WALLS", lines)) + ok = self._restore(line.split("<<")[0].strip(), body) + else: + ok = any(self._command(part.replace("2>/dev/null", "")) for part in line.split(" || ")) + if not ok: raise IptablesFailed(line) - def _command(self, command: str) -> bool: + def _tool(self, command: str) -> tuple[list[str], dict[str, list[tuple[str, ...]]]] | None: + self.calls.append(command.strip()) argv = shlex.split(command) - assert argv[0] == "iptables" - if self.fail_on and self.fail_on in command: + tool = argv[0].removesuffix("-restore") + assert tool in TOOLS and "-w" in argv + if argv[0] in self.missing or (self.fail_on and self.fail_on in command): + return None + return [a for a in argv[1:] if a != "-w"], self.tables[TOOLS[tool]] + + def _restore(self, command: str, body: list[str]) -> bool: + found = self._tool(command) + if found is None: return False - op, chain, rest = argv[1], argv[2], tuple(argv[3:]) - if op == "-N": - if chain in self.chains: + args, table = found + assert args == ["--noflush"] and body[0] == "*filter" and body[-1] == "COMMIT" + staged = copy.deepcopy(table) + for line in body[1:-1]: + if self.fail_on and self.fail_on in line: + return False + if line.startswith(":"): + staged.setdefault(line[1:].split()[0], []).clear() + continue + op, chain, *rule = shlex.split(line) + if chain not in staged: return False - self.chains[chain] = [] - return True - if chain not in self.chains: + if op == "-F": + staged[chain].clear() + elif op == "-A": + staged[chain].append(tuple(rule)) + else: + raise AssertionError(f"unexpected restore line {line!r}") + table.clear() + table.update(staged) + return True + + def _command(self, command: str) -> bool: + found = self._tool(command) + if found is None: + return False + (op, chain, *rest), table = found + if chain not in table: return False - rules = self.chains[chain] - if op == "-F": - rules.clear() - elif op == "-A": - rules.append(rest) - elif op == "-I": + rules, rest = table[chain], tuple(rest) + if op == "-I": rules.insert(int(rest[0]) - 1, rest[1:]) elif op == "-C": return rest in rules - elif op == "-D": - if rest not in rules: - return False - rules.remove(rest) else: raise AssertionError(f"unexpected iptables {op}") return True @@ -84,7 +123,7 @@ def verdict(self, packet: Packet, chain: str) -> str: return "DROP" if self._walk(packet, chain) == "DROP" else "ACCEPT" def _walk(self, packet: Packet, chain: str) -> str: - for rule in self.chains[chain]: + for rule in self.tables[packet.dst.version][chain]: options = dict(zip(rule[::2], rule[1::2])) if not _matches(packet, rule, options): continue @@ -96,9 +135,17 @@ def _walk(self, packet: Packet, chain: str) -> str: return "RETURN" +def _interface(pattern: str, name: str | None) -> bool: + return name is not None and (name.startswith(pattern[:-1]) if pattern.endswith("+") else name == pattern) + + def _matches(packet: Packet, rule: tuple[str, ...], options: dict[str, str]) -> bool: if "--ctstate" in rule and not packet.established: return False + if "-i" in options and not _interface(options["-i"], packet.in_iface): + return False + if "-o" in options and not _interface(options["-o"], packet.out_iface): + return False if "-s" in options and packet.src not in ip_network(options["-s"]): return False if "-d" in options and packet.dst not in ip_network(options["-d"]): @@ -112,13 +159,28 @@ def _matches(packet: Packet, rule: tuple[str, ...], options: dict[str, str]) -> class Packet: src: IPv4Address dst: IPv4Address + in_iface: str + out_iface: str | None = None proto: str = "tcp" dport: int = 443 established: bool = False -def packet(src: str, dst: str, **kw) -> Packet: - return Packet(ip_address(src), ip_address(dst), **kw) +def packet(src: str, dst: str, in_iface: str = "eth0", out_iface: str | None = None, **kw) -> Packet: + return Packet(ip_address(src), ip_address(dst), in_iface, out_iface, **kw) + + +def from_slot(index: int, dst: str, *, half: str = "env", out_iface: str | None = "eth0", src: str | None = None, + **kw) -> Packet: + """A packet that came in on slot ``index``'s ``half`` bridge, from an address of that half unless ``src`` spoofs + another.""" + network = getattr(slot_networks(index), half) + return packet(src or host(network), dst, getattr(slot_bridges(index), half), out_iface, **kw) + + +def to_slot(index: int, half: str = "env") -> dict[str, str]: + """The destination and out interface of a packet to slot ``index``'s ``half``.""" + return {"dst": host(getattr(slot_networks(index), half), 3), "out_iface": getattr(slot_bridges(index), half)} @pytest.fixture @@ -163,76 +225,127 @@ def test_a_resolv_conf_with_no_usable_resolver_is_refused(conf): upstream_resolvers(conf) -def test_a_slot_reaches_both_halves_of_its_own_23_and_no_other_slot(walled): +def test_a_slot_reaches_both_its_bridges_and_no_other_slots(walled): for i in range(SLOT_COUNT): - own = slot_networks(i) - assert walled.verdict(packet(host(own.env), host(own.website)), "FORWARD") == "ACCEPT" - assert walled.verdict(packet(host(own.website), host(own.env, 3)), "FORWARD") == "ACCEPT" + for half, other_half in itertools.product(("env", "website"), repeat=2): + assert walled.verdict(from_slot(i, half=half, **to_slot(i, other_half)), "FORWARD") == "ACCEPT" for j in (j for j in range(SLOT_COUNT) if j != i): - other = slot_networks(j) - assert walled.verdict(packet(host(own.env), host(other.env)), "FORWARD") == "DROP" - assert walled.verdict(packet(host(own.website), host(other.website)), "FORWARD") == "DROP" + assert walled.verdict(from_slot(i, **to_slot(j)), "FORWARD") == "DROP" + assert walled.verdict(from_slot(i, half="website", **to_slot(j, "website")), "FORWARD") == "DROP" + + +def test_a_slot_that_spoofs_another_slots_address_is_still_walled_in_by_its_bridge(walled): + spoofed = host(slot_networks(5).env) + + assert walled.verdict(from_slot(3, src=spoofed, **to_slot(5)), "FORWARD") == "DROP" + assert walled.verdict(from_slot(3, src=spoofed, **to_slot(5, "website")), "FORWARD") == "DROP" + assert walled.verdict(from_slot(3, "10.0.0.5", src="8.8.8.8"), "FORWARD") == "DROP" + assert walled.verdict(from_slot(3, "10.250.6.1", src="172.21.0.9", out_iface=None), "INPUT") == "DROP" @pytest.mark.parametrize("resolver", [str(r) for r in RESOLVERS]) def test_a_slot_reaches_each_resolver_on_port_53_only(walled, resolver): - slot = host(slot_networks(7).env) - for proto in ("udp", "tcp"): - assert walled.verdict(packet(slot, resolver, proto=proto, dport=53), "FORWARD") == "ACCEPT" + assert walled.verdict(from_slot(7, resolver, proto=proto, dport=53), "FORWARD") == "ACCEPT" if ip_address(resolver).is_private: - assert walled.verdict(packet(slot, resolver, dport=80), "FORWARD") == "DROP" + assert walled.verdict(from_slot(7, resolver, dport=80), "FORWARD") == "DROP" @pytest.mark.parametrize("dst", ["10.0.0.5", "10.251.0.2", "172.16.4.4", "172.21.0.2", "192.168.1.1", "169.254.169.254", "100.64.0.1", "100.127.255.254"]) def test_a_slot_reaches_no_private_link_local_or_carrier_address(walled, dst): - assert walled.verdict(packet(host(slot_networks(0).env), dst, proto="udp", dport=53), "FORWARD") == "DROP" + assert walled.verdict(from_slot(0, dst, proto="udp", dport=53), "FORWARD") == "DROP" def test_a_slot_reaches_the_internet_and_replies_to_what_reached_it(walled): - slot = host(slot_networks(45).website) - - assert walled.verdict(packet(slot, "8.8.4.4"), "FORWARD") == "ACCEPT" - assert walled.verdict(packet(slot, "172.20.0.9", established=True), "FORWARD") == "ACCEPT" + assert walled.verdict(from_slot(45, "8.8.4.4", half="website"), "FORWARD") == "ACCEPT" + assert walled.verdict(from_slot(45, "172.20.0.9", half="website", established=True), "FORWARD") == "ACCEPT" + assert walled.verdict(from_slot(45, half="website", established=True, **to_slot(2)), "FORWARD") == "ACCEPT" def test_a_slot_reaches_nothing_on_the_box_but_replies_to_the_box(walled): - slot = host(slot_networks(3).env) + assert walled.verdict(from_slot(3, "10.250.6.1", out_iface=None), "INPUT") == "DROP" + assert walled.verdict(from_slot(3, "172.21.0.9", out_iface=None, dport=22), "INPUT") == "DROP" + assert walled.verdict(from_slot(3, "10.250.6.1", out_iface=None, established=True), "INPUT") == "ACCEPT" - assert walled.verdict(packet(slot, "10.250.6.1"), "INPUT") == "DROP" - assert walled.verdict(packet(slot, "172.21.0.9", dport=22), "INPUT") == "DROP" - assert walled.verdict(packet(slot, "10.250.6.1", established=True), "INPUT") == "ACCEPT" + +def test_no_ipv6_from_a_slot_is_forwarded_or_reaches_the_box_even_as_a_reply(walled): + for established in (False, True): + for dst, out_iface in (("2001:4860:4860::8888", "eth0"), ("fd00::2", "aes3web"), ("fe80::1", "aes3env")): + assert walled.verdict(packet("fd00::9", dst, "aes3env", out_iface, established=established), + "FORWARD") == "DROP" + assert walled.verdict(packet("fd00::9", "fe80::1", "aes3env", established=established), "INPUT") == "DROP" def test_traffic_not_from_a_slot_is_left_to_docker(walled): - assert walled.verdict(packet("10.251.0.2", "172.21.0.9", dport=80), "FORWARD") == "ACCEPT" - assert walled.verdict(packet("172.21.0.9", host(slot_networks(0).env)), "FORWARD") == "ACCEPT" - assert walled.verdict(packet("10.251.0.2", "10.251.0.1"), "INPUT") == "ACCEPT" + assert walled.verdict(packet("10.251.0.2", "172.21.0.9", "br-1a2b", "eth0", dport=80), "FORWARD") == "ACCEPT" + assert walled.verdict(packet("172.21.0.9", in_iface="eth0", **to_slot(0)), "FORWARD") == "ACCEPT" + assert walled.verdict(packet("10.251.0.2", "10.251.0.1", "br-1a2b"), "INPUT") == "ACCEPT" + assert walled.verdict(packet("2001:db8::2", "2001:db8::1", "eth0"), "INPUT") == "ACCEPT" + +def test_each_restore_is_one_transaction_that_empties_and_fills_both_walls_chains(): + lines = walls_firewall_script(RESOLVERS).splitlines() + restores = [i for i, line in enumerate(lines) if "-restore" in line] -def test_running_the_script_again_leaves_the_same_rules_and_no_guard(walled): - before = {chain: list(rules) for chain, rules in walled.chains.items()} + assert [lines[i] for i in restores] == ["iptables-restore -w --noflush <<'WALLS'", + "ip6tables-restore -w --noflush <<'WALLS'"] + for i in restores: + body = lines[i + 1:lines.index("WALLS", i)] + assert body[0] == "*filter" and body[-1] == "COMMIT" and body.count("COMMIT") == 1 + for chain in ("AGENTENV-WALLS-FWD", "AGENTENV-WALLS-IN"): + assert f":{chain} - [0:0]" in body + assert body.index(f"-F {chain}") < min(n for n, line in enumerate(body) if line.startswith(f"-A {chain} ")) + + +def test_running_the_script_again_leaves_the_same_rules(walled): + before = copy.deepcopy(walled.tables) walled.run(walls_firewall_script(RESOLVERS)) - assert walled.chains == before + assert walled.tables == before assert walled.chains["DOCKER-USER"][0] == ("-j", "AGENTENV-WALLS-FWD") assert walled.chains["INPUT"] == [("-j", "AGENTENV-WALLS-IN")] + assert walled.tables[6]["FORWARD"] == [("-j", "AGENTENV-WALLS-FWD")] + assert walled.tables[6]["INPUT"] == [("-j", "AGENTENV-WALLS-IN")] -def test_a_run_that_fails_part_way_leaves_every_slot_walled_off(): +def test_a_run_over_older_walls_replaces_their_rules(): table = FakeIptables() table.run(walls_firewall_script(RESOLVERS)) - table.fail_on = "-A AGENTENV-WALLS-FWD -s 10.250.0.0/16 -d 10.0.0.0/8" + table.chains["AGENTENV-WALLS-FWD"].insert(0, ("-s", "10.250.0.0/16", "-j", "RETURN")) + + table.run(walls_firewall_script(RESOLVERS)) + + assert table.verdict(from_slot(0, **to_slot(1)), "FORWARD") == "DROP" + assert table.chains["DOCKER-USER"].count(("-j", "AGENTENV-WALLS-FWD")) == 1 + + +@pytest.mark.parametrize("fail_on, family", [("-A AGENTENV-WALLS-FWD -i aes+ -d 10.0.0.0/8", 4), + ("-A AGENTENV-WALLS-IN -i aes+ -j DROP", 4), ("ip6tables-restore", 6)]) +def test_a_restore_that_fails_leaves_its_walls_as_they_were_and_nothing_runs_after(fail_on, family): + table = FakeIptables() + table.run(walls_firewall_script(RESOLVERS)) + for chains in table.tables.values(): + chains["AGENTENV-WALLS-FWD"].append(("-j", "DROP")) + before = copy.deepcopy(table.tables[family]) + table.calls.clear() + table.fail_on = fail_on with pytest.raises(IptablesFailed): table.run(walls_firewall_script(RESOLVERS)) - slot = host(slot_networks(0).env) - assert table.verdict(packet(slot, host(slot_networks(0).website)), "FORWARD") == "DROP" - assert table.verdict(packet(slot, "8.8.4.4"), "FORWARD") == "DROP" - assert table.verdict(packet(slot, "10.250.0.1"), "INPUT") == "DROP" + assert table.tables[family] == before + assert "-restore" in table.calls[-1] and not any(" -C " in call or " -I " in call for call in table.calls) + + +def test_a_box_without_ip6tables_fails_the_script_before_any_wall_is_hooked_in(): + table = FakeIptables(missing=("ip6tables-restore",)) + + with pytest.raises(IptablesFailed, match="ip6tables-restore"): + table.run(walls_firewall_script(RESOLVERS)) + + assert table.chains["DOCKER-USER"] == [("-j", "RETURN")] and table.chains["INPUT"] == [] def test_the_script_fails_before_dockerd_has_made_its_docker_user_chain(): @@ -240,6 +353,56 @@ def test_the_script_fails_before_dockerd_has_made_its_docker_user_chain(): FakeIptables(docker_user=False).run(walls_firewall_script(RESOLVERS)) +# A stand-in for one iptables tool: it logs its command line and any restore input it is fed, says no rule exists to +# ``-C``, and fails any command matching the case pattern FAIL. +_STUB = """#!BASH +call="${0##*/} $*" +printf '%s\\n' "$call" >> LOG +case "$call" in *-restore*) while IFS= read -r line; do printf '%s\\n' "$line" >> LOG; done ;; esac +case "$call" in FAIL) exit 1 ;; *" -C "*) exit 1 ;; esac +""" + + +def _run_under_bash(tmp_path, tools: tuple[str, ...], fail: str = "__never__") -> tuple[int, list[str]]: + """Run the script under bash with only ``tools``, as stubs, on its PATH: its exit code and the stubs' log.""" + bash, log = shutil.which("bash"), tmp_path / "log" + (tmp_path / "bin").mkdir() + for tool in tools: + stub = tmp_path / "bin" / tool + stub.write_text(_STUB.replace("BASH", bash).replace("LOG", str(log)).replace("FAIL", fail)) + stub.chmod(0o755) + done = subprocess.run([bash, "-c", walls_firewall_script(RESOLVERS)], env={"PATH": str(tmp_path / "bin")}, + capture_output=True, text=True) + return done.returncode, log.read_text().splitlines() if log.exists() else [] + + +_ALL_TOOLS = ("iptables", "iptables-restore", "ip6tables", "ip6tables-restore") + + +def test_under_bash_each_restore_reads_its_whole_input_then_each_wall_is_hooked_in(tmp_path): + code, log = _run_under_bash(tmp_path, _ALL_TOOLS) + + script = walls_firewall_script(RESOLVERS).splitlines() + assert code == 0 + assert log[:log.index("ip6tables-restore -w --noflush")] == \ + ["iptables-restore -w --noflush", *script[2:script.index("WALLS")]] + assert [line for line in log if " -I " in line] == [ + "iptables -w -I DOCKER-USER 1 -j AGENTENV-WALLS-FWD", "iptables -w -I INPUT 1 -j AGENTENV-WALLS-IN", + "ip6tables -w -I FORWARD 1 -j AGENTENV-WALLS-FWD", "ip6tables -w -I INPUT 1 -j AGENTENV-WALLS-IN"] + + +@pytest.mark.parametrize("tools, fail", [ + pytest.param(_ALL_TOOLS, "iptables-restore*", id="iptables-restore fails"), + pytest.param(_ALL_TOOLS, "ip6tables-restore*", id="ip6tables-restore fails"), + pytest.param(("iptables", "iptables-restore", "ip6tables"), "__never__", id="no ip6tables-restore"), +]) +def test_under_bash_a_failed_or_missing_restore_fails_the_script_before_any_hook(tmp_path, tools, fail): + code, log = _run_under_bash(tmp_path, tools, fail) + + assert code != 0 + assert not any(" -C " in line or " -I " in line for line in log) + + def test_the_script_needs_a_resolver(): with pytest.raises(ValueError): walls_firewall_script(()) @@ -257,6 +420,22 @@ async def test_applying_the_walls_reads_the_boxs_resolvers_and_runs_the_script_f assert box.exec_script.await_args.args == (walls_firewall_script(RESOLVERS),) +@pytest.mark.asyncio +async def test_applying_the_walls_raises_when_a_restore_fails_and_keeps_the_walls_as_they_were(): + table = FakeIptables() + table.run(walls_firewall_script(RESOLVERS)) + before = copy.deepcopy(table.tables) + table.fail_on = "ip6tables-restore" + box = MagicMock(sandbox_id="sb-1") + box.exec_with_output = AsyncMock(return_value=(0, MODAL_RESOLV_CONF, "")) + box.exec_script = AsyncMock(side_effect=lambda script, **_: table.run(script)) + + with pytest.raises(IptablesFailed): + await apply_walls_firewall(box) + + assert table.tables == before + + @pytest.mark.asyncio async def test_applying_the_walls_raises_and_runs_nothing_when_resolv_conf_cant_be_read(): box = MagicMock(sandbox_id="sb-1") From d24cfca0037fd039d1db812e5b73ddf55a183c6b Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Sat, 21 Nov 2026 00:49:27 -0500 Subject: [PATCH 07/15] fix(env-providers): the door is no open proxy, the slot check allows only the generator's keys, env values stay one string, and every slot caller sends the door header The door built its upstream URL by appending the raw request target, so a target like @10.250.0.9:80/x sent the request, token stripped, to another host. It now answers 400 to any target that isn't a path from the root (//x, @host/x, an absolute URL, *), and builds the upstream URL from the route's host and port, for HTTP and WebSockets. The slot compose check takes an allowlist instead of a denylist: the keys the default stack's generator and slot_compose write, and services, networks and volumes at the top level. So build, env_file, extends, include, configs, secrets, cgroup, gpus, deploy, security_opt, sysctls and volumes_from are all refused. A named volume with any settings is refused, as driver_opts can bind any host path, and so is a $ in a mount's source or a mount type other than bind, volume or tmpfs. An anonymous volume such as /var/lib/postgresql/data passes, which it didn't. An MCP server's extra_env_vars and a sidecar's env are written as they are when YAML reads them back as one string, and JSON-quoted otherwise, so a newline or ": " can't add a key or a service. Plain values render as before; the default stack's golden file is unchanged. The legacy MCP reset and tool check, the spec conformance check's live tool read, the legacy /export-state stream and the in-process proxy's MCP registrations now send the slot's door header, and nothing new for the default stack. A slot refuses computers on sandboxes of their own: their clock follower and site routing would need the door token on another machine, so the token stays on the box. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/door.py | 42 +++-- src/agent_env/env/legacy_protocol.py | 46 +++--- .../env_providers/env_gateway_provider.py | 21 ++- .../providers/env_providers/slot_compose.py | 38 +++-- src/agent_env/task/episode/run.py | 10 +- src/agent_env/task/episode/steps.py | 3 +- .../verify_spec_conformance.py | 2 +- .../task_step/task_steps/snapshot_env.py | 2 +- tst/unit/env/door_grant_test.py | 143 +++++++++++++++++- tst/unit/env/gateway/door_test.py | 61 ++++++++ .../env_gateway_provider_test.py | 18 +++ .../env_providers/slot_compose_test.py | 49 +++++- 12 files changed, 378 insertions(+), 57 deletions(-) diff --git a/src/agent_env/env/gateway/door.py b/src/agent_env/env/gateway/door.py index 5a97a4b9a..fecc78c82 100644 --- a/src/agent_env/env/gateway/door.py +++ b/src/agent_env/env/gateway/door.py @@ -5,7 +5,8 @@ the door removes that header and forwards the rest, ``Authorization`` and ``Host`` included, untouched. HTTP bodies stream both ways, so server-sent events and long downloads pass as they come, and WebSockets are relayed frame by frame. Every other request gets 401. Browsers can't set the header, and no cookie or ticket sign-in exists yet, so a -browser is refused too. +browser is refused too. A request target that isn't a path from the root (``//x``, ``@host/x``, ``http://host/x``) gets +400, and the upstream address is built from the route alone, so no request can point the door at another host. """ from __future__ import annotations @@ -31,6 +32,7 @@ b"trailer", b"transfer-encoding", b"upgrade", b"proxy-connection"}) _REFUSAL = (f"401: this slot's door takes only the {SLOT_TOKEN_HEADER} header. Browser sign-in (a cookie or a " f"ticket) isn't supported yet.\n").encode() +_BAD_TARGET = b"400: the door takes only a request target that is a path from the root, like /mcp\n" _UPSTREAM_CONNECT_TIMEOUT_S = 10.0 @@ -54,30 +56,33 @@ class Door: def __init__(self, upstream: str, token: str, client: httpx.AsyncClient): if not token: raise ValueError("a door needs a token") + host, _, port = upstream.rpartition(":") self._upstream = upstream + self._host, self._port = host, int(port) self._token = token.encode() self._client = client async def __call__(self, scope, receive, send) -> None: admitted = self._admitted(scope["headers"]) headers = [(k, v) for k, v in scope["headers"] if k != _TOKEN_HEADER and k not in _HOP_BY_HOP] + target = _path_target(scope) if scope["type"] == "websocket": - await self._websocket(scope, receive, send, headers, admitted) - elif admitted: - await self._http(scope, receive, send, headers) - else: + await self._websocket(scope, receive, send, headers, admitted, target) + elif not admitted: await _respond(send, 401, _REFUSAL) + elif target is None: + await _respond(send, 400, _BAD_TARGET) + else: + await self._http(scope, receive, send, headers, target) def _admitted(self, headers) -> bool: tokens = [value for key, value in headers if key == _TOKEN_HEADER] return len(tokens) == 1 and hmac.compare_digest(tokens[0], self._token) - def _target(self, scope, scheme: str) -> str: - path = scope.get("raw_path") or scope["path"].encode() - query = f"?{scope['query_string'].decode('latin-1')}" if scope.get("query_string") else "" - return f"{scheme}://{self._upstream}{path.decode('latin-1')}{query}" + def _url(self, scheme: str, target: bytes) -> httpx.URL: + return httpx.URL(scheme=scheme, host=self._host, port=self._port, raw_path=target) - async def _http(self, scope, receive, send, headers) -> None: + async def _http(self, scope, receive, send, headers, target: bytes) -> None: has_body = any(key in (b"content-length", b"transfer-encoding") for key, _ in scope["headers"]) async def body(): @@ -89,7 +94,7 @@ async def body(): if not message.get("more_body"): return - request = self._client.build_request(scope["method"], self._target(scope, "http"), headers=headers, + request = self._client.build_request(scope["method"], self._url("http", target), headers=headers, content=body() if has_body else None) try: response = await self._client.send(request, stream=True) @@ -106,16 +111,19 @@ async def body(): finally: await response.aclose() - async def _websocket(self, scope, receive, send, headers, admitted: bool) -> None: + async def _websocket(self, scope, receive, send, headers, admitted: bool, target: bytes | None) -> None: if (await receive())["type"] != "websocket.connect": return if not admitted: await _deny_websocket(scope, send, 401, _REFUSAL) return + if target is None: + await _deny_websocket(scope, send, 400, _BAD_TARGET) + return forwarded = [(k.decode("latin-1"), v.decode("latin-1")) for k, v in headers if k != b"host" and not k.startswith(b"sec-websocket-")] try: - upstream = await connect(self._target(scope, "ws"), additional_headers=forwarded, + upstream = await connect(str(self._url("ws", target)), additional_headers=forwarded, subprotocols=scope.get("subprotocols") or None, max_size=None, open_timeout=_UPSTREAM_CONNECT_TIMEOUT_S) except Exception as e: @@ -145,6 +153,14 @@ async def upstream_bound(): await upstream.close() +def _path_target(scope) -> bytes | None: + """The request's path and query as sent, when the path is one from the root (``/`` then not ``/``); else None.""" + path = scope.get("raw_path") or scope["path"].encode() + if not path.startswith(b"/") or path.startswith(b"//"): + return None + return path + b"?" + scope["query_string"] if scope.get("query_string") else path + + async def _respond(send, status: int, body: bytes) -> None: await send({"type": "http.response.start", "status": status, "headers": [(b"content-type", b"text/plain"), (b"content-length", str(len(body)).encode())]}) diff --git a/src/agent_env/env/legacy_protocol.py b/src/agent_env/env/legacy_protocol.py index 1acf6eb81..86cacbb28 100644 --- a/src/agent_env/env/legacy_protocol.py +++ b/src/agent_env/env/legacy_protocol.py @@ -8,8 +8,10 @@ from __future__ import annotations import asyncio +import contextlib import dataclasses import logging +from collections.abc import AsyncIterator from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Optional @@ -18,6 +20,7 @@ from mcp import ClientSession from mcp.types import CallToolResult from mcp.client.streamable_http import streamable_http_client +from mcp.shared._httpx_utils import create_mcp_http_client from agent_env.env.door_headers import granted_door_headers @@ -267,18 +270,27 @@ async def service_state(deployed: Optional[DeployedEnv], gateway_url: Optional[s return await _export_state_at(base_url, timeout=EXPORT_STATE_TIMEOUT_SECONDS, verify=True) +@contextlib.asynccontextmanager +async def _mcp_session(mcp_url: str) -> AsyncIterator[ClientSession]: + """An initialized MCP session with ``mcp_url``, on mcp's own client, sending the slot door's header the running + step's grant gives it (``granted_door_headers``).""" + async with create_mcp_http_client(headers=granted_door_headers(mcp_url) or None) as http_client, \ + streamable_http_client(mcp_url, http_client=http_client) as (read_stream, write_stream, _), \ + ClientSession(read_stream, write_stream) as session: + await session.initialize() + yield session + + async def offers_tool(mcp_url: str, name: str) -> bool: """Whether the MCP endpoint at ``mcp_url`` lists the tool ``name``, on any page of its tools.""" - async with streamable_http_client(mcp_url) as (read_stream, write_stream, _): - async with ClientSession(read_stream, write_stream) as session: - await session.initialize() - cursor = None - while True: - page = await session.list_tools(cursor) - if any(tool.name == name for tool in page.tools): - return True - if not (cursor := page.nextCursor): - return False + async with _mcp_session(mcp_url) as session: + cursor = None + while True: + page = await session.list_tools(cursor) + if any(tool.name == name for tool in page.tools): + return True + if not (cursor := page.nextCursor): + return False async def reset_via_mcp_tool( @@ -293,14 +305,12 @@ async def reset_via_mcp_tool( for attempt in range(max_retries): reset_done = False try: - async with streamable_http_client(mcp_url) as (read_stream, write_stream, _): - async with ClientSession(read_stream, write_stream) as session: - await session.initialize() - reset_tool_name = f"{environment_name}_reset" - result = await session.call_tool(reset_tool_name, arguments) - result_text = "".join(c.text for c in result.content if hasattr(c, "text")) - logger.info(f"load_environment_artifact: {reset_tool_name} returned: {result_text}") - reset_done = True + async with _mcp_session(mcp_url) as session: + reset_tool_name = f"{environment_name}_reset" + result = await session.call_tool(reset_tool_name, arguments) + result_text = "".join(c.text for c in result.content if hasattr(c, "text")) + logger.info(f"load_environment_artifact: {reset_tool_name} returned: {result_text}") + reset_done = True except BaseExceptionGroup as eg: if reset_done: logger.info("load_environment_artifact: succeeded (ignoring cleanup ExceptionGroup)") diff --git a/src/agent_env/providers/env_providers/env_gateway_provider.py b/src/agent_env/providers/env_providers/env_gateway_provider.py index bf3ef70f6..2a75b6bdb 100644 --- a/src/agent_env/providers/env_providers/env_gateway_provider.py +++ b/src/agent_env/providers/env_providers/env_gateway_provider.py @@ -18,6 +18,7 @@ from typing import TYPE_CHECKING, Optional import httpx +import yaml from agentenv_protocol.client import control_headers from agentenv_protocol.website import ( SESSION_SECRET_ENV, @@ -508,8 +509,7 @@ def create_docker_compose( db_url = state_provider.url_for_environment(server.environment_name, instance=state_instance) lines.append(f" - DATABASE_URL={db_url}") if server.extra_env_vars: - for key, value in server.extra_env_vars.items(): - lines.append(f" - {key}={value}") + lines.extend(_environment_line(key, value) for key, value in server.extra_env_vars.items()) lines.extend([ " healthcheck:", f' test: ["CMD-SHELL", "python3 -c \\"import socket; s=socket.create_connection((\'localhost\',{gateway_port}),2); s.close()\\""]', @@ -655,8 +655,7 @@ def create_docker_compose( ]) if sc.env: lines.append(" environment:") - for key, value in sc.env.items(): - lines.append(f" - {key}={value}") + lines.extend(_environment_line(key, value) for key, value in sc.env.items()) lines.extend([ " ports:", *(f' - "{spec}"' for spec in port_bindings(host_ips, publish(sc.host_port), sc.container_port)), @@ -1554,6 +1553,9 @@ async def _deploy_gateway( if stack_layout.is_slot and (existing_sandbox is None or not existing_sandbox.walls_verified): raise ValueError(f"Can't deploy into slot {stack_layout.compose_project}: a slot needs an existing sandbox " f"whose walls between slots are verified") + if stack_layout.is_slot and children is not None: + raise ValueError(f"Can't deploy into slot {stack_layout.compose_project}: a computer runs on a sandbox of " + "its own, and its clock follower and site routing would need the slot's door token there") self._stack_layout = stack_layout # Every attempt starts from the caller's store: a failed attempt's close() cleared it. self._state_instance = state_instance @@ -1891,6 +1893,17 @@ def _settings_lines(settings: dict) -> list[str]: +def _environment_line(key: str, value: object) -> str: + """The compose line setting ``key`` to ``value`` in a service's environment list: as written when YAML reads it + back as that one string, else quoted, so a newline or a ``: `` in a value can't add a key or a service.""" + entry = f"{key}={value}" + try: + plain = "\n" not in entry and "\r" not in entry and yaml.safe_load(f"- {entry}") == [entry] + except yaml.YAMLError: + plain = False + return f" - {entry}" if plain else f" - {json.dumps(entry)}" + + def _seconds(seconds: float) -> str: """``seconds`` as a compose duration, in whole seconds rounded up, so a health check never allows less.""" return f"{math.ceil(seconds)}s" diff --git a/src/agent_env/providers/env_providers/slot_compose.py b/src/agent_env/providers/env_providers/slot_compose.py index 0167ed605..fd1a3265f 100644 --- a/src/agent_env/providers/env_providers/slot_compose.py +++ b/src/agent_env/providers/env_providers/slot_compose.py @@ -24,10 +24,13 @@ DOOR_COMMAND = ["python", "-m", "gateway.door"] SLOT_RUNTIME = "runsc" _BRIDGE_NAME_OPTION = "com.docker.network.bridge.name" -# Compose keys that would let a slot's container reach past its walls: host devices and capabilities, another -# namespace than its own, a looser seccomp or AppArmor profile. -_REFUSED_KEYS = ("privileged", "cap_add", "devices", "device_cgroup_rules", "network_mode", "pid", "ipc", "uts", - "userns_mode", "cgroup_parent", "security_opt", "volumes_from", "sysctls") +# The only keys a slot's compose may use: the ones the default stack's generator and slot_compose write. Every other +# key is refused rather than listed, as many reach past the walls: host devices, capabilities or namespaces, a looser +# profile, a build context, files read from the box (env_file, include, extends, configs, secrets). +_ALLOWED_TOP_LEVEL_KEYS = frozenset({"services", "networks", "volumes"}) +_ALLOWED_SERVICE_KEYS = frozenset({"image", "command", "depends_on", "environment", "extra_hosts", "healthcheck", + "networks", "ports", "restart", "shm_size", "volumes", "runtime"}) +_MOUNT_TYPES = frozenset({"bind", "volume", "tmpfs"}) def resolv_conf_path(layout: StackLayout) -> str: @@ -82,12 +85,14 @@ def slot_compose(compose: str, layout: StackLayout, *, door_image: str, door_tok def slot_compose_problems(doc: Mapping, layout: StackLayout) -> list[str]: - """Why a slot's parsed compose file would let a container past its walls: a key in ``_REFUSED_KEYS``, a runtime - other than gVisor, a published port on any service but the door, the docker socket, or a bind mount from outside - ``layout.app_dir``. Empty when there is none.""" - problems = [] + """Why a slot's parsed compose file would let a container past its walls: a key outside the allowed ones, a named + volume with any settings (a driver's options can bind any host path), a runtime other than gVisor, a published + port on any service but the door, the docker socket, a bind mount from outside ``layout.app_dir``, or a ``$`` in a + mount's source. Empty when there is none.""" + problems = [f"the file sets {key}" for key in doc if key not in _ALLOWED_TOP_LEVEL_KEYS] + problems += [f"volume {name} sets {sorted(config)}" for name, config in (doc.get("volumes") or {}).items() if config] for name, service in (doc.get("services") or {}).items(): - problems += [f"{name} sets {key}" for key in _REFUSED_KEYS if key in service] + problems += [f"{name} sets {key}" for key in service if key not in _ALLOWED_SERVICE_KEYS] if service.get("runtime") != SLOT_RUNTIME: problems.append(f"{name} runs under {service.get('runtime')!r}, not {SLOT_RUNTIME}") if service.get("ports") and name != DOOR_SERVICE_NAME: @@ -144,13 +149,22 @@ def _addresses(services: Mapping[str, Mapping], networks: Mapping[str, tuple[IPv def _volume_problem(volume: object, app_dir: str) -> str | None: - """Why a service's volume would reach past its slot: the docker socket, or a bind from outside ``app_dir``.""" + """Why a service's volume would reach past its slot: a ``$`` Compose would fill in, the docker socket, a mount + type other than bind, volume or tmpfs, or a bind from outside ``app_dir``. An anonymous volume (a container path + alone) and a named volume pass.""" if isinstance(volume, Mapping): source = str(volume.get("source") or "") - bind = volume.get("type") == "bind" + kind = volume.get("type") + if kind not in _MOUNT_TYPES: + return f"mounts a {kind!r}, not one of {sorted(_MOUNT_TYPES)}" + bind = kind == "bind" else: - source = str(volume).split(":", 1)[0] + source, separator, _ = str(volume).partition(":") + if not separator: + source = "" bind = source.startswith(("/", ".", "~")) + if "$" in source: + return f"mounts {source}, which Compose would fill in from the box" if "docker.sock" in source: return f"mounts the docker socket ({source})" if not bind: diff --git a/src/agent_env/task/episode/run.py b/src/agent_env/task/episode/run.py index b9b446789..f9be52e17 100644 --- a/src/agent_env/task/episode/run.py +++ b/src/agent_env/task/episode/run.py @@ -288,9 +288,11 @@ def _raise_unless_completed(self) -> None: if (error := self._run.exception()) is not None: raise error - async def _serve_in_process(self, agent: str, role: str | None, mcp_urls: dict[str, str]) -> DeployedAgent: + async def _serve_in_process(self, agent: str, role: str | None, + mcp_urls: dict[str, tuple[str, dict[str, str]]]) -> DeployedAgent: """A proxy served in this process for ``agent``, which works in no sandbox, with each env server registered as - ``deploy_agent`` registers them with any agent, at the URL this process reaches: played as the others are.""" + ``deploy_agent`` registers them with any agent, at the URL this process reaches and with the slot door's header + it takes, both by env id in ``mcp_urls``: played as the others are.""" server = InProcessProxy() self._in_process.append(server) url = await server.start() @@ -299,8 +301,8 @@ async def _serve_in_process(self, agent: str, role: str | None, mcp_urls: dict[s response.raise_for_status() card = response.json() mcp_config = A2AAgent.find_extension(card, A2AAgent.EXT_MCP_CONFIG) - for env_id, mcp_url in mcp_urls.items(): - body = _mcp_add_body(mcp_config, mcp_url, sandbox_request_headers_for_url(mcp_url), env_id, role) + for env_id, (mcp_url, door) in mcp_urls.items(): + body = _mcp_add_body(mcp_config, mcp_url, {**sandbox_request_headers_for_url(mcp_url), **door}, env_id, role) (await client.post(url + mcp_config["params"]["endpoint"], json=body)).raise_for_status() deployed = DeployedAgent(agent_name=agent, api_url=url, a2a_url=url, a2a_card=card, role=role) await self._attach(agent, deployed) diff --git a/src/agent_env/task/episode/steps.py b/src/agent_env/task/episode/steps.py index e5ed62e87..4bd2f40a7 100644 --- a/src/agent_env/task/episode/steps.py +++ b/src/agent_env/task/episode/steps.py @@ -48,7 +48,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: mcp_urls = {} for env_id in getattr(self.step, "env_ids", None) or []: deployed = bound_deployment(context, env_id, env_step_id=self.step.env_step_id, step_id=self.id) - mcp_urls[env_id] = deployed.mcp_url if deployed is not None else live_mcp_url(env_id) + mcp_urls[env_id] = ((deployed.mcp_url, deployed.door_headers_for(deployed.mcp_url or "")) if deployed is not None + else (live_mcp_url(env_id), {})) deployed = await episode._serve_in_process(agent, getattr(self.step, "role", None), mcp_urls) context.deployed_agents.append(deployed) if system_prompt := getattr(self.step, "system_prompt", None): diff --git a/src/agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py b/src/agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py index 9532fc0dd..38e9ad525 100644 --- a/src/agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py +++ b/src/agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py @@ -437,7 +437,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: # slow gateway can't trip httpx's short default and block the gate. mcp_url = deployed.mcp_url logger.info(f"Connecting to MCP at {mcp_url} to read live tools") - http_client = httpx.AsyncClient(timeout=_HTTP_TIMEOUT_S) + http_client = httpx.AsyncClient(timeout=_HTTP_TIMEOUT_S, headers=deployed.door_headers_for(mcp_url or "")) try: async with streamable_http_client(mcp_url, http_client=http_client) as (read_stream, write_stream, _): async with ClientSession(read_stream, write_stream) as session: diff --git a/src/agent_env/task_step/task_steps/snapshot_env.py b/src/agent_env/task_step/task_steps/snapshot_env.py index f81fef173..027873b44 100644 --- a/src/agent_env/task_step/task_steps/snapshot_env.py +++ b/src/agent_env/task_step/task_steps/snapshot_env.py @@ -602,7 +602,7 @@ async def _export_environment_to_file( return ".json" legacy_url = f"{legacy_protocol.environment_base_url(gateway_url, environment_name, mcp=True)}/export-state" - async with httpx.AsyncClient() as client: + async with httpx.AsyncClient(headers=granted_door_headers(legacy_url)) as client: async with client.stream( "GET", legacy_url, diff --git a/tst/unit/env/door_grant_test.py b/tst/unit/env/door_grant_test.py index ea35d35e0..7f3c012a1 100644 --- a/tst/unit/env/door_grant_test.py +++ b/tst/unit/env/door_grant_test.py @@ -4,19 +4,26 @@ from __future__ import annotations import functools +import json from types import SimpleNamespace -from unittest.mock import patch +from unittest.mock import AsyncMock, patch import httpx import pytest from agentenv_protocol import client as protocol_v1 +from agent_env.a2a_agent.a2a_agent import A2AAgent from agent_env.env import legacy_protocol from agent_env.env.env import DeployedEnv, DeployedGatewayEnv from agent_env.env.gateway.constants import SLOT_TOKEN_HEADER from agent_env.explorer.routers import triggers +from agent_env.providers.env_providers.env_gateway_provider import EnvironmentGatewayProvider +from agent_env.providers.env_providers.stack_layout import DEFAULT_STACK_LAYOUT, StackLayout +from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_steps.mcp_cli_builder.build_mcp_cli import _resolve_manifest_endpoint from agent_env.task_step.task_steps.mcp_cli_builder.codegen import generate_cli_script +from agent_env.task_step.task_steps.mcp_env_validator.verify_spec_conformance import VerifySpecConformanceTaskStep +from agent_env.task_step.task_steps.snapshot_env import SnapshotEnvTaskStep GATEWAY = "https://s1-gw.modal.host" PGWEB = "https://s1-pgweb.modal.host/" @@ -118,3 +125,137 @@ def test_a_generated_cli_sends_the_slot_token_it_was_installed_with(monkeypatch, monkeypatch.setenv(namespace["SLOT_TOKEN_ENV"], token) assert namespace["_headers"]().get(SLOT_TOKEN_HEADER) == sent assert namespace["ROLE_HEADER"] in namespace["_headers"]() + + +def _mcp_answer(request: httpx.Request) -> httpx.Response: + """A streamable-HTTP MCP server's answer to ``request``, with one tool, ``crm_reset``.""" + if request.method != "POST": + return httpx.Response(405 if request.method == "GET" else 200) + message = json.loads(request.content) + if "id" not in message: + return httpx.Response(202) + results = { + "initialize": {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, + "serverInfo": {"name": "crm", "version": "1"}}, + "tools/list": {"tools": [{"name": "crm_reset", "inputSchema": {"type": "object"}}]}, + "tools/call": {"content": [{"type": "text", "text": "reset"}], "isError": False}, + } + return httpx.Response(200, json={"jsonrpc": "2.0", "id": message["id"], "result": results[message["method"]]}) + + +@pytest.fixture +def served(monkeypatch) -> list[httpx.Request]: + """Every request any httpx client sends, answered as an MCP server at ``/mcp``, a card-less service elsewhere (404 + for a card, a JSON body for ``/export-state``).""" + requests: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request) + if request.url.path.endswith("/mcp"): + return _mcp_answer(request) + if request.url.path.endswith("/export-state"): + return httpx.Response(200, json={"rows": []}) + return httpx.Response(404) + + monkeypatch.setattr(httpx, "AsyncClient", functools.partial(httpx.AsyncClient, transport=httpx.MockTransport(handler))) + return requests + + +def _door_sent(requests: list[httpx.Request]) -> set[str | None]: + return {request.headers.get(SLOT_TOKEN_HEADER) for request in requests} + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("door_token", "sent"), [(None, None), ("door-tok", "door-tok")]) +async def test_the_legacy_mcp_reset_sends_the_door_header_under_a_slots_grant(served, door_token, sent): + with protocol_v1.authorized(_record(door_token).grants): + assert await legacy_protocol.offers_tool(f"{GATEWAY}/mcp", "crm_reset") + assert not (await legacy_protocol.reset_via_mcp_tool(f"{GATEWAY}/mcp", "crm", max_retries=1)).isError + assert {request.url.path for request in served} == {"/mcp"} + assert _door_sent(served) == {sent} + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("door_token", "sent"), [(None, None), ("door-tok", "door-tok")]) +async def test_the_legacy_export_state_stream_sends_the_door_header_under_a_slots_grant(served, tmp_path, door_token, sent): + with protocol_v1.authorized(_record(door_token).grants): + suffix = await SnapshotEnvTaskStep._export_environment_to_file(GATEWAY, "slack", str(tmp_path / "out"), 30) + assert suffix == ".json" + assert served[-1].url.path == "/svc/mcp-slack/export-state" + assert _door_sent(served) == {sent} + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("door_token", "sent"), [(None, None), ("door-tok", "door-tok")]) +async def test_the_spec_conformance_check_reads_live_tools_with_the_door_header(monkeypatch, door_token, sent): + requests: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request) + if request.url.path.endswith("/openapi.yaml"): + return httpx.Response(200, text="paths:\n /reset:\n post:\n operationId: reset\n") + return _mcp_answer(request) + + monkeypatch.setattr(httpx, "AsyncClient", functools.partial(httpx.AsyncClient, transport=httpx.MockTransport(handler))) + record = _record(door_token) + record.mcp_url = f"{GATEWAY}/mcp" + record.environment_card = {"name": "crm", "url": "/agentenv", + "children_environments": [{"name": "crm", "url": "/svc/mcp-crm/agentenv"}]} + env = SimpleNamespace(environment_name="crm", merge_metadata=lambda _: None) + with patch("agent_env.env.env.Env.get", return_value=env): + await VerifySpecConformanceTaskStep(id="s", version=None, env_id="crm").execute(TaskStepContext(deployed_envs=[record])) + assert [request.url.path for request in requests if request.url.path == "/mcp"] + assert _door_sent(requests) == {sent} + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("door_token", "sent"), [(None, {}), ("door-tok", DOOR)]) +async def test_the_in_process_proxy_registers_each_envs_mcp_server_with_its_door_header(monkeypatch, door_token, sent): + from agent_env.task.episode import run as episode_run + from agent_env.task.episode.steps import _EpisodeAgentStep + + registrations: list[dict] = [] + card = {"capabilities": {"extensions": [{"uri": A2AAgent.EXT_MCP_CONFIG, + "params": {"endpoint": "/mcp-config", "methods": {"add": {"method": "POST"}}}}]}} + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/mcp-config": + registrations.append(json.loads(request.content)) + return httpx.Response(200, json={}) + return httpx.Response(200, json=card) + + monkeypatch.setattr(httpx, "AsyncClient", functools.partial(httpx.AsyncClient, transport=httpx.MockTransport(handler))) + + class _Proxy: + async def start(self) -> str: + return "http://127.0.0.1:1" + + monkeypatch.setattr(episode_run, "InProcessProxy", _Proxy) + record = _record(door_token) + record.mcp_url = f"{GATEWAY}/mcp" + episode = SimpleNamespace(_in_process=[], _attach=AsyncMock()) + episode._serve_in_process = functools.partial(episode_run.Episode._serve_in_process, episode) + step = SimpleNamespace(agent_name="a", env_ids=["crm"], env_step_id=None, role=None) + agent_step = _EpisodeAgentStep.__new__(_EpisodeAgentStep) + agent_step.step, agent_step.sandboxed, agent_step.id = step, False, "play" + context = TaskStepContext(deployed_envs=[record]) + with patch("agent_env.task.episode.steps._episode_of", return_value=episode), \ + patch("agent_env.task.episode.steps.bound_deployment", return_value=record): + await agent_step.execute(context) + assert registrations == [{"url": f"{GATEWAY}/mcp", **({"headers": sent} if sent else {})}] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("layout", [DEFAULT_STACK_LAYOUT, StackLayout.for_slot(2)]) +async def test_a_slot_refuses_computers_on_sandboxes_of_their_own_and_the_default_stack_takes_them(layout): + class _Stop(Exception): + pass + + async def children(_url, _token): + return [] + + with patch.object(EnvironmentGatewayProvider, "in_vm", side_effect=_Stop), \ + pytest.raises(ValueError if layout.is_slot else _Stop, match="sandbox of its own" if layout.is_slot else None): + await EnvironmentGatewayProvider()._deploy_gateway( + SimpleNamespace(), state_instance=None, mcp_servers=[], mcp_server_images=[], + existing_sandbox=SimpleNamespace(walls_verified=True), children=children, stack_layout=layout) diff --git a/tst/unit/env/gateway/door_test.py b/tst/unit/env/gateway/door_test.py index f0e68dedb..8f92120aa 100644 --- a/tst/unit/env/gateway/door_test.py +++ b/tst/unit/env/gateway/door_test.py @@ -146,6 +146,67 @@ async def test_a_websocket_without_the_token_gets_401(door_port): assert refused.value.response.status_code == 401 +@pytest_asyncio.fixture +async def other_host(): + """A server the door must never reach, with every request it gets.""" + seen: list[str] = [] + + async def record(request: Request) -> JSONResponse: + seen.append(request.url.path) + return JSONResponse({"reached": "the other host"}) + + async def record_ws(websocket: WebSocket) -> None: + seen.append(websocket.url.path) + await websocket.accept() + await websocket.close() + + enable_socket() # loopback only + server, port = await _serve(Starlette(routes=[Route("/{path:path}", record), WebSocketRoute("/{path:path}", record_ws)])) + try: + yield port, seen + finally: + await server.shutdown() + + +# {other} is the other host's port. +_BAD_TARGETS = ["@127.0.0.1:{other}/echo", "//127.0.0.1:{other}/echo", "http://127.0.0.1:{other}/echo", "echo", "*"] + + +async def _raw_status(port: int, request: bytes) -> int: + reader, writer = await asyncio.open_connection("127.0.0.1", port) + try: + writer.write(request) + await writer.drain() + status_line = await asyncio.wait_for(reader.readline(), 5) + finally: + writer.close() + return int(status_line.split()[1]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("target", _BAD_TARGETS) +async def test_a_target_that_isnt_a_path_from_the_root_gets_400_and_reaches_no_other_host(door_port, other_host, target): + other_port, seen = other_host + target = target.format(other=other_port) + status = await _raw_status(door_port, f"GET {target} HTTP/1.1\r\nHost: x\r\n{SLOT_TOKEN_HEADER}: {TOKEN}\r\n" + f"Connection: close\r\n\r\n".encode()) + assert status == 400 + assert seen == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("target", _BAD_TARGETS) +async def test_a_websocket_whose_target_isnt_a_path_from_the_root_gets_400_and_reaches_no_other_host(door_port, other_host, + target): + other_port, seen = other_host + target = target.format(other=other_port) + status = await _raw_status(door_port, (f"GET {target} HTTP/1.1\r\nHost: x\r\n{SLOT_TOKEN_HEADER}: {TOKEN}\r\n" + "Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n").encode()) + assert status == 400 + assert seen == [] + + @pytest.mark.asyncio async def test_an_upstream_that_isnt_up_is_a_502_not_a_pass(): enable_socket() diff --git a/tst/unit/providers/env_providers/env_gateway_provider_test.py b/tst/unit/providers/env_providers/env_gateway_provider_test.py index b9a87b550..ea4d060f5 100644 --- a/tst/unit/providers/env_providers/env_gateway_provider_test.py +++ b/tst/unit/providers/env_providers/env_gateway_provider_test.py @@ -1650,6 +1650,24 @@ def test_extra_env_vars_overriding_only_service_name_diverges_the_pair(): assert _env_values(block, "ENVIRONMENT_NAME") == [_ENV_NAME] +@pytest.mark.parametrize("value", ["a\nprivileged: true", "x\n evil:\n image: busybox", "k: v", "\x07bell", " #x"]) +def test_an_env_value_stays_one_string_and_adds_no_key_or_service(value): + from agent_env.env.envs.service_db import ServiceDBConfig + + compose = yaml.safe_load(EnvironmentGatewayProvider().create_docker_compose( + mcp_servers=[MCPServerConfig(image=_ENV_IMAGE, environment_name=_ENV_NAME, extra_env_vars={"V": value})], + sidecars=[SidecarConfig(environment_name="relay", image_artifact=_FakeImageArtifact("ecr/relay:1.0.4"), + container_port=8000, host_port=18768, env={"V": value})], + state_provider=LocalPostgresStateProvider(service_db_config=ServiceDBConfig()), + state_instance=LocalPostgresStateProvider.default_instance(), + )) + services = compose["services"] + assert set(services) == {"servicedb", _ENV_NAME, "gateway", "relay"} + for name in (_ENV_NAME, "relay"): + assert "privileged" not in services[name] + assert services[name]["environment"][-1] == f"V={value}" + + def test_service_name_still_emitted_until_fd1730_removes_it(): """REGRESSION GUARD — the dual-inject is additive-only: SERVICE_NAME must keep being emitted for MCP servers AND website backends, because the deployed fleet still reads it. Dropping that diff --git a/tst/unit/providers/env_providers/slot_compose_test.py b/tst/unit/providers/env_providers/slot_compose_test.py index 41f7e48e3..404bb4711 100644 --- a/tst/unit/providers/env_providers/slot_compose_test.py +++ b/tst/unit/providers/env_providers/slot_compose_test.py @@ -138,6 +138,23 @@ def test_the_slots_compose_passes_its_own_wall_check(slot): (lambda s: s["gateway"]["volumes"].append("../s4:/other"), "bind-mounts ../s4"), (lambda s: s["gateway"]["volumes"].append("~/x:/x"), "bind-mounts ~/x"), (lambda s: s["gateway"]["volumes"].append({"type": "bind", "source": "/app", "target": "/a"}), "bind-mounts /app"), + (lambda s: s["gateway"]["volumes"].append("$HOME/x:/x"), "Compose would fill in"), + (lambda s: s["gateway"]["volumes"].append("./${OTHER}:/x"), "Compose would fill in"), + (lambda s: s["gateway"]["volumes"].append({"type": "bind", "source": "./$X", "target": "/x"}), "Compose would fill in"), + (lambda s: s["gateway"]["volumes"].append({"type": "npipe", "source": "x", "target": "/x"}), "mounts a 'npipe'"), + (lambda s: s["gateway"].update(env_file=["/etc/environment"]), "gateway sets env_file"), + (lambda s: s["gateway"].update(env_file=[f"{SLOT.app_dir}/../s4/.env"]), "gateway sets env_file"), + (lambda s: s["gateway"].update(extends={"file": "/other/compose.yml", "service": "x"}), "gateway sets extends"), + (lambda s: s["gateway"].update(build={"context": "/"}), "gateway sets build"), + (lambda s: s["gateway"].update(cgroup="host"), "gateway sets cgroup"), + (lambda s: s["gateway"].update(gpus="all"), "gateway sets gpus"), + (lambda s: s["gateway"].update(deploy={"resources": {"reservations": {"devices": [{"capabilities": ["gpu"]}]}}}), + "gateway sets deploy"), + (lambda s: s["gateway"].update(sysctls={"net.ipv4.ip_forward": 1}), "gateway sets sysctls"), + (lambda s: s["gateway"].update(volumes_from=["servicedb"]), "gateway sets volumes_from"), + (lambda s: s["gateway"].update(configs=["c"]), "gateway sets configs"), + (lambda s: s["gateway"].update(secrets=["s"]), "gateway sets secrets"), + (lambda s: s["gateway"].pop("runtime"), "gateway runs under None"), ]) def test_the_wall_check_refuses_whatever_would_reach_past_the_slot(slot, change, problem): broken = copy.deepcopy(slot) @@ -145,9 +162,37 @@ def test_the_wall_check_refuses_whatever_would_reach_past_the_slot(slot, change, assert any(problem in found for found in slot_compose_problems(broken, SLOT)) -def test_named_volumes_and_binds_inside_the_slots_dir_pass(slot): +@pytest.mark.parametrize(("key", "value"), [ + ("include", ["/other/compose.yml"]), + ("configs", {"c": {"file": "/etc/shadow"}}), + ("secrets", {"s": {"file": "../s4/secret"}}), +]) +def test_the_wall_check_refuses_a_top_level_key_that_reads_a_file_from_the_box(slot, key, value): + broken = copy.deepcopy(slot) + broken[key] = value + assert f"the file sets {key}" in slot_compose_problems(broken, SLOT) + + +@pytest.mark.parametrize("mount", ["logs:/var/log", {"type": "volume", "source": "logs", "target": "/var/log"}]) +@pytest.mark.parametrize("config", [ + {"driver_opts": {"type": "none", "o": "bind", "device": "/etc"}}, + {"driver_opts": {"device": "/var/run"}}, + {"name": "aes4_logs"}, + {"external": True}, +]) +def test_the_wall_check_refuses_a_named_volume_with_any_settings(slot, mount, config): + broken = copy.deepcopy(slot) + broken["services"]["gateway"]["volumes"].append(mount) + broken["volumes"] = {"logs": config} + assert any(found.startswith("volume logs sets") for found in slot_compose_problems(broken, SLOT)) + + +def test_named_and_anonymous_volumes_and_binds_inside_the_slots_dir_pass(slot): fine = copy.deepcopy(slot) - fine["services"]["gateway"]["volumes"] += ["logs:/var/log", "./data:/data", f"{SLOT.app_dir}/x:/x"] + fine["services"]["gateway"]["volumes"] += ["logs:/var/log", "./data:/data", f"{SLOT.app_dir}/x:/x", + "/var/lib/postgresql/data", {"type": "tmpfs", "target": "/tmp"}, + {"type": "volume", "source": "logs", "target": "/l"}] + fine["volumes"] = {"logs": None} assert slot_compose_problems(fine, SLOT) == [] From ff047c44f1d72002a0d85d998c9c81f208437f14 Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Sat, 21 Nov 2026 01:03:04 -0500 Subject: [PATCH 08/15] fix(sandbox-providers): no slot forges a reply into another, IPv6 is dropped in raw, the tag guard matches places, and a slot compose uses only its own networks The walls chain now decides slot-to-slot traffic before it lets replies through, so a slot can no longer pass a forged established packet into another slot's flow. The script also turns on strict reverse-path filtering (all and default, so slot bridges made later inherit it). IPv6 from a slot is dropped in raw PREROUTING, which Docker's later FORWARD jumps can't get ahead of. The walls-tag guard matches its writer, readers and handle __init__ by module and qualified name. It also catches WALLS_TAG imported under another name, the tag's value or a guarded name built with + or an f-string, _walls= keywords, __dict__ or vars() in a module that mentions walls, and a reattach passing walls= anything but what it read from tags. The restore-failure test now runs through ModalVmSandbox's real exec and exec_script against a fake exec that exits 1. slot_compose_problems refuses a top-level network that isn't exactly the slot's own (subnet, bridge name, no IPv6), and a service on no network or on one outside them, since Compose would put it on a bridge the walls don't see. Co-Authored-By: Claude Opus 5.5 --- .../providers/env_providers/slot_compose.py | 31 ++- .../sandbox_providers/shared_box_walls.py | 36 ++- .../env_providers/slot_compose_test.py | 27 +++ .../modal_shared_box_test.py | 205 +++++++++++++----- .../shared_box_walls_test.py | 129 +++++++++-- 5 files changed, 334 insertions(+), 94 deletions(-) diff --git a/src/agent_env/providers/env_providers/slot_compose.py b/src/agent_env/providers/env_providers/slot_compose.py index fd1a3265f..b7ad2299a 100644 --- a/src/agent_env/providers/env_providers/slot_compose.py +++ b/src/agent_env/providers/env_providers/slot_compose.py @@ -73,12 +73,7 @@ def slot_compose(compose: str, layout: StackLayout, *, door_image: str, door_tok service["extra_hosts"] = [*(service.get("extra_hosts") or []), *(f"{peer}:{ip}" for peer, ip in peers.items())] service["volumes"] = [*(service.get("volumes") or []), resolv_conf_mount] used = {network for service_addresses in addresses.values() for network in service_addresses} - doc["networks"] = {network: { - "driver": "bridge", - "enable_ipv6": False, - "driver_opts": {_BRIDGE_NAME_OPTION: bridge}, - "ipam": {"config": [{"subnet": str(subnet)}]}, - } for network, (subnet, bridge) in networks.items() if network in used} + doc["networks"] = {network: config for network, config in _slot_networks(index).items() if network in used} if problems := slot_compose_problems(doc, layout): raise ValueError(f"slot {index}'s compose file breaks its walls: {'; '.join(problems)}") return yaml.safe_dump(doc, sort_keys=False, width=float("inf")) @@ -86,13 +81,20 @@ def slot_compose(compose: str, layout: StackLayout, *, door_image: str, door_tok def slot_compose_problems(doc: Mapping, layout: StackLayout) -> list[str]: """Why a slot's parsed compose file would let a container past its walls: a key outside the allowed ones, a named - volume with any settings (a driver's options can bind any host path), a runtime other than gVisor, a published - port on any service but the door, the docker socket, a bind mount from outside ``layout.app_dir``, or a ``$`` in a - mount's source. Empty when there is none.""" + volume with any settings (a driver's options can bind any host path), a network other than the slot's own as + ``slot_compose`` writes it, as one on another bridge is outside the walls, a service on none of them, which Compose + would put on such a network, a runtime other than gVisor, a published port on any service but the door, the docker + socket, a bind mount from outside ``layout.app_dir``, or a ``$`` in a mount's source. Empty when there is none.""" problems = [f"the file sets {key}" for key in doc if key not in _ALLOWED_TOP_LEVEL_KEYS] problems += [f"volume {name} sets {sorted(config)}" for name, config in (doc.get("volumes") or {}).items() if config] + own = _slot_networks(layout.slot_index) if layout.slot_index is not None else {} + networks = doc.get("networks") or {} + problems += [f"network {name} isn't one of the slot's own" for name, config in networks.items() + if own.get(name) != config] for name, service in (doc.get("services") or {}).items(): problems += [f"{name} sets {key}" for key in service if key not in _ALLOWED_SERVICE_KEYS] + if not (on := _service_networks(service)) or not networks.keys() >= set(on): + problems.append(f"{name} is on {on or 'no network'}, not only the slot's own") if service.get("runtime") != SLOT_RUNTIME: problems.append(f"{name} runs under {service.get('runtime')!r}, not {SLOT_RUNTIME}") if service.get("ports") and name != DOOR_SERVICE_NAME: @@ -109,6 +111,17 @@ def _slot_network_plan(index: int) -> dict[str, tuple[IPv4Network, str]]: return {ENV_NETWORK: (subnets.env, bridges.env), SITES_NETWORK: (subnets.website, bridges.website)} +def _slot_networks(index: int) -> dict[str, dict]: + """The top-level ``networks`` entry of each network slot ``index`` may use: a bridge with its fixed name and + subnet, and no IPv6.""" + return {network: { + "driver": "bridge", + "enable_ipv6": False, + "driver_opts": {_BRIDGE_NAME_OPTION: bridge}, + "ipam": {"config": [{"subnet": str(subnet)}]}, + } for network, (subnet, bridge) in _slot_network_plan(index).items()} + + def _service_networks(service: Mapping) -> list[str]: networks = service.get("networks") or [] return list(networks) if isinstance(networks, (list, Mapping)) else [] diff --git a/src/agent_env/providers/sandbox_providers/shared_box_walls.py b/src/agent_env/providers/sandbox_providers/shared_box_walls.py index f8e7c1b96..24a294965 100644 --- a/src/agent_env/providers/sandbox_providers/shared_box_walls.py +++ b/src/agent_env/providers/sandbox_providers/shared_box_walls.py @@ -6,7 +6,8 @@ the bridge it came in on, which a container can't spoof as it can a source address. It only drops: what it lets through still meets Docker's own rules, so it never opens a path Docker would close. Forwarded traffic from a slot may reach its own two bridges, the box's upstream resolvers on port 53, and anything outside the private ranges; traffic -from a slot to the box itself, and any IPv6 from a slot, is dropped. +from a slot to another slot, even posing as a reply, to the box itself, and any IPv6 from a slot, is dropped. Strict +reverse-path filtering drops a packet whose source address its bridge doesn't route to. """ from __future__ import annotations @@ -26,10 +27,17 @@ ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", "100.64.0.0/10")) FORWARD_CHAIN, INPUT_CHAIN = "AGENTENV-WALLS-FWD", "AGENTENV-WALLS-IN" _ESTABLISHED = "-m conntrack --ctstate ESTABLISHED,RELATED" -# Where each walls chain is jumped to. The box's dockerd isn't set up for IPv6, so it may make no ip6tables -# DOCKER-USER; the IPv6 walls hook into FORWARD itself. -_HOOKS = (("iptables", "DOCKER-USER", FORWARD_CHAIN), ("iptables", "INPUT", INPUT_CHAIN), - ("ip6tables", "FORWARD", FORWARD_CHAIN), ("ip6tables", "INPUT", INPUT_CHAIN)) +# The rules hooked into the box's own chains, each table, chain and rule. The box's dockerd isn't set up for IPv6, so it +# may make no ip6tables DOCKER-USER, and Docker may later put its own FORWARD jumps above ours: IPv6 from a slot is also +# dropped in raw PREROUTING, which every packet meets before any filter chain and where Docker adds no ACCEPT. +_HOOKS = (("iptables", "filter", "DOCKER-USER", f"-j {FORWARD_CHAIN}"), + ("iptables", "filter", "INPUT", f"-j {INPUT_CHAIN}"), + ("ip6tables", "raw", "PREROUTING", f"-i {SLOT_BRIDGE_PREFIX}+ -j DROP"), + ("ip6tables", "filter", "FORWARD", f"-j {FORWARD_CHAIN}"), + ("ip6tables", "filter", "INPUT", f"-j {INPUT_CHAIN}")) +# Strict reverse-path filtering. Slot bridges come up after the walls, so they take it from ``default``; ``all`` makes +# it the floor for every interface, as the kernel applies the larger of ``all`` and an interface's own value. +RP_FILTER_KNOBS = ("/proc/sys/net/ipv4/conf/all/rp_filter", "/proc/sys/net/ipv4/conf/default/rp_filter") class SlotNetworks(NamedTuple): @@ -91,26 +99,30 @@ def _restore_input(chains: dict[str, list[str]]) -> str: def walls_firewall_script(resolvers: Sequence[IPv4Address]) -> str: """A root shell script that sets the box's firewall to the walls for every slot, the same rules however often it - runs. Each of iptables and ip6tables refills the walls' chains in one transaction, so a run that fails leaves the - walls as they were, then each chain is hooked in once. A box without ip6tables fails the script.""" + runs. It turns on strict reverse-path filtering, then each of iptables and ip6tables refills the walls' chains in + one transaction, so a run that fails leaves the walls as they were, then each hook is added once. A box without + ip6tables fails the script. + + Slot-to-slot traffic is decided before conntrack is asked whether a packet is a reply: no real flow crosses + slots, so a slot that forges a reply into another slot's flow is dropped like any other packet between them.""" if not resolvers: raise ValueError("the walls need at least one upstream resolver") from_slot = f"-i {SLOT_BRIDGE_PREFIX}+" - forward = [f"{_ESTABLISHED} -j RETURN"] + forward = [] for bridges in map(slot_bridges, range(SLOT_COUNT)): forward += [f"-i {a} -o {b} -j RETURN" for a in bridges for b in bridges] - forward.append(f"{from_slot} -o {SLOT_BRIDGE_PREFIX}+ -j DROP") + forward += [f"{from_slot} -o {SLOT_BRIDGE_PREFIX}+ -j DROP", f"{_ESTABLISHED} -j RETURN"] forward += [f"{from_slot} -d {r}/32 -p {proto} --dport 53 -j RETURN" for r in resolvers for proto in ("udp", "tcp")] forward += [f"{from_slot} -d {n} -j DROP" for n in _PRIVATE_RANGES] tables = { "iptables": {FORWARD_CHAIN: forward, INPUT_CHAIN: [f"{_ESTABLISHED} -j RETURN", f"{from_slot} -j DROP"]}, "ip6tables": {FORWARD_CHAIN: [f"{from_slot} -j DROP"], INPUT_CHAIN: [f"{from_slot} -j DROP"]}, } - lines = ["set -eu"] + lines = ["set -eu", *(f"printf 1 > {knob}" for knob in RP_FILTER_KNOBS)] for tool, chains in tables.items(): lines += [f"{tool}-restore -w --noflush <<'WALLS'", _restore_input(chains) + "WALLS"] - for tool, parent, chain in _HOOKS: - lines.append(f"{tool} -w -C {parent} -j {chain} 2>/dev/null || {tool} -w -I {parent} 1 -j {chain}") + for tool, table, parent, rule in _HOOKS: + lines.append(f"{tool} -w -t {table} -C {parent} {rule} 2>/dev/null || {tool} -w -t {table} -I {parent} 1 {rule}") return "\n".join(lines) + "\n" diff --git a/tst/unit/providers/env_providers/slot_compose_test.py b/tst/unit/providers/env_providers/slot_compose_test.py index 404bb4711..c0fd7c179 100644 --- a/tst/unit/providers/env_providers/slot_compose_test.py +++ b/tst/unit/providers/env_providers/slot_compose_test.py @@ -187,6 +187,33 @@ def test_the_wall_check_refuses_a_named_volume_with_any_settings(slot, mount, co assert any(found.startswith("volume logs sets") for found in slot_compose_problems(broken, SLOT)) +@pytest.mark.parametrize(("change", "problem"), [ + pytest.param(lambda n: n["env-network"]["ipam"]["config"][0].update(subnet=str(slot_networks(4).env)), + "network env-network isn't one of the slot's own", id="another slot's subnet"), + pytest.param(lambda n: n["website-network"]["driver_opts"].update({"com.docker.network.bridge.name": "br-x"}), + "network website-network isn't one of the slot's own", id="a bridge outside the walls"), + pytest.param(lambda n: n["env-network"]["driver_opts"].update({"com.docker.network.bridge.name": slot_bridges(4).env}), + "network env-network isn't one of the slot's own", id="another slot's bridge"), + pytest.param(lambda n: n["env-network"].update(enable_ipv6=True), "network env-network isn't", id="ipv6"), + pytest.param(lambda n: n["env-network"].update(external=True), "network env-network isn't", id="external"), + pytest.param(lambda n: n["env-network"].pop("driver_opts"), "network env-network isn't", id="no bridge name"), + pytest.param(lambda n: n.update(other={"driver": "bridge"}), "network other isn't one of the slot's own", + id="a network of its own"), +]) +def test_the_wall_check_refuses_any_network_but_the_slots_own(slot, change, problem): + broken = copy.deepcopy(slot) + change(broken["networks"]) + assert problem in "; ".join(slot_compose_problems(broken, SLOT)) + + +@pytest.mark.parametrize("networks", [None, [], ["default"], ["env-network", "other"]], + ids=["unset", "empty", "default", "one more"]) +def test_the_wall_check_refuses_a_service_on_any_network_but_the_slots_own(slot, networks): + broken = copy.deepcopy(slot) + broken["services"]["gateway"]["networks"] = networks + assert any(found.startswith("gateway is on") for found in slot_compose_problems(broken, SLOT)) + + def test_named_and_anonymous_volumes_and_binds_inside_the_slots_dir_pass(slot): fine = copy.deepcopy(slot) fine["services"]["gateway"]["volumes"] += ["logs:/var/log", "./data:/data", f"{SLOT.app_dir}/x:/x", diff --git a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py index 58294543b..4ef2d16eb 100644 --- a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py +++ b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py @@ -461,106 +461,213 @@ async def test_marking_the_walls_verified_writes_nothing_unless_the_sandbox_is_t assert box.walls_verified is False -_WALLS_WRITER = "_mark_walls_verified" -#: Functions that may name WALLS_TAG without writing it: its refusal in attribution and the reattach that reads it, -#: which alone passes what it read to a handle's ``walls``. -_WALLS_READERS = {"_attribution_tags", "get_shared_box"} -#: Names whose spelling as a string would reach the walls tag or the tags around getattr and setattr. -_WALLS_NAMES = {"WALLS_TAG", "set_tags", "_walls"} - - -def _walls_tag_strays(name: str, text: str) -> list[str]: - """Each place in the module ``text`` that writes the walls tag, or a handle's record of it, outside its one writer. - - WALLS_TAG, bare or as an attribute, is named only in its definition, by the functions that read or refuse it, and - by the writer, the only one to put it in a dict or assign it. ``set_tags`` is reached, called or not, only on a +_MODAL_SANDBOX, _MODAL_VM_SANDBOX = modal_sandbox.__name__, modal_vm_sandbox.__name__ +#: The places, each a module and a qualified name in it, with a part in the walls tag: its one writer; the functions +#: that may name WALLS_TAG without writing it, its refusal in attribution and the reattach, which alone passes a +#: handle the ``walls`` it read from the tags; and the handle's ``__init__``, which alone stores that ``walls``. +_WALLS_WRITER = (_MODAL_VM_SANDBOX, "_mark_walls_verified") +_WALLS_REATTACH = (_MODAL_VM_SANDBOX, "ModalVmSandboxProvider.get_shared_box") +_WALLS_READERS = {(_MODAL_SANDBOX, "_attribution_tags"), _WALLS_REATTACH} +_HANDLE_INIT = (_MODAL_VM_SANDBOX, "ModalVmSandbox.__init__") +_TAG_DEFINITION = (_MODAL_SANDBOX, "") +#: The strings that would reach the walls tag, or the tags and the handle's record around getattr and setattr. +_WALLS_NAMES = {"WALLS_TAG", "set_tags", "_walls", WALLS_TAG} + + +def _places(tree: ast.Module) -> tuple[dict[int, str], dict[str, ast.AST]]: + """The qualified name, as ``Class.method``, of the class or function holding each node of ``tree``, "" at module + scope; and each function by its qualified name.""" + place, functions = {}, {} + + def visit(node: ast.AST, path: str) -> None: + for child in ast.iter_child_nodes(node): + place[id(child)] = path + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + inner = f"{path}.{child.name}" if path else child.name + if not isinstance(child, ast.ClassDef): + functions[inner] = child + visit(child, inner) + else: + visit(child, path) + + visit(tree, "") + return place, functions + + +def _folded(node: ast.AST) -> str | None: + """The string ``node`` makes from literals alone, joined by ``+`` or in an f-string; None for anything else.""" + if isinstance(node, ast.Constant): + return node.value if isinstance(node.value, str) else None + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): + left, right = _folded(node.left), _folded(node.right) + return None if left is None or right is None else left + right + if isinstance(node, ast.FormattedValue): + return _folded(node.value) if node.conversion == -1 and node.format_spec is None else None + if isinstance(node, ast.JoinedStr): + parts = [_folded(value) for value in node.values] + return None if None in parts else "".join(parts) + return None + + +def _walls_read_from_tags(function: ast.AST, value: ast.expr) -> bool: + """Whether ``value`` is ``tags.get(WALLS_TAG)``, for a ``tags`` that ``function`` assigns once, from + ``await _read_tags(...)``.""" + read = re.fullmatch(r"(\w+)\.get\(WALLS_TAG\)", ast.unparse(value)) + if read is None: + return False + stores = [n for n in ast.walk(function) if isinstance(n, ast.Name) and n.id == read[1] and isinstance(n.ctx, ast.Store)] + return len(stores) == 1 and any( + isinstance(n, ast.Assign) and n.targets == stores and re.fullmatch(r"await _read_tags\(.*\)", ast.unparse(n.value)) + for n in ast.walk(function)) + + +def _walls_tag_strays(module: str, text: str) -> list[str]: + """Each place in ``text``, the source of ``module``, that writes the walls tag, or a handle's record of it, outside + its one writer, each place matched by module and qualified name, never by name alone. + + WALLS_TAG, bare, as an attribute or imported under another name, is named only in its definition, by the readers, + and by the writer, the only one to put it in a dict or assign it. ``set_tags`` is reached, called or not, only on a Modal App, named ``app``, or by the writer. A handle's ``_walls`` is assigned only by the writer, or from the - ``walls`` argument in ``__init__``, and ``walls=`` is passed only by the readers. None of these names is spelled - as a string, as for getattr, except by the writer.""" + ``walls`` argument in the handle's ``__init__``; no call passes ``_walls=``, and ``walls=`` is passed only by the + reattach, with what it read from the tags. None of these names, nor the tag's value, is made as a string, quoted + any way, joined with ``+`` or in an f-string, outside the tag's definition. A module that mentions walls reaches + no object's ``__dict__`` or ``vars``, which would write ``_walls`` unnamed.""" tree = ast.parse(text) - owner = {} - for function in (n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))): - for node in ast.walk(function): - owner.setdefault(id(node), function.name) - writes, passthrough = set(), set() + place, functions = _places(tree) + writes, passthrough, definition = set(), set(), set() for node in ast.walk(tree): if isinstance(node, ast.Dict): writes |= {id(k) for k in node.keys if k is not None} if isinstance(node, ast.Subscript) and isinstance(node.ctx, ast.Store): writes.add(id(node.slice)) - if isinstance(node, ast.Assign) and owner.get(id(node)) == "__init__" \ + if isinstance(node, ast.Assign) and (module, place[id(node)]) == _HANDLE_INIT \ and isinstance(node.value, ast.Name) and node.value.id == "walls": passthrough |= {id(t) for t in node.targets} + if isinstance(node, ast.Assign) and (module, place[id(node)]) == _TAG_DEFINITION \ + and [ast.unparse(t) for t in node.targets] == ["WALLS_TAG"]: + definition |= {id(node.targets[0]), id(node.value)} + mentions_walls = "walls" in text.lower() stray = [] for node in ast.walk(tree): - function = owner.get(id(node)) - if function == _WALLS_WRITER: + where_in = place.get(id(node), "") + if (module, where_in) == _WALLS_WRITER: continue - where = f"{name}:{getattr(node, 'lineno', '?')} in {function or 'module scope'}" + where = f"{module}:{getattr(node, 'lineno', '?')} in {where_in or 'module scope'}" if (isinstance(node, ast.Name) and node.id == "WALLS_TAG") or \ (isinstance(node, ast.Attribute) and node.attr == "WALLS_TAG"): - if function is None and isinstance(node.ctx, ast.Store): - continue - if function not in _WALLS_READERS or id(node) in writes: + if id(node) not in definition and ((module, where_in) not in _WALLS_READERS or id(node) in writes): stray.append(f"{where} names WALLS_TAG") + if isinstance(node, ast.alias) and node.name == "WALLS_TAG" and node.asname not in (None, "WALLS_TAG"): + stray.append(f"{where} imports WALLS_TAG as {node.asname}") if isinstance(node, ast.Attribute) and node.attr == "set_tags" \ and not (isinstance(node.value, ast.Name) and node.value.id == "app"): stray.append(f"{where} sets tags") if isinstance(node, ast.Attribute) and node.attr == "_walls" and not isinstance(node.ctx, ast.Load) \ and id(node) not in passthrough: stray.append(f"{where} assigns _walls") - if isinstance(node, ast.keyword) and node.arg == "walls" and function not in _WALLS_READERS: + if isinstance(node, ast.keyword) and node.arg == "_walls": + stray.append(f"{where} passes _walls=") + if isinstance(node, ast.keyword) and node.arg == "walls" and not ( + (module, where_in) == _WALLS_REATTACH and _walls_read_from_tags(functions[where_in], node.value)): stray.append(f"{where} passes walls=") callee = getattr(node, "func", None) - if isinstance(node, ast.Call) and getattr(callee, "id", getattr(callee, "attr", None)) == "ModalVmSandbox" \ + callee_name = getattr(callee, "id", getattr(callee, "attr", None)) + if isinstance(node, ast.Call) and callee_name == "ModalVmSandbox" \ and (len(node.args) > 4 or any(k.arg is None for k in node.keywords)): stray.append(f"{where} may pass walls to ModalVmSandbox unnamed") - if isinstance(node, ast.Constant) and node.value in _WALLS_NAMES: - stray.append(f"{where} spells {node.value!r}") + if mentions_walls and ((isinstance(node, ast.Attribute) and node.attr == "__dict__") + or (isinstance(node, ast.Call) and callee_name == "vars")): + stray.append(f"{where} reaches an object's __dict__") + if (spelled := _folded(node)) in _WALLS_NAMES and id(node) not in definition: + stray.append(f"{where} spells {spelled!r}") return stray +def _module_name(source: Path, package: Path) -> str: + return ".".join(source.relative_to(package.parent).with_suffix("").parts) + + def test_only_the_walls_writer_writes_the_walls_tag_or_sets_a_sandboxs_tags(): package = Path(modal_sandbox.__file__).parents[2] + assert _module_name(Path(modal_vm_sandbox.__file__), package) == _MODAL_VM_SANDBOX stray = [] for source in package.rglob("*.py"): - text = source.read_text() - if f'"{WALLS_TAG}"' in text and source != Path(modal_sandbox.__file__): - stray.append(f"{source.name} spells the walls tag's value") - stray += _walls_tag_strays(source.name, text) + stray += _walls_tag_strays(_module_name(source, package), source.read_text()) assert stray == [] +_REATTACH = ("class ModalVmSandboxProvider:\n async def get_shared_box(self, sb):\n" + " tags = await _read_tags(sb)\n return ModalVmSandbox(sb, {{}}, shared_box_id='b', walls={})") +_PLANTED = "agent_env.planted" _PLANTED_WALLS_WRITES = { "tag in a dict, async set_tags": ("def f(sb):\n sb.set_tags.aio({WALLS_TAG: WALLS_VERSION})", "names WALLS_TAG"), "sync set_tags": ("def f(sb, tags):\n sb.set_tags(tags)", "sets tags"), "getattr set_tags": ("def f(sb, tags):\n getattr(sb, 'set_tags').aio(tags)", "spells 'set_tags'"), "set_tags held for later": ("def f(sb):\n write = sb.set_tags\n return write", "sets tags"), "WALLS_TAG as an attribute": ("def f(m, tags):\n tags[m.WALLS_TAG] = 'walls-v1'", "names WALLS_TAG"), - "reader writes the tag": ("def get_shared_box(m, tags):\n tags[m.WALLS_TAG] = 'v'", "names WALLS_TAG"), + "reader writes the tag": (f"{_REATTACH.format('tags.get(WALLS_TAG)')}\n tags[WALLS_TAG] = 'v'", + "names WALLS_TAG", _MODAL_VM_SANDBOX), "getattr WALLS_TAG": ("def f(m):\n return getattr(m, 'WALLS_TAG')", "spells 'WALLS_TAG'"), + "WALLS_TAG imported under another name": (f"from {_MODAL_SANDBOX} import WALLS_TAG as T\n" + "def f(sb, tags):\n sb.x({**tags, T: 'v'})", "imports WALLS_TAG as T"), + "WALLS_TAG defined again": ("WALLS_TAG = 'x'", "names WALLS_TAG"), + "tag value in single quotes": (f"def f(sb):\n sb.x({{'{WALLS_TAG}': 'v'}})", f"spells {WALLS_TAG!r}"), + "tag value in triple quotes": (f'def f(sb):\n sb.x({{"""{WALLS_TAG}""": "v"}})', f"spells {WALLS_TAG!r}"), + "tag value joined with +": (f"def f(sb):\n sb.x({{'{WALLS_TAG[:4]}' + '{WALLS_TAG[4:]}': 'v'}})", + f"spells {WALLS_TAG!r}"), + "tag value in an f-string": (f"def f(sb):\n sb.x({{f'{WALLS_TAG[:4]}{{\"{WALLS_TAG[4:]}\"}}': 'v'}})", + f"spells {WALLS_TAG!r}"), + "_walls joined with +": ("def f(box):\n setattr(box, '_wa' + 'lls', 1)", "spells '_walls'"), "constructor walls=": ("def f(sb):\n return ModalVmSandbox(sb, {}, walls=WALLS_VERSION)", "passes walls="), + "reattach passes a constant": (_REATTACH.format("WALLS_VERSION"), "passes walls=", _MODAL_VM_SANDBOX), + "reattach passes another tag": (_REATTACH.format("tags.get(SHARED_BOX_TAG)"), "passes walls=", _MODAL_VM_SANDBOX), + "reattach rewrites what it read": (f"{_REATTACH.format('tags.get(WALLS_TAG)')}\n tags = {{}}", + "passes walls=", _MODAL_VM_SANDBOX), + "reattach of another class": (_REATTACH.replace("ModalVmSandboxProvider", "Other").format("tags.get(WALLS_TAG)"), + "passes walls=", _MODAL_VM_SANDBOX), + "reattach in another module": (_REATTACH.format("tags.get(WALLS_TAG)"), "passes walls="), "constructor positional": ("def f(sb):\n return ModalVmSandbox(sb, {}, None, 'b', WALLS_VERSION)", "unnamed"), "constructor **kwargs": ("def f(sb, kw):\n return ModalVmSandbox(sb, {}, **kw)", "unnamed"), "_walls assigned": ("def f(box):\n box._walls = WALLS_VERSION", "assigns _walls"), "_walls set in __init__ to a constant": ("def __init__(self):\n self._walls = WALLS_VERSION", "assigns _walls"), + "_walls set in another class's __init__": ("class Other:\n def __init__(self, walls):\n self._walls = walls", + "assigns _walls", _MODAL_VM_SANDBOX), "setattr _walls": ("def f(box):\n setattr(box, '_walls', WALLS_VERSION)", "spells '_walls'"), + "vars(...).update(_walls=)": ("def f(box):\n vars(box).update(_walls=WALLS_VERSION)", "passes _walls="), + "vars in a module that mentions walls": ("def f(box, d):\n vars(box).update(d)\n return box.walls_verified", + "reaches an object's __dict__"), + "__dict__ in a module that mentions walls": ("def f(box, d):\n box.__dict__.update(d) # walls", + "reaches an object's __dict__"), + "writer's name in another module": ("def _mark_walls_verified(box):\n box._walls = WALLS_VERSION", + "assigns _walls"), + "writer's name as a method": ("class X:\n def _mark_walls_verified(self):\n self._walls = WALLS_VERSION", + "assigns _walls", _MODAL_VM_SANDBOX), + "inside the writer, a nested function": ("def _mark_walls_verified(box):\n def inner():\n" + " box._walls = WALLS_VERSION\n inner()", + "assigns _walls", _MODAL_VM_SANDBOX), } -@pytest.mark.parametrize("snippet, reason", _PLANTED_WALLS_WRITES.values(), ids=_PLANTED_WALLS_WRITES.keys()) -def test_the_walls_guard_catches_each_way_to_write_the_walls_outside_its_writer(snippet, reason): - assert any(reason in stray for stray in _walls_tag_strays("planted.py", snippet)) +@pytest.mark.parametrize("planted", _PLANTED_WALLS_WRITES.values(), ids=_PLANTED_WALLS_WRITES.keys()) +def test_the_walls_guard_catches_each_way_to_write_the_walls_outside_its_writer(planted): + snippet, reason, module = (*planted, _PLANTED)[:3] + assert any(reason in stray for stray in _walls_tag_strays(module, snippet)) def test_the_walls_guard_lets_the_writer_readers_and_handle_do_their_part(): - clean = ( - "WALLS_TAG = 'x'\n" - "def _mark_walls_verified(box, tags):\n" - " box._sb.set_tags.aio({**tags, WALLS_TAG: WALLS_VERSION})\n box._walls = WALLS_VERSION\n" - "def get_shared_box(sb, tags):\n return ModalVmSandbox(sb, {}, walls=tags.get(WALLS_TAG))\n" - "def _attribution_tags(key):\n return key == WALLS_TAG\n" - "def __init__(self, walls):\n self._walls = walls\n" - "def f(app, tags):\n app.set_tags.aio(tags)\n" - ) - assert _walls_tag_strays("clean.py", clean) == [] + clean = { + _MODAL_SANDBOX: ( + f"WALLS_TAG = '{WALLS_TAG}'\n" + "def _attribution_tags(key):\n return key == WALLS_TAG\n" + "def f(app, tags):\n app.set_tags.aio(tags)\n" + ), + _MODAL_VM_SANDBOX: ( + f"from {_MODAL_SANDBOX} import WALLS_TAG\n" + "async def _mark_walls_verified(box):\n" + " tags = await _read_tags(box._sb)\n" + " await box._sb.set_tags.aio({**tags, WALLS_TAG: WALLS_VERSION})\n box._walls = WALLS_VERSION\n" + f"{_REATTACH.format('tags.get(WALLS_TAG)')}\n" + "class ModalVmSandbox:\n def __init__(self, walls):\n self._walls = walls\n" + ), + } + assert [stray for module, text in clean.items() for stray in _walls_tag_strays(module, text)] == [] diff --git a/tst/unit/providers/sandbox_providers/shared_box_walls_test.py b/tst/unit/providers/sandbox_providers/shared_box_walls_test.py index df163b7f8..b6c25f969 100644 --- a/tst/unit/providers/sandbox_providers/shared_box_walls_test.py +++ b/tst/unit/providers/sandbox_providers/shared_box_walls_test.py @@ -6,6 +6,7 @@ import copy import itertools +import re import shlex import shutil import subprocess @@ -15,7 +16,9 @@ import pytest +from agent_env.providers.sandbox_providers.modal_vm_sandbox import ModalVmSandbox from agent_env.providers.sandbox_providers.shared_box_walls import ( + RP_FILTER_KNOBS, SLOT_BRIDGE_PREFIX, SLOT_COUNT, SLOT_RANGE, @@ -36,13 +39,15 @@ class IptablesFailed(Exception): class FakeIptables: - """The filter tables of iptables and ip6tables as the script leaves them, the script run line by line as - ``bash -e`` would, each restore all or nothing. ``fail_on`` makes the one command or restore line holding that text - fail, and ``missing`` names tools the box lacks. ``calls`` is every command run, in order.""" + """The filter tables of iptables and ip6tables, with each one's raw PREROUTING as ``raw:PREROUTING``, and the + kernel settings the script writes, as the script leaves them, run line by line as ``bash -e`` would, each restore + all or nothing. ``fail_on`` makes the one command or restore line holding that text fail, and ``missing`` names + tools the box lacks. ``calls`` is every command run, in order.""" def __init__(self, *, docker_user: bool = True, fail_on: str | None = None, missing: tuple[str, ...] = ()): self.tables: dict[int, dict[str, list[tuple[str, ...]]]] = { - family: {"INPUT": [], "FORWARD": []} for family in TOOLS.values()} + family: {"INPUT": [], "FORWARD": [], "raw:PREROUTING": []} for family in TOOLS.values()} + self.settings: dict[str, str] = {} if docker_user: self.tables[4]["DOCKER-USER"] = [("-j", "RETURN")] self.tables[4]["FORWARD"].append(("-j", "DOCKER-USER")) @@ -61,6 +66,8 @@ def run(self, script: str) -> None: if "<<'WALLS'" in line: body = list(itertools.takewhile(lambda body_line: body_line != "WALLS", lines)) ok = self._restore(line.split("<<")[0].strip(), body) + elif line.startswith("printf "): + ok = self._write(line) else: ok = any(self._command(part.replace("2>/dev/null", "")) for part in line.split(" || ")) if not ok: @@ -101,11 +108,21 @@ def _restore(self, command: str, body: list[str]) -> bool: table.update(staged) return True + def _write(self, line: str) -> bool: + self.calls.append(line) + value, path = re.fullmatch(r"printf (\S+) > (\S+)", line).groups() + if self.fail_on and self.fail_on in line: + return False + self.settings[path] = value + return True + def _command(self, command: str) -> bool: found = self._tool(command) if found is None: return False - (op, chain, *rest), table = found + (dash_t, table_name, op, chain, *rest), table = found + assert dash_t == "-t" + chain = chain if table_name == "filter" else f"{table_name}:{chain}" if chain not in table: return False rules, rest = table[chain], tuple(rest) @@ -118,9 +135,10 @@ def _command(self, command: str) -> bool: return True def verdict(self, packet: Packet, chain: str) -> str: - """``ACCEPT`` or ``DROP`` for ``packet`` entering ``chain``, whose policy, like every built-in chain's on the - box, accepts.""" - return "DROP" if self._walk(packet, chain) == "DROP" else "ACCEPT" + """``ACCEPT`` or ``DROP`` for ``packet`` arriving, through raw PREROUTING, at ``chain``, whose policy, like every + built-in chain's on the box, accepts.""" + dropped = "DROP" in (self._walk(packet, "raw:PREROUTING"), self._walk(packet, chain)) + return "DROP" if dropped else "ACCEPT" def _walk(self, packet: Packet, chain: str) -> str: for rule in self.tables[packet.dst.version][chain]: @@ -128,10 +146,10 @@ def _walk(self, packet: Packet, chain: str) -> str: if not _matches(packet, rule, options): continue target = options["-j"] - if target in ("DROP", "RETURN"): + if target in ("ACCEPT", "DROP", "RETURN"): return target - if self._walk(packet, target) == "DROP": - return "DROP" + if (verdict := self._walk(packet, target)) != "RETURN": + return verdict return "RETURN" @@ -260,7 +278,19 @@ def test_a_slot_reaches_no_private_link_local_or_carrier_address(walled, dst): def test_a_slot_reaches_the_internet_and_replies_to_what_reached_it(walled): assert walled.verdict(from_slot(45, "8.8.4.4", half="website"), "FORWARD") == "ACCEPT" assert walled.verdict(from_slot(45, "172.20.0.9", half="website", established=True), "FORWARD") == "ACCEPT" - assert walled.verdict(from_slot(45, half="website", established=True, **to_slot(2)), "FORWARD") == "ACCEPT" + assert walled.verdict(from_slot(45, half="website", established=True, **to_slot(45)), "FORWARD") == "ACCEPT" + + +def test_a_slot_that_forges_a_reply_into_another_slots_flow_is_dropped(walled): + for half, other_half in itertools.product(("env", "website"), repeat=2): + assert walled.verdict(from_slot(3, half=half, established=True, **to_slot(5, other_half)), "FORWARD") == "DROP" + assert walled.verdict(from_slot(3, established=True, src=host(slot_networks(5).env), **to_slot(5)), + "FORWARD") == "DROP" + + +def test_the_script_turns_on_strict_reverse_path_filtering_for_every_interface_and_every_new_one(walled): + assert RP_FILTER_KNOBS == ("/proc/sys/net/ipv4/conf/all/rp_filter", "/proc/sys/net/ipv4/conf/default/rp_filter") + assert walled.settings == {knob: "1" for knob in RP_FILTER_KNOBS} def test_a_slot_reaches_nothing_on_the_box_but_replies_to_the_box(walled): @@ -277,6 +307,17 @@ def test_no_ipv6_from_a_slot_is_forwarded_or_reaches_the_box_even_as_a_reply(wal assert walled.verdict(packet("fd00::9", "fe80::1", "aes3env", established=established), "INPUT") == "DROP" +@pytest.mark.parametrize("chain", ["FORWARD", "INPUT"]) +def test_no_ipv6_from_a_slot_gets_through_when_docker_puts_its_own_rules_above_the_walls(walled, chain): + walled.tables[6][chain].insert(0, ("-j", "ACCEPT")) + + out_iface = "eth0" if chain == "FORWARD" else None + for established in (False, True): + assert walled.verdict(packet("fd00::9", "2001:4860:4860::8888", "aes3env", out_iface, established=established), + chain) == "DROP" + assert walled.verdict(packet("2001:db8::2", "2001:db8::1", "eth0"), chain) == "ACCEPT" + + def test_traffic_not_from_a_slot_is_left_to_docker(walled): assert walled.verdict(packet("10.251.0.2", "172.21.0.9", "br-1a2b", "eth0", dport=80), "FORWARD") == "ACCEPT" assert walled.verdict(packet("172.21.0.9", in_iface="eth0", **to_slot(0)), "FORWARD") == "ACCEPT" @@ -308,6 +349,7 @@ def test_running_the_script_again_leaves_the_same_rules(walled): assert walled.chains["INPUT"] == [("-j", "AGENTENV-WALLS-IN")] assert walled.tables[6]["FORWARD"] == [("-j", "AGENTENV-WALLS-FWD")] assert walled.tables[6]["INPUT"] == [("-j", "AGENTENV-WALLS-IN")] + assert walled.tables[6]["raw:PREROUTING"] == [("-i", "aes+", "-j", "DROP")] def test_a_run_over_older_walls_replaces_their_rules(): @@ -364,15 +406,18 @@ def test_the_script_fails_before_dockerd_has_made_its_docker_user_chain(): def _run_under_bash(tmp_path, tools: tuple[str, ...], fail: str = "__never__") -> tuple[int, list[str]]: - """Run the script under bash with only ``tools``, as stubs, on its PATH: its exit code and the stubs' log.""" + """Run the script under bash with only ``tools``, as stubs, on its PATH, and its kernel settings written under + ``tmp_path``: its exit code and the stubs' log.""" bash, log = shutil.which("bash"), tmp_path / "log" (tmp_path / "bin").mkdir() for tool in tools: stub = tmp_path / "bin" / tool stub.write_text(_STUB.replace("BASH", bash).replace("LOG", str(log)).replace("FAIL", fail)) stub.chmod(0o755) - done = subprocess.run([bash, "-c", walls_firewall_script(RESOLVERS)], env={"PATH": str(tmp_path / "bin")}, - capture_output=True, text=True) + for knob in RP_FILTER_KNOBS: + (tmp_path / knob.lstrip("/")).parent.mkdir(parents=True) + script = walls_firewall_script(RESOLVERS).replace(" /proc/sys/", f" {tmp_path}/proc/sys/") + done = subprocess.run([bash, "-c", script], env={"PATH": str(tmp_path / "bin")}, capture_output=True, text=True) return done.returncode, log.read_text().splitlines() if log.exists() else [] @@ -383,12 +428,17 @@ def test_under_bash_each_restore_reads_its_whole_input_then_each_wall_is_hooked_ code, log = _run_under_bash(tmp_path, _ALL_TOOLS) script = walls_firewall_script(RESOLVERS).splitlines() + restore = script.index("iptables-restore -w --noflush <<'WALLS'") assert code == 0 + assert all((tmp_path / knob.lstrip("/")).read_text() == "1" for knob in RP_FILTER_KNOBS) assert log[:log.index("ip6tables-restore -w --noflush")] == \ - ["iptables-restore -w --noflush", *script[2:script.index("WALLS")]] + ["iptables-restore -w --noflush", *script[restore + 1:script.index("WALLS")]] assert [line for line in log if " -I " in line] == [ - "iptables -w -I DOCKER-USER 1 -j AGENTENV-WALLS-FWD", "iptables -w -I INPUT 1 -j AGENTENV-WALLS-IN", - "ip6tables -w -I FORWARD 1 -j AGENTENV-WALLS-FWD", "ip6tables -w -I INPUT 1 -j AGENTENV-WALLS-IN"] + "iptables -w -t filter -I DOCKER-USER 1 -j AGENTENV-WALLS-FWD", + "iptables -w -t filter -I INPUT 1 -j AGENTENV-WALLS-IN", + "ip6tables -w -t raw -I PREROUTING 1 -i aes+ -j DROP", + "ip6tables -w -t filter -I FORWARD 1 -j AGENTENV-WALLS-FWD", + "ip6tables -w -t filter -I INPUT 1 -j AGENTENV-WALLS-IN"] @pytest.mark.parametrize("tools, fail", [ @@ -420,22 +470,53 @@ async def test_applying_the_walls_reads_the_boxs_resolvers_and_runs_the_script_f assert box.exec_script.await_args.args == (walls_firewall_script(RESOLVERS),) +def _modal_vm_running(table: FakeIptables) -> MagicMock: + """A Modal VM sandbox whose exec reads the box's resolv.conf or runs a ``bash -c`` script against ``table``, + exiting 1, as bash would, when a line of it fails.""" + def process(code: int, stdout: str = "", stderr: str = "") -> MagicMock: + done = MagicMock() + done.wait.aio = AsyncMock(return_value=code) + done.stdout.read.aio = AsyncMock(return_value=stdout.encode()) + done.stderr.read.aio = AsyncMock(return_value=stderr.encode()) + return done + + def run(*command: str, text: bool) -> MagicMock: + if command == ("cat", "/etc/resolv.conf"): + return process(0, MODAL_RESOLV_CONF) + assert command[:2] == ("bash", "-c") + try: + table.run(command[2]) + except IptablesFailed as failed: + return process(1, stderr=f"failed: {failed}") + return process(0) + + sb = MagicMock(object_id="sb-1") + sb.exec.aio = AsyncMock(side_effect=run) + return sb + + @pytest.mark.asyncio -async def test_applying_the_walls_raises_when_a_restore_fails_and_keeps_the_walls_as_they_were(): +async def test_applying_the_walls_on_a_modal_vm_raises_when_a_restore_fails_and_keeps_the_walls_as_they_were(): table = FakeIptables() table.run(walls_firewall_script(RESOLVERS)) before = copy.deepcopy(table.tables) table.fail_on = "ip6tables-restore" - box = MagicMock(sandbox_id="sb-1") - box.exec_with_output = AsyncMock(return_value=(0, MODAL_RESOLV_CONF, "")) - box.exec_script = AsyncMock(side_effect=lambda script, **_: table.run(script)) - with pytest.raises(IptablesFailed): - await apply_walls_firewall(box) + with pytest.raises(RuntimeError, match=r"exit 1(.|\n)*ip6tables-restore"): + await apply_walls_firewall(ModalVmSandbox(_modal_vm_running(table), {}, shared_box_id="box-1")) assert table.tables == before +@pytest.mark.asyncio +async def test_applying_the_walls_on_a_modal_vm_sets_them(): + table = FakeIptables() + + await apply_walls_firewall(ModalVmSandbox(_modal_vm_running(table), {}, shared_box_id="box-1")) + + assert table.verdict(from_slot(0, **to_slot(1)), "FORWARD") == "DROP" + + @pytest.mark.asyncio async def test_applying_the_walls_raises_and_runs_nothing_when_resolv_conf_cant_be_read(): box = MagicMock(sandbox_id="sb-1") From b24271ff15795e6a5646875ca188dcc4d8afc621 Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Sat, 21 Nov 2026 01:24:20 -0500 Subject: [PATCH 09/15] feat(sandbox-providers): a shared box is tagged walls-verified only after its live self-test passes create_shared_box, set up for a gateway, now runs verify_walls on the new box once dockerd is up and the walls are applied. verify_walls runs one table of probes and, only after every one passes and both probe slots are torn down, calls _mark_walls_verified, the one writer of the walls tag. Any probe that answers otherwise, raises or runs past its own limit or the run's 5 minutes leaves the box untagged; create_shared_box ends it through terminate_shared_box and raises an error naming the probe. Each probe's result is logged as one structured event. The probes read the box's address, kernel and resolvers; check that Docker defaults to runsc with userns and no-new-privileges; check every walls rule with iptables -C, each chain's size, the hooks and rp_filter; bring up probe slots 0 and 1 from compose files slot_compose renders, with a door built on the box from this checkout's gateway sources; then check from slot 0 that slot 1's containers, its door through the box's address, the box, the private ranges and IPv6 are unreachable, that its own peer answers by name, that DNS answers through the mounted resolv.conf, that the internet answers (both skipped under an allowlisted egress), and that slot 1's door gives 401, 401, 200 and 400 to no token, a wrong one, the right one and a target that isn't a path. The live test, skipped unless AGENTENV_LIVE_MODAL=1, creates a box, checks the tag after a reattach, and checks what only a real box shows: the walls' own drop rules counted the blocked probes, the box's egress and its tunnel still work, no other interface is named aes*, and a container under gVisor can't open a raw socket. Co-Authored-By: Claude Opus 5.5 --- .../providers/sandbox_providers/AGENTS.md | 2 +- .../sandbox_providers/modal_vm_sandbox.py | 39 +- .../sandbox_providers/shared_box_selftest.py | 417 ++++++++++++++++++ .../sandbox_providers/shared_box_walls.py | 43 +- .../shared_box_walls_live_test.py | 161 +++++++ .../modal_shared_box_test.py | 34 +- .../shared_box_selftest_test.py | 254 +++++++++++ .../shared_box_walls_test.py | 87 ++++ 8 files changed, 1018 insertions(+), 19 deletions(-) create mode 100644 src/agent_env/providers/sandbox_providers/shared_box_selftest.py create mode 100644 tst/integration/providers/sandbox_providers/shared_box_walls_live_test.py create mode 100644 tst/unit/providers/sandbox_providers/shared_box_selftest_test.py diff --git a/src/agent_env/providers/sandbox_providers/AGENTS.md b/src/agent_env/providers/sandbox_providers/AGENTS.md index a6494bdc6..c5b499a53 100644 --- a/src/agent_env/providers/sandbox_providers/AGENTS.md +++ b/src/agent_env/providers/sandbox_providers/AGENTS.md @@ -54,7 +54,7 @@ with `exposed_ports=[port]` and returns the VM, and the deploy then loads and st | `create_sandbox(*, image_name, port, env, cpu, memory, disk_size_gb, timeout, attribution, network_policy) -> Sandbox` | yes (a VM backend wraps `create_vm`) | an agent's sandbox (`provider.create_sandbox`); `create_container` of a container-only backend | | `get_sandbox(sandbox_id) -> Sandbox` | yes | every step after the one that created the sandbox, and teardown | | `terminate_sandbox(sandbox_id)` | no | teardown. The default calls `get_sandbox` then `terminate()`, and treats `SandboxNotFoundError` as done; override when you can terminate without a live handle | -| `create_shared_box(box_id, *, cpu, memory, timeout, exposed_ports, setup_for_gateway, attribution, network_policy) -> VmSandbox` | no | nothing yet: a VM for several tasks' slots. The default raises `NotImplementedError`; `modal_vm` tags the VM with `SHARED_BOX_TAG` at create, refuses to end it from its handle's `terminate()` or `terminate_sandbox`, raising `SharedBoxTerminateRefused`, and ends it only through `terminate_shared_box(sandbox_id, box_id)`. Its VM runs `_SHARED_BOX_IMAGE`, every container under gVisor in a user namespace, and set up for a gateway it gets the firewall in `shared_box_walls.py` that walls its slots apart. `get_shared_box(sandbox_id, box_id)` reattaches to one; its handle's `walls_verified` is true only when the box carries `WALLS_TAG` at the current `WALLS_VERSION`, which nothing writes yet | +| `create_shared_box(box_id, *, cpu, memory, timeout, exposed_ports, setup_for_gateway, attribution, network_policy) -> VmSandbox` | no | nothing yet: a VM for several tasks' slots. The default raises `NotImplementedError`; `modal_vm` tags the VM with `SHARED_BOX_TAG` at create, refuses to end it from its handle's `terminate()` or `terminate_sandbox`, raising `SharedBoxTerminateRefused`, and ends it only through `terminate_shared_box(sandbox_id, box_id)`. Its VM runs `_SHARED_BOX_IMAGE`, every container under gVisor in a user namespace, and set up for a gateway it gets the firewall in `shared_box_walls.py` that walls its slots apart, then `verify_walls` runs the probes in `shared_box_selftest.py`: once every one passes and its two probe slots are torn down, it tags the box with `WALLS_TAG` at the current `WALLS_VERSION`, the only writer of that tag; a box whose probe fails is ended through `terminate_shared_box` and the error names the probe. `get_shared_box(sandbox_id, box_id)` reattaches to one; its handle's `walls_verified` is true only when the box carries that tag | | `create_container(...)` | inherited | containers that run an env or agent image. Override only when the platform boots images natively. Its `shm_mb` is the MiB the container's `/dev/shm` holds (`--shm-size` on the default VM path), passed only where `SHARED_MEMORY` is on | | `reset_container(sandbox, *, image_name, port, env, shm_mb)` | inherited | a computer env's reset, which replaces the container `create_container` ran with a fresh one on the same sandbox and port, its `/dev/shm` as before. The default works on a VM backend; one whose sandbox is the container itself raises `NotImplementedError` | | `native_platforms()` | no | a computer env's deploy and gate 3, which boot a build only on a provider that runs its arch without emulation. The default is `linux/amd64`; local Docker returns this machine's | diff --git a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py index 4b68b0324..0ef091924 100644 --- a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py +++ b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py @@ -66,6 +66,7 @@ from agent_env.providers.sandbox_providers.shared_box_walls import apply_walls_firewall if TYPE_CHECKING: + from agent_env.providers.sandbox_providers.shared_box_selftest import ProbeResult from agent_env.store.object_store import ObjectStore logger = logging.getLogger(__name__) @@ -463,15 +464,27 @@ async def create_shared_box( network_policy: Optional[NetworkPolicy] = None, ) -> ModalVmSandbox: """A VM running Docker with every container under gVisor, tagged as shared box ``box_id`` at create, since a - later ``set_tags`` would replace its attribution tags; set up for a gateway, it has the walls between its slots - too, though not yet verified. Its handle's terminate, and ``terminate_sandbox``, refuse to end it: only - ``terminate_shared_box`` does.""" + later ``set_tags`` would replace its attribution tags. Set up for a gateway, it has the walls between its slots + too, and returns only once ``verify_walls`` has verified them; a box whose walls fail it is ended through + ``terminate_shared_box`` and its error raised. Its handle's terminate, and ``terminate_sandbox``, refuse to end + it: only ``terminate_shared_box`` does.""" if not _MODAL_TAG_KEY.fullmatch(box_id): raise ValueError(f"shared box id {box_id!r} can't be a Modal tag: use 1-63 of a-z A-Z 0-9 . _ -") - return await self._created(_KEEPALIVE_CMD, _SHARED_BOX_IMAGE, cpu=cpu, memory=memory, timeout=timeout, - ports=list(exposed_ports or []), attribution=attribution, - network_policy=network_policy, setup_for_gateway=setup_for_gateway, - idle_timeout=self._idle_timeout, runtime="vm", shared_box_id=box_id) + box = await self._created(_KEEPALIVE_CMD, _SHARED_BOX_IMAGE, cpu=cpu, memory=memory, timeout=timeout, + ports=list(exposed_ports or []), attribution=attribution, + network_policy=network_policy, setup_for_gateway=setup_for_gateway, + idle_timeout=self._idle_timeout, runtime="vm", shared_box_id=box_id) + if setup_for_gateway: + try: + await verify_walls(box) + except BaseException: + try: + await self.terminate_shared_box(box.sandbox_id, box_id) + except Exception as e: + logger.warning(f"Failed to end shared box {box_id} ({box.sandbox_id}) after its walls weren't " + f"verified: {type(e).__name__}: {e}") + raise + return box async def terminate_shared_box(self, sandbox_id: str, box_id: str) -> None: """End shared box ``box_id``, the sandbox ``sandbox_id``, and every slot on it. A sandbox tagged as another box, @@ -597,6 +610,18 @@ async def _tunnel_urls(sb: modal.Sandbox) -> dict[int, str]: return {p: _tunnel_url(t) for p, t in (await sb.tunnels.aio()).items()} +async def verify_walls(box: ModalVmSandbox) -> list[ProbeResult]: + """Run every probe of shared box ``box``'s walls, a new box whose dockerd is up and whose walls are applied, and + once all have passed and their probe slots are gone, tag the box as verified: the only way the tag is written. + Returns each probe's result; raises WallsNotVerified, tagging nothing, at the first probe that fails.""" + # Imported here: the probes tear their slots down with the gateway provider, which imports this module. + from agent_env.providers.sandbox_providers.shared_box_selftest import run_walls_probes + + results = await run_walls_probes(box, dockerd_config=_SHARED_BOX_DOCKERD_CONFIG) + await _mark_walls_verified(box) + return results + + async def _mark_walls_verified(box: ModalVmSandbox) -> None: """Tag shared box ``box`` as having walls that passed the current WALLS_VERSION's self-test, keeping its other tags, as ``set_tags`` replaces them all. The one writer of WALLS_TAG, for the self-test to call once its probes pass.""" diff --git a/src/agent_env/providers/sandbox_providers/shared_box_selftest.py b/src/agent_env/providers/sandbox_providers/shared_box_selftest.py new file mode 100644 index 000000000..4b787b028 --- /dev/null +++ b/src/agent_env/providers/sandbox_providers/shared_box_selftest.py @@ -0,0 +1,417 @@ +"""The probes of a new shared box's walls, run once dockerd is up and the walls are applied, before any slot is. + +The probes run in order from one table, each a small function whose answer is a short string that passes only if it is +one of the probe's expected answers. They check Docker's settings, the firewall's rules, then bring up two probe slots, +0 and 1, from compose files the real ``slot_compose`` renders, and check from slot 0 that nothing outside it is +reachable but its own services, the box's resolvers and the internet, that the door of slot 1 takes only its token, +and that both slots tear down. Every container is the pinned Python image the gateway is built on; the door's is that +image with the door's three dependencies, pinned, and the gateway package's sources from this checkout, built on the +box, so the probe runs this checkout's ``door.py`` with the command ``slot_compose`` gives it. + +Any probe that answers otherwise, raises or runs out of time ends the run: the box's walls are not verified. +""" + +from __future__ import annotations + +import asyncio +import json +import logging +import secrets +import shlex +import time +from collections.abc import Awaitable, Callable, Mapping +from dataclasses import dataclass +from pathlib import Path + +import yaml + +from agent_env.env import gateway as gateway_package +from agent_env.env.gateway.constants import SLOT_TOKEN_HEADER +from agent_env.providers.env_providers.constants import ENV_NETWORK +from agent_env.providers.env_providers.env_gateway_provider import tear_down_slot +from agent_env.providers.env_providers.slot_compose import ( + DOOR_SERVICE_NAME, + SLOT_RUNTIME, + resolv_conf_path, + slot_compose, + slot_resolv_conf, +) +from agent_env.providers.env_providers.stack_layout import StackLayout +from agent_env.providers.sandbox_providers.sandbox import VmSandbox +from agent_env.providers.sandbox_providers.shared_box_walls import upstream_resolvers, walls_check_script + +logger = logging.getLogger(__name__) + +WALLS_PROBE_EVENT = "agent_env.shared_box_walls_probe" +#: Every probe's answer is the last line its script prints; this line before it names the probe, so a log of the box's +#: execs, or a test's fake box, can tell which probe ran. +PROBE_MARKER = "# walls probe: " +#: The whole run's limit, in seconds, past which the probe running is cut off and the walls are not verified. +TOTAL_BUDGET_S = 300.0 + +#: The gateway image's base, by digest: every probe container runs it. +PROBE_IMAGE = ("public.ecr.aws/docker/library/python:3.11-slim" + "@sha256:c20888b6acdd1e63e1c433a185bf3ad162c0288fe484616ce062e0d28add2900") +_DOOR_DEPENDENCIES = ("httpx==0.28.1", "uvicorn==0.49.0", "websockets==17.2") +_DOOR_SOURCES = ("__init__.py", "constants.py", "door.py") +DOOR_IMAGE = "agentenv-walls-probe-door:local" +_PROBE_SLOTS = (0, 1) +_PROBER, _PEER = "probe", "web" +_PEER_PORT = 8080 +#: Slot 0's scratch dir, which its teardown removes. +_DOOR_CONTEXT = StackLayout.for_slot(0).scratch_path("door") +_PUBLIC_HOST = "www.google.com" +_CONNECTIVITY_URL = f"https://{_PUBLIC_HOST}/generate_204" +_PUBLIC_IPV6 = ("[2606:4700:4700::1111]:443", "[2001:4860:4860::8888]:443") +_BLOCKED = frozenset({"blocked"}) + + +class WallsNotVerified(RuntimeError): + """A probe of a shared box's walls answered otherwise than expected, raised or ran out of time. ``results`` holds + every probe that ran, the failed one last.""" + + def __init__(self, sandbox_id: str, results: list[ProbeResult]): + self.results = results + failed = results[-1] + super().__init__(f"the walls of shared box {sandbox_id} failed the probe {failed.name}: expected " + f"{' or '.join(sorted(failed.expected))}, got {failed.observed!r}") + + +@dataclass(frozen=True) +class ProbeResult: + name: str + expected: frozenset[str] + observed: str + seconds: float + + @property + def passed(self) -> bool: + return self.observed in self.expected + + +@dataclass(frozen=True) +class BoxFacts: + """What the probes need to know of the box: its own IPv4 address, its kernel's release and its resolv.conf.""" + + address: str + kernel: str + resolv_conf: str + + +@dataclass(frozen=True) +class ProbeSlot: + layout: StackLayout + compose: str + door_token: str + peer_address: str + door_address: str + + @property + def door_port(self) -> int: + return self.layout.host_port(_PEER_PORT) + + def exec_in_prober(self, *argv: str) -> str: + return shlex.join([*self.layout.compose_argv, "exec", "-T", _PROBER, *argv]) + + +@dataclass(frozen=True) +class ProbePlan: + facts: BoxFacts + slots: tuple[ProbeSlot, ProbeSlot] + no_new_privileges: bool + open_egress: bool + + @property + def inside(self) -> ProbeSlot: + return self.slots[0] + + @property + def other(self) -> ProbeSlot: + return self.slots[1] + + +@dataclass(frozen=True) +class Probe: + name: str + expected: frozenset[str] + timeout_s: float + run: Callable[[VmSandbox, ProbePlan], Awaitable[str]] + #: Run only when the box's egress is open: under an allowlist, the internet and its names aren't the walls' to give. + needs_open_egress: bool = False + + +async def run_walls_probes(box: VmSandbox, *, dockerd_config: Mapping) -> list[ProbeResult]: + """Every probe's result, in order, once all have passed on ``box``, a new shared box whose dockerd is up, run + from ``dockerd_config``, and whose walls are applied; raises WallsNotVerified at the first that doesn't. It leaves + no probe slot behind when they pass; when one fails, the caller ends the box.""" + deadline = time.monotonic() + TOTAL_BUDGET_S + results: list[ProbeResult] = [] + + async def attempt(name: str, expected: frozenset[str], timeout_s: float, run: Callable[[], Awaitable[str]]) -> None: + started = time.monotonic() + try: + observed = await asyncio.wait_for(run(), timeout=max(0.0, min(timeout_s, deadline - started))) + except asyncio.TimeoutError: + observed = f"no answer within {min(timeout_s, deadline - started):.0f}s" + except Exception as e: + observed = f"raised {type(e).__name__}: {e}" + result = ProbeResult(name, expected, observed, time.monotonic() - started) + results.append(result) + _log(box, result) + if not result.passed: + raise WallsNotVerified(box.sandbox_id, results) + + plan: ProbePlan | None = None + + async def read_plan() -> str: + nonlocal plan + plan = await _plan(box, dockerd_config) + return "read" + + await attempt("box_facts", frozenset({"read"}), 30, read_plan) + for probe in PROBES: + if probe.needs_open_egress and not plan.open_egress: + logger.info(f"walls probe {probe.name} not run on {box.sandbox_id}: its egress is allowlisted") + continue + await attempt(probe.name, probe.expected, probe.timeout_s, lambda probe=probe: probe.run(box, plan)) + return results + + +def _log(box: VmSandbox, result: ProbeResult) -> None: + logger.info(f"walls probe {result.name} on {box.sandbox_id}: {'passed' if result.passed else 'FAILED'}, got " + f"{result.observed!r} in {result.seconds:.1f}s", + extra={"event": WALLS_PROBE_EVENT, "sandbox_id": box.sandbox_id, "probe": result.name, + "passed": result.passed, "expected": sorted(result.expected), "observed": result.observed, + "seconds": round(result.seconds, 2)}) + + +_FACTS = """ +import json, platform, socket +s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) +s.connect(("1.1.1.1", 53)) +print(json.dumps({"address": s.getsockname()[0], "kernel": platform.release(), + "resolv_conf": open("/etc/resolv.conf").read()})) +""" + + +async def _plan(box: VmSandbox, dockerd_config: Mapping) -> ProbePlan: + answer = await _answer(box, "box_facts", shlex.join(["python3", "-c", _FACTS])) + try: + facts = BoxFacts(**json.loads(answer)) + except (ValueError, TypeError): + raise RuntimeError(f"the box's address, kernel and resolv.conf weren't read: {answer}") from None + policy = box.network_policy + return ProbePlan(facts, tuple(_probe_slot(StackLayout.for_slot(i)) for i in _PROBE_SLOTS), + no_new_privileges=bool(dockerd_config.get("no-new-privileges")), + open_egress=policy is None or not policy.restricts_egress) + + +def _probe_slot(layout: StackLayout) -> ProbeSlot: + """A slot of a prober, which runs nothing, and a peer, a web server whose port the door takes over.""" + stack = {"services": { + _PROBER: {"image": PROBE_IMAGE, "command": ["sleep", "infinity"], "networks": [ENV_NETWORK]}, + _PEER: {"image": PROBE_IMAGE, "command": ["python", "-m", "http.server", "--bind", "0.0.0.0", str(_PEER_PORT)], + "networks": [ENV_NETWORK], "ports": [f"{layout.host_port(_PEER_PORT)}:{_PEER_PORT}"]}, + }} + token = secrets.token_urlsafe(32) + compose = slot_compose(yaml.safe_dump(stack), layout, door_image=DOOR_IMAGE, door_token=token) + services = yaml.safe_load(compose)["services"] + return ProbeSlot(layout, compose, token, services[_PEER]["networks"][ENV_NETWORK]["ipv4_address"], + services[DOOR_SERVICE_NAME]["networks"][ENV_NETWORK]["ipv4_address"]) + + +async def _answer(box: VmSandbox, name: str, script: str) -> str: + """The last line ``script``, run as probe ``name``, printed, or how it failed.""" + code, stdout, stderr = await box.exec_with_output("bash", "-c", f"{PROBE_MARKER}{name}\n{script}") + if code: + return f"exit {code}: {(stderr.strip() or stdout.strip())[-300:]}" + lines = stdout.strip().splitlines() + return lines[-1].strip() if lines else "" + + +_DOCKER_INFO = """ +import json, sys +info = json.load(sys.stdin) +options = info.get("SecurityOptions") or [] +problems = [] +if info.get("DefaultRuntime") != sys.argv[1]: + problems.append("the default runtime is " + str(info.get("DefaultRuntime"))) +if not any(option.startswith("name=userns") for option in options): + problems.append("no userns in " + str(options)) +if sys.argv[2] == "1" and "name=no-new-privileges" not in options: + problems.append("no no-new-privileges in " + str(options)) +print("; ".join(problems) or "ok") +""" + + +async def _docker_runs_gvisor_in_a_user_namespace(box: VmSandbox, plan: ProbePlan) -> str: + check = shlex.join(["python3", "-c", _DOCKER_INFO, SLOT_RUNTIME, "1" if plan.no_new_privileges else "0"]) + return await _answer(box, "docker_info", f"set -o pipefail\ndocker info --format '{{{{json .}}}}' | {check}") + + +async def _firewall_holds_the_walls(box: VmSandbox, plan: ProbePlan) -> str: + return await _answer(box, "firewall", walls_check_script(upstream_resolvers(plan.facts.resolv_conf))) + + +async def _probe_slots_come_up(box: VmSandbox, plan: ProbePlan) -> str: + files = {f"{_DOOR_CONTEXT}/Dockerfile": _door_dockerfile().encode()} + files |= {f"{_DOOR_CONTEXT}/gateway/{name}": (Path(gateway_package.__file__).parent / name).read_bytes() + for name in _DOOR_SOURCES} + for slot in plan.slots: + files[slot.layout.compose_file] = slot.compose.encode() + files[resolv_conf_path(slot.layout)] = slot_resolv_conf(plan.facts.resolv_conf).encode() + for path, data in files.items(): + await box.write_host_file(data, path) + up = [f"{slot.layout.compose_command} up -d --quiet-pull" for slot in plan.slots] + return await _answer(box, "probe_slots_up", "\n".join( + ["set -eu", f"docker build -q -t {DOOR_IMAGE} {_DOOR_CONTEXT} >/dev/null", *up, "echo up"])) + + +def _door_dockerfile() -> str: + return "\n".join([f"FROM {PROBE_IMAGE}", f"RUN pip install --no-cache-dir {' '.join(_DOOR_DEPENDENCIES)}", + "COPY gateway /app/gateway", "ENV PYTHONPATH=/app", ""]) + + +async def _slots_run_under_gvisor(box: VmSandbox, plan: ProbePlan) -> str: + listed = [f"ids=\"$ids $(docker ps -q --filter label=com.docker.compose.project={slot.layout.compose_project})\"" + for slot in plan.slots] + return await _answer(box, "slots_under_gvisor", "\n".join([ + "set -eu", 'ids=""', *listed, + '[ -n "$(echo $ids)" ] || { echo "no probe container is running"; exit 0; }', + "others=$(docker inspect -f '{{.Name}} {{.HostConfig.Runtime}}' $ids | grep -v ' " + SLOT_RUNTIME + "$' || true)", + f"kernel=$({plan.inside.exec_in_prober('uname', '-r')})", + 'if [ -n "$others" ]; then echo "not under ' + SLOT_RUNTIME + ': $others"', + f'elif [ "$kernel" = {shlex.quote(plan.facts.kernel)} ]; then echo "a slot runs the box\'s kernel"', + "else echo gvisor; fi", + ])) + + +_GET = """ +import sys, time, urllib.request +deadline = time.monotonic() + float(sys.argv[2]) +while True: + try: + print(urllib.request.urlopen(sys.argv[1], timeout=5).status) + break + except Exception as e: + if time.monotonic() > deadline: + print(type(e).__name__ + ": " + str(e)) + break + time.sleep(1) +""" + + +def _peer_by_name(index: int) -> Callable[[VmSandbox, ProbePlan], Awaitable[str]]: + async def run(box: VmSandbox, plan: ProbePlan) -> str: + slot = plan.slots[index] + url = f"http://{_PEER}:{_PEER_PORT}/" + return await _answer(box, f"slot_{index}_peer_by_name", slot.exec_in_prober("python", "-c", _GET, url, "30")) + return run + + +_REACH = """ +import socket, sys +reached = [] +for target in sys.argv[1:]: + host, _, port = target.rpartition(":") + host = host.strip("[]") + try: + with socket.socket(socket.AF_INET6 if ":" in host else socket.AF_INET) as s: + s.settimeout(3) + s.connect((host, int(port))) + reached.append(target + " open") + except ConnectionRefusedError: + reached.append(target + " refused") + except OSError: + pass +print("reached " + ", ".join(reached) if reached else "blocked") +""" + + +def _blocked_from_inside(name: str, targets: Callable[[ProbePlan], list[str]]) -> Probe: + """A probe that slot 0's prober reaches none of ``targets``: a connection that opens or is refused got there.""" + async def run(box: VmSandbox, plan: ProbePlan) -> str: + return await _answer(box, name, plan.inside.exec_in_prober("python", "-c", _REACH, *targets(plan))) + return Probe(name, _BLOCKED, 45, run) + + +_DNS = """ +import socket, sys +have = [line.split()[1] for line in open("/etc/resolv.conf") if line.split()[:1] == ["nameserver"]] +if have != sys.argv[2:]: + print("resolv.conf names " + " ".join(have)) +else: + try: + socket.getaddrinfo(sys.argv[1], 443, socket.AF_INET) + print("answers") + except OSError as e: + print(type(e).__name__ + ": " + str(e)) +""" + + +async def _dns_answers_through_the_mounted_resolv_conf(box: VmSandbox, plan: ProbePlan) -> str: + resolvers = [str(r) for r in upstream_resolvers(plan.facts.resolv_conf)] + return await _answer(box, "dns", plan.inside.exec_in_prober("python", "-c", _DNS, _PUBLIC_HOST, *resolvers)) + + +async def _internet_is_reachable(box: VmSandbox, plan: ProbePlan) -> str: + return await _answer(box, "internet", plan.inside.exec_in_prober("python", "-c", _GET, _CONNECTIVITY_URL, "30")) + + +_DOOR = """ +import http.client, sys, time +host, port, header, token = sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4] + +def status(target, value): + connection = http.client.HTTPConnection(host, port, timeout=5) + try: + connection.request("GET", target, headers={} if value is None else {header: value}) + return connection.getresponse().status + finally: + connection.close() + +deadline = time.monotonic() + 30 +while True: + try: + status("/", None) + break + except OSError: + if time.monotonic() > deadline: + raise + time.sleep(1) +print(status("/", None), status("/", "wrong-" + token), status("/", token), status("//elsewhere/x", token)) +""" + + +async def _door_takes_only_its_token(box: VmSandbox, plan: ProbePlan) -> str: + slot = plan.other + argv = ["python3", "-c", _DOOR, plan.facts.address, str(slot.door_port), SLOT_TOKEN_HEADER, slot.door_token] + return await _answer(box, "door", shlex.join(argv)) + + +async def _probe_slots_tear_down(box: VmSandbox, plan: ProbePlan) -> str: + for slot in plan.slots: + await tear_down_slot(box, slot.layout) + return "torn down" + + +PROBES: tuple[Probe, ...] = ( + Probe("docker_info", frozenset({"ok"}), 30, _docker_runs_gvisor_in_a_user_namespace), + Probe("firewall", frozenset({"ok"}), 60, _firewall_holds_the_walls), + Probe("probe_slots_up", frozenset({"up"}), 180, _probe_slots_come_up), + Probe("slots_under_gvisor", frozenset({"gvisor"}), 30, _slots_run_under_gvisor), + Probe("slot_0_peer_by_name", frozenset({"200"}), 45, _peer_by_name(0)), + Probe("slot_1_peer_by_name", frozenset({"200"}), 45, _peer_by_name(1)), + _blocked_from_inside("a_to_b_container_ip", lambda plan: [ + f"{plan.other.peer_address}:{_PEER_PORT}", f"{plan.other.door_address}:{plan.other.door_port}"]), + _blocked_from_inside("a_to_b_door_via_box_ip", lambda plan: [f"{plan.facts.address}:{plan.other.door_port}"]), + _blocked_from_inside("a_to_box_ip", lambda plan: [f"{plan.facts.address}:{port}" for port in (22, 80, 2375)]), + _blocked_from_inside("a_to_private_ranges", lambda plan: [ + "10.0.0.1:80", "169.254.169.254:80", "192.168.0.1:80", "100.64.0.1:80", + *(f"{r}:80" for r in upstream_resolvers(plan.facts.resolv_conf))]), + _blocked_from_inside("a_ipv6", lambda plan: list(_PUBLIC_IPV6)), + Probe("dns", frozenset({"answers"}), 30, _dns_answers_through_the_mounted_resolv_conf, needs_open_egress=True), + Probe("internet", frozenset({"204"}), 45, _internet_is_reachable, needs_open_egress=True), + Probe("door", frozenset({"401 401 200 400"}), 45, _door_takes_only_its_token), + Probe("probe_slots_torn_down", frozenset({"torn down"}), 60, _probe_slots_tear_down), +) diff --git a/src/agent_env/providers/sandbox_providers/shared_box_walls.py b/src/agent_env/providers/sandbox_providers/shared_box_walls.py index 24a294965..4583e9397 100644 --- a/src/agent_env/providers/sandbox_providers/shared_box_walls.py +++ b/src/agent_env/providers/sandbox_providers/shared_box_walls.py @@ -13,6 +13,7 @@ from __future__ import annotations import ipaddress +import shlex from ipaddress import IPv4Address, IPv4Network from typing import NamedTuple, Sequence @@ -97,11 +98,8 @@ def _restore_input(chains: dict[str, list[str]]) -> str: return "\n".join(lines) + "\n" -def walls_firewall_script(resolvers: Sequence[IPv4Address]) -> str: - """A root shell script that sets the box's firewall to the walls for every slot, the same rules however often it - runs. It turns on strict reverse-path filtering, then each of iptables and ip6tables refills the walls' chains in - one transaction, so a run that fails leaves the walls as they were, then each hook is added once. A box without - ip6tables fails the script. +def walls_rules(resolvers: Sequence[IPv4Address]) -> dict[str, dict[str, list[str]]]: + """The rules of each walls chain, in order, for each of iptables and ip6tables. Slot-to-slot traffic is decided before conntrack is asked whether a packet is a reply: no real flow crosses slots, so a slot that forges a reply into another slot's flow is dropped like any other packet between them.""" @@ -114,18 +112,49 @@ def walls_firewall_script(resolvers: Sequence[IPv4Address]) -> str: forward += [f"{from_slot} -o {SLOT_BRIDGE_PREFIX}+ -j DROP", f"{_ESTABLISHED} -j RETURN"] forward += [f"{from_slot} -d {r}/32 -p {proto} --dport 53 -j RETURN" for r in resolvers for proto in ("udp", "tcp")] forward += [f"{from_slot} -d {n} -j DROP" for n in _PRIVATE_RANGES] - tables = { + return { "iptables": {FORWARD_CHAIN: forward, INPUT_CHAIN: [f"{_ESTABLISHED} -j RETURN", f"{from_slot} -j DROP"]}, "ip6tables": {FORWARD_CHAIN: [f"{from_slot} -j DROP"], INPUT_CHAIN: [f"{from_slot} -j DROP"]}, } + + +def walls_firewall_script(resolvers: Sequence[IPv4Address]) -> str: + """A root shell script that sets the box's firewall to the walls for every slot, the same rules however often it + runs. It turns on strict reverse-path filtering, then each of iptables and ip6tables refills the walls' chains in + one transaction, so a run that fails leaves the walls as they were, then each hook is added once. A box without + ip6tables fails the script.""" lines = ["set -eu", *(f"printf 1 > {knob}" for knob in RP_FILTER_KNOBS)] - for tool, chains in tables.items(): + for tool, chains in walls_rules(resolvers).items(): lines += [f"{tool}-restore -w --noflush <<'WALLS'", _restore_input(chains) + "WALLS"] for tool, table, parent, rule in _HOOKS: lines.append(f"{tool} -w -t {table} -C {parent} {rule} 2>/dev/null || {tool} -w -t {table} -I {parent} 1 {rule}") return "\n".join(lines) + "\n" +def walls_check_script(resolvers: Sequence[IPv4Address]) -> str: + """A root shell script that prints ``ok`` when the box's firewall is the walls ``walls_firewall_script`` sets: each + walls chain holds its rules and no others, each hook is in place and reverse-path filtering is strict. Otherwise + its last line counts the problems and names the first. It changes nothing. + + Each rule is checked with ``-C``, which compares rules as iptables parsed them rather than as text, so the check + doesn't depend on how ``-S`` would print them. It doesn't check the rules' order.""" + lines = ['problems=0 first=""', 'problem() { problems=$((problems + 1)); [ -n "$first" ] || first="$1"; }'] + for tool, chains in walls_rules(resolvers).items(): + for chain, rules in chains.items(): + for rule in rules: + what = shlex.quote(f"{tool} {chain} lacks {rule}") + lines.append(f"{tool} -w -C {chain} {rule} 2>/dev/null || problem {what}") + size = shlex.quote(f"{tool} {chain} doesn't hold exactly its {len(rules)} rules") + lines.append(f'[ "$({tool} -w -S {chain} 2>/dev/null | wc -l)" -eq {len(rules) + 1} ] || problem {size}') + for tool, table, parent, rule in _HOOKS: + what = shlex.quote(f"{tool} {table} {parent} lacks {rule}") + lines.append(f"{tool} -w -t {table} -C {parent} {rule} 2>/dev/null || problem {what}") + for knob in RP_FILTER_KNOBS: + lines.append(f'[ "$(cat {knob} 2>/dev/null)" = 1 ] || problem {shlex.quote(f"{knob} is not 1")}') + lines.append('if [ "$problems" = 0 ]; then echo ok; else echo "walls problems: $problems; the first: $first"; fi') + return "\n".join(lines) + "\n" + + async def apply_walls_firewall(sandbox: Sandbox) -> None: """Set the walls on ``sandbox``, a shared box whose dockerd is up, against the resolvers its resolv.conf names.""" code, resolv_conf, stderr = await sandbox.exec_with_output("cat", "/etc/resolv.conf") diff --git a/tst/integration/providers/sandbox_providers/shared_box_walls_live_test.py b/tst/integration/providers/sandbox_providers/shared_box_walls_live_test.py new file mode 100644 index 000000000..9d1ed25b3 --- /dev/null +++ b/tst/integration/providers/sandbox_providers/shared_box_walls_live_test.py @@ -0,0 +1,161 @@ +"""A new shared box on Modal passes its walls self-test and keeps the tag across a reattach, and the checks only a real +box can answer hold: the iptables tools the walls need are there, the walls' own drop rules counted the probes they +blocked, so ``-i aes+`` matched routed and DNAT'd slot traffic, strict reverse-path filtering leaves the box's own +egress and its tunnel working, no interface but a slot's bridge is named ``aes*``, and a container under gVisor can't +open a raw socket, so a slot can't forge a reply into another's flow. It deploys nothing else, and ends the box. + +Skipped unless ``AGENTENV_LIVE_MODAL=1``. Modal credentials come from ``MODAL_TOKEN_ID`` and ``MODAL_TOKEN_SECRET``, else +the active profile in ``~/.modal.toml``; ``MODAL_ENVIRONMENT`` picks the Modal environment. Each probe's result prints +as a ``walls-probe`` JSON line, and the live checks as one ``walls-live`` line; run with ``-s`` to see them pass.""" + +from __future__ import annotations + +import asyncio +import json +import logging +import os +import secrets +import shlex +import time + +import httpx +import pytest + +from agent_env.providers.sandbox_providers.modal_vm_sandbox import ModalVmSandbox, ModalVmSandboxProvider +from agent_env.providers.sandbox_providers.shared_box_selftest import PROBE_IMAGE, WALLS_PROBE_EVENT +from agent_env.providers.sandbox_providers.shared_box_walls import ( + FORWARD_CHAIN, + INPUT_CHAIN, + RP_FILTER_KNOBS, + SLOT_BRIDGE_PREFIX, +) + +pytestmark = [ + pytest.mark.integration, + pytest.mark.int_test_slow, + pytest.mark.asyncio, + pytest.mark.skipif(os.environ.get("AGENTENV_LIVE_MODAL") != "1", reason="set AGENTENV_LIVE_MODAL=1 to run on Modal"), +] + +TUNNEL_PORT = 8000 +BOX_CPU, BOX_MEMORY_MB, BOX_LIFETIME_S = 2, 4096, 1800 +TUNNEL_WITHIN_S = 60 +CONNECTIVITY_URL = "https://www.google.com/generate_204" + +#: Run on the box with its own python3: what each live-only check found, as one JSON object. +LIVE_CHECKS = r''' +import json, os, subprocess, sys + +def sh(command): + done = subprocess.run(["bash", "-c", command], capture_output=True, text=True) + return {"code": done.returncode, "out": done.stdout.strip(), "err": done.stderr.strip()[-300:]} + +forward, inbound, knobs, prefix, image, url = sys.argv[1:7] +print(json.dumps({ + "tools": {tool: sh(f"command -v {tool}")["code"] == 0 + for tool in ("iptables", "iptables-restore", "ip6tables", "ip6tables-restore")}, + "iptables_version": sh("iptables --version")["out"], + "ip6tables_version": sh("ip6tables --version")["out"], + "br_netfilter": os.path.isdir("/sys/module/br_netfilter"), + "bridge_nf_call_iptables": sh("cat /proc/sys/net/bridge/bridge-nf-call-iptables")["out"] or "absent", + "rp_filter": {knob: sh(f"cat {knob}")["out"] for knob in knobs.split(",")}, + "slot_named_interfaces": [name for name in os.listdir("/sys/class/net") if name.startswith(prefix)], + "forward_counters": sh(f"iptables -w -L {forward} -v -x -n")["out"], + "input_counters": sh(f"iptables -w -L {inbound} -v -x -n")["out"], + "ipv6_raw_counters": sh("ip6tables -w -t raw -L PREROUTING -v -x -n")["out"], + "box_egress": sh(f"curl -sS -o /dev/null -w '%{{http_code}}' --max-time 15 {url}")["out"], + "raw_socket_under_gvisor": sh( + f"docker run --rm --network none {image} python -c " + "'import socket; socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)'"), +})) +''' + + +def _counted(listing: str, *, target: str, in_iface: str, out_iface: str | None = None, + destination_in: tuple[str, ...] | None = None) -> int: + """The packets the rules of an ``iptables -L -v -x -n`` listing with ``target``, ``in_iface`` and, when given, + ``out_iface`` and a destination among ``destination_in``, counted.""" + total = 0 + for line in listing.splitlines()[2:]: + fields = line.split() + if len(fields) < 9 or fields[2] != target or fields[5] != in_iface: + continue + if out_iface is not None and fields[6] != out_iface: + continue + if destination_in is not None and fields[8] not in destination_in: + continue + total += int(fields[0]) + return total + + +async def _tunnel_answers(box: ModalVmSandbox) -> int | str: + """The status a GET through the box's tunnel gets from a web server run on the box for the length of the check.""" + serving = asyncio.ensure_future(box.exec_with_output( + "bash", "-c", f"timeout {TUNNEL_WITHIN_S + 30} python3 -m http.server {TUNNEL_PORT} --bind 0.0.0.0")) + deadline, last = time.monotonic() + TUNNEL_WITHIN_S, "no answer" + try: + async with httpx.AsyncClient(timeout=10, trust_env=False) as client: + while time.monotonic() < deadline: + try: + status = (await client.get(box.tunnel_urls[TUNNEL_PORT])).status_code + if status == 200: + return status + last = status + except httpx.HTTPError as e: + last = f"{type(e).__name__}: {e}" + await asyncio.sleep(3) + return last + finally: + serving.cancel() + await asyncio.gather(serving, return_exceptions=True) + + +async def test_a_new_shared_box_verifies_its_walls_and_the_live_only_checks_hold(caplog): + provider = ModalVmSandboxProvider(environment_name=os.environ.get("MODAL_ENVIRONMENT")) + box_id = f"walls-live-{secrets.token_hex(4)}" + box = None + caplog.set_level(logging.INFO, logger="agent_env.providers.sandbox_providers.shared_box_selftest") + try: + try: + box = await provider.create_shared_box(box_id, cpu=BOX_CPU, memory=BOX_MEMORY_MB, timeout=BOX_LIFETIME_S, + exposed_ports=[TUNNEL_PORT]) + finally: + for record in caplog.records: + if getattr(record, "event", None) == WALLS_PROBE_EVENT: + print("walls-probe", json.dumps({key: getattr(record, key) for key in + ("probe", "passed", "expected", "observed", "seconds")})) + reattached = await provider.get_shared_box(box.sandbox_id, box_id) + assert reattached.walls_verified + + argv = ["python3", "-c", LIVE_CHECKS, FORWARD_CHAIN, INPUT_CHAIN, ",".join(RP_FILTER_KNOBS), + SLOT_BRIDGE_PREFIX, PROBE_IMAGE, CONNECTIVITY_URL] + code, stdout, stderr = await reattached.exec_with_output("bash", "-c", shlex.join(argv)) + assert code == 0, stderr + found = json.loads(stdout.strip().splitlines()[-1]) + found["tunnel"] = await _tunnel_answers(reattached) + found["counted"] = { + "slot_to_slot_drops": _counted(found["forward_counters"], target="DROP", in_iface=f"{SLOT_BRIDGE_PREFIX}+", + out_iface=f"{SLOT_BRIDGE_PREFIX}+"), + "private_range_drops": _counted(found["forward_counters"], target="DROP", in_iface=f"{SLOT_BRIDGE_PREFIX}+", + out_iface="*", destination_in=( + "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", + "100.64.0.0/10")), + "box_drops": _counted(found["input_counters"], target="DROP", in_iface=f"{SLOT_BRIDGE_PREFIX}+"), + "same_bridge_returns": _counted(found["forward_counters"], target="RETURN", in_iface="aes0env", + out_iface="aes0env"), + } + print("walls-live", json.dumps(found)) + + assert all(found["tools"].values()), found["tools"] + assert found["rp_filter"] == {knob: "1" for knob in RP_FILTER_KNOBS} + assert found["slot_named_interfaces"] == [] + assert found["box_egress"] == "204" + assert found["tunnel"] == 200 + assert found["counted"]["slot_to_slot_drops"] > 0 + assert found["counted"]["private_range_drops"] > 0 + assert found["counted"]["box_drops"] > 0 + raw = found["raw_socket_under_gvisor"] + assert raw["code"] != 0 and "PermissionError" in raw["err"], raw + finally: + if box is not None: + await provider.terminate_shared_box(box.sandbox_id, box_id) diff --git a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py index 4ef2d16eb..f7e6ab263 100644 --- a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py +++ b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py @@ -464,14 +464,16 @@ async def test_marking_the_walls_verified_writes_nothing_unless_the_sandbox_is_t _MODAL_SANDBOX, _MODAL_VM_SANDBOX = modal_sandbox.__name__, modal_vm_sandbox.__name__ #: The places, each a module and a qualified name in it, with a part in the walls tag: its one writer; the functions #: that may name WALLS_TAG without writing it, its refusal in attribution and the reattach, which alone passes a -#: handle the ``walls`` it read from the tags; and the handle's ``__init__``, which alone stores that ``walls``. +#: handle the ``walls`` it read from the tags; the handle's ``__init__``, which alone stores that ``walls``; and the +#: self-test, which alone calls the writer. _WALLS_WRITER = (_MODAL_VM_SANDBOX, "_mark_walls_verified") +_WALLS_SELF_TEST = (_MODAL_VM_SANDBOX, "verify_walls") _WALLS_REATTACH = (_MODAL_VM_SANDBOX, "ModalVmSandboxProvider.get_shared_box") _WALLS_READERS = {(_MODAL_SANDBOX, "_attribution_tags"), _WALLS_REATTACH} _HANDLE_INIT = (_MODAL_VM_SANDBOX, "ModalVmSandbox.__init__") _TAG_DEFINITION = (_MODAL_SANDBOX, "") #: The strings that would reach the walls tag, or the tags and the handle's record around getattr and setattr. -_WALLS_NAMES = {"WALLS_TAG", "set_tags", "_walls", WALLS_TAG} +_WALLS_NAMES = {"WALLS_TAG", "set_tags", "_walls", "_mark_walls_verified", WALLS_TAG} def _places(tree: ast.Module) -> tuple[dict[int, str], dict[str, ast.AST]]: @@ -523,7 +525,8 @@ def _walls_read_from_tags(function: ast.AST, value: ast.expr) -> bool: def _walls_tag_strays(module: str, text: str) -> list[str]: """Each place in ``text``, the source of ``module``, that writes the walls tag, or a handle's record of it, outside - its one writer, each place matched by module and qualified name, never by name alone. + its one writer, or calls that writer outside the self-test, each place matched by module and qualified name, + never by name alone. WALLS_TAG, bare, as an attribute or imported under another name, is named only in its definition, by the readers, and by the writer, the only one to put it in a dict or assign it. ``set_tags`` is reached, called or not, only on a @@ -531,7 +534,8 @@ def _walls_tag_strays(module: str, text: str) -> list[str]: ``walls`` argument in the handle's ``__init__``; no call passes ``_walls=``, and ``walls=`` is passed only by the reattach, with what it read from the tags. None of these names, nor the tag's value, is made as a string, quoted any way, joined with ``+`` or in an f-string, outside the tag's definition. A module that mentions walls reaches - no object's ``__dict__`` or ``vars``, which would write ``_walls`` unnamed.""" + no object's ``__dict__`` or ``vars``, which would write ``_walls`` unnamed. The writer, ``_mark_walls_verified``, + is named only by the self-test, ``verify_walls``, and imported nowhere.""" tree = ast.parse(text) place, functions = _places(tree) writes, passthrough, definition = set(), set(), set() @@ -559,6 +563,12 @@ def _walls_tag_strays(module: str, text: str) -> list[str]: stray.append(f"{where} names WALLS_TAG") if isinstance(node, ast.alias) and node.name == "WALLS_TAG" and node.asname not in (None, "WALLS_TAG"): stray.append(f"{where} imports WALLS_TAG as {node.asname}") + if ((isinstance(node, ast.Name) and node.id == "_mark_walls_verified") + or (isinstance(node, ast.Attribute) and node.attr == "_mark_walls_verified")) \ + and (module, where_in) != _WALLS_SELF_TEST: + stray.append(f"{where} names _mark_walls_verified") + if isinstance(node, ast.alias) and node.name == "_mark_walls_verified": + stray.append(f"{where} imports _mark_walls_verified") if isinstance(node, ast.Attribute) and node.attr == "set_tags" \ and not (isinstance(node.value, ast.Name) and node.value.id == "app"): stray.append(f"{where} sets tags") @@ -645,6 +655,21 @@ def test_only_the_walls_writer_writes_the_walls_tag_or_sets_a_sandboxs_tags(): "inside the writer, a nested function": ("def _mark_walls_verified(box):\n def inner():\n" " box._walls = WALLS_VERSION\n inner()", "assigns _walls", _MODAL_VM_SANDBOX), + "writer called outside the self-test": ("async def create(box):\n await _mark_walls_verified(box)", + "names _mark_walls_verified", _MODAL_VM_SANDBOX), + "writer held for later": ("def f():\n return _mark_walls_verified", "names _mark_walls_verified", + _MODAL_VM_SANDBOX), + "writer reached as an attribute": ("async def f(m, box):\n await m._mark_walls_verified(box)", + "names _mark_walls_verified"), + "writer imported": (f"from {_MODAL_VM_SANDBOX} import _mark_walls_verified", "imports _mark_walls_verified"), + "writer through getattr": ("async def f(m, box):\n await getattr(m, '_mark_walls_verified')(box)", + "spells '_mark_walls_verified'"), + "a self-test of the same name in another module": ("async def verify_walls(box):\n" + " await _mark_walls_verified(box)", + "names _mark_walls_verified"), + "the self-test as a method": ("class X:\n async def verify_walls(self, box):\n" + " await _mark_walls_verified(box)", + "names _mark_walls_verified", _MODAL_VM_SANDBOX), } @@ -666,6 +691,7 @@ def test_the_walls_guard_lets_the_writer_readers_and_handle_do_their_part(): "async def _mark_walls_verified(box):\n" " tags = await _read_tags(box._sb)\n" " await box._sb.set_tags.aio({**tags, WALLS_TAG: WALLS_VERSION})\n box._walls = WALLS_VERSION\n" + "async def verify_walls(box):\n await run_walls_probes(box)\n await _mark_walls_verified(box)\n" f"{_REATTACH.format('tags.get(WALLS_TAG)')}\n" "class ModalVmSandbox:\n def __init__(self, walls):\n self._walls = walls\n" ), diff --git a/tst/unit/providers/sandbox_providers/shared_box_selftest_test.py b/tst/unit/providers/sandbox_providers/shared_box_selftest_test.py new file mode 100644 index 000000000..d8a344f3c --- /dev/null +++ b/tst/unit/providers/sandbox_providers/shared_box_selftest_test.py @@ -0,0 +1,254 @@ +"""A shared box is returned from ``create_shared_box`` with its walls verified only when every probe of its self-test +answers as expected, its probe slots are torn down, and only then; any other answer, error or timeout ends the box +through ``terminate_shared_box`` and raises, naming the probe. The probes run here against a fake box that scripts +each probe's answer, and their scripts' own logic runs here against a real door and real sockets.""" + +from __future__ import annotations + +import asyncio +import dataclasses +import json +import socket +import sys +from pathlib import Path +from unittest.mock import AsyncMock + +import httpx +import pytest +import uvicorn +from pytest_socket import enable_socket + +from agent_env.env import gateway as gateway_package +from agent_env.env.gateway.constants import SLOT_TOKEN_HEADER +from agent_env.env.gateway.door import Door +from agent_env.providers.env_providers.stack_layout import StackLayout +from agent_env.providers.sandbox_providers import modal_vm_sandbox, shared_box_selftest +from agent_env.providers.sandbox_providers.modal_sandbox import WALLS_TAG, WALLS_VERSION +from agent_env.providers.sandbox_providers.modal_vm_sandbox import ModalVmSandbox, ModalVmSandboxProvider +from agent_env.providers.sandbox_providers.sandbox import NetworkMode, NetworkPolicy +from agent_env.providers.sandbox_providers.shared_box_selftest import PROBE_MARKER, PROBES, WallsNotVerified +from tst.unit.providers.sandbox_providers.modal_shared_box_test import BOX, _offline, modal_api, modal_sb, provider + +__all__ = ["_offline", "modal_api"] + +TEARDOWN = "probe_slots_torn_down" +TEARDOWNS = {StackLayout.for_slot(i).teardown_script for i in (0, 1)} +PASSING = { + "box_facts": json.dumps({"address": "10.0.0.5", "kernel": "6.1.0-modal", + "resolv_conf": "nameserver 172.21.0.1\n"}), + "docker_info": "ok", + "firewall": "ok", + "probe_slots_up": "up", + "slots_under_gvisor": "gvisor", + "slot_0_peer_by_name": "200", + "slot_1_peer_by_name": "200", + "a_to_b_container_ip": "blocked", + "a_to_b_door_via_box_ip": "blocked", + "a_to_box_ip": "blocked", + "a_to_private_ranges": "blocked", + "a_ipv6": "blocked", + "dns": "answers", + "internet": "204", + "door": "401 401 200 400", +} +EVERY_PROBE = ["box_facts", *(probe.name for probe in PROBES)] + + +class FakeBox: + """The execs of a shared box, each probe's script answered from ``answers`` by the probe it names, a teardown as + the probe ``probe_slots_torn_down``, and every other exec, a file written, with success. An answer is the probe's + printed line, an exit code and stderr, an exception to raise, or ``hang`` to never return. ``events`` is each probe + run, in order, and ``tag`` once the box's tags are set.""" + + def __init__(self, **answers): + self.answers = {**PASSING, **answers} + self.events: list[str] = [] + + async def exec_with_output(self, box, *args: str) -> tuple[int, str, str]: + name = None + if args[:-1] in (("bash", "-c"), ("sudo", "bash", "-c")): + script = args[-1] + if script.startswith(PROBE_MARKER): + name = script[len(PROBE_MARKER):].split("\n", 1)[0] + elif script in TEARDOWNS: + name = TEARDOWN + if name is None: + return 0, "", "" + self.events.append(name) + answer = self.answers.get(name, "") + if answer == "hang": + await asyncio.Event().wait() + if isinstance(answer, BaseException): + raise answer + return answer if isinstance(answer, tuple) else (0, f"{answer}\n", "") + + +@pytest.fixture +def box_api(modal_api, monkeypatch): + """A Modal VM whose dockerd starts, whose walls apply, and whose execs ``box_api.box`` answers; its set_tags is + recorded among that box's events.""" + monkeypatch.setattr(ModalVmSandbox, "_ensure_dockerd_running", AsyncMock()) + monkeypatch.setattr(modal_vm_sandbox, "apply_walls_firewall", AsyncMock()) + modal_api.sb = modal_sb(BOX) + modal_api.box = FakeBox() + monkeypatch.setattr(ModalVmSandbox, "exec_with_output", + lambda self, *args: modal_api.box.exec_with_output(self, *args)) + modal_api.sb.set_tags.aio.side_effect = lambda tags: modal_api.box.events.append("tag") + return modal_api + + +def spied_provider(): + p = provider(ModalVmSandboxProvider) + p.terminate_shared_box = AsyncMock(wraps=p.terminate_shared_box) + return p + + +@pytest.mark.asyncio +async def test_a_box_whose_probes_all_pass_is_tagged_verified_once_after_its_probe_slots_are_gone(box_api): + p = spied_provider() + + box = await p.create_shared_box("box-1") + + assert box.walls_verified is True + box_api.sb.set_tags.aio.assert_awaited_once_with({**BOX, WALLS_TAG: WALLS_VERSION}) + assert box_api.box.events == [*EVERY_PROBE[:-1], TEARDOWN, TEARDOWN, "tag"] + p.terminate_shared_box.assert_not_called() + + +ANSWERS = {"unexpected answer": "something else", "script fails": (1, "", "boom"), + "exec raises": ConnectionError("exec dropped")} + + +@pytest.mark.parametrize("probe, answer", [ + pytest.param(probe, answer, id=f"{probe}, {how}") for probe in EVERY_PROBE for how, answer in ANSWERS.items() + # A teardown prints nothing it is judged by: only its failing counts. + if not (probe == TEARDOWN and how == "unexpected answer")]) +@pytest.mark.asyncio +async def test_a_box_whose_probe_answers_otherwise_is_ended_untagged_and_the_error_names_the_probe( + box_api, probe, answer): + box_api.box = FakeBox(**{probe: answer}) + p = spied_provider() + + with pytest.raises(WallsNotVerified, match=rf"probe {probe}:") as raised: + await p.create_shared_box("box-1") + + box_api.sb.set_tags.aio.assert_not_called() + p.terminate_shared_box.assert_awaited_once_with("sb-1", "box-1") + box_api.sb.terminate.aio.assert_awaited_once() + assert [r.name for r in raised.value.results] == EVERY_PROBE[:EVERY_PROBE.index(probe) + 1] + assert [r.passed for r in raised.value.results] == [*([True] * EVERY_PROBE.index(probe)), False] + + +@pytest.mark.parametrize("probe", ["firewall", "door"]) +@pytest.mark.parametrize("limit", ["probe", "whole run"]) +@pytest.mark.asyncio +async def test_a_probe_that_doesnt_answer_in_time_leaves_the_box_untagged_and_ends_it( + box_api, monkeypatch, probe, limit): + box_api.box = FakeBox(**{probe: "hang"}) + if limit == "probe": + monkeypatch.setattr(shared_box_selftest, "PROBES", tuple( + dataclasses.replace(p, timeout_s=0.05) if p.name == probe else p for p in PROBES)) + else: + monkeypatch.setattr(shared_box_selftest, "TOTAL_BUDGET_S", 0.2) + p = spied_provider() + + with pytest.raises(WallsNotVerified, match=rf"probe {probe}: .*no answer within"): + await p.create_shared_box("box-1") + + box_api.sb.set_tags.aio.assert_not_called() + p.terminate_shared_box.assert_awaited_once_with("sb-1", "box-1") + + +@pytest.mark.asyncio +async def test_a_box_whose_egress_is_allowlisted_is_verified_without_the_internet_probes(box_api): + policy = NetworkPolicy(mode=NetworkMode.ALLOWLIST, allow_hosts=("pypi.org",)) + + box = await spied_provider().create_shared_box("box-1", network_policy=policy) + + assert box.walls_verified is True + assert box_api.box.events == [e for e in EVERY_PROBE if e not in ("dns", "internet")][:-1] + [TEARDOWN] * 2 + ["tag"] + + +@pytest.mark.asyncio +async def test_a_box_not_set_up_for_a_gateway_runs_no_probe_and_stays_unverified(box_api): + box = await spied_provider().create_shared_box("box-1", setup_for_gateway=False) + + assert box.walls_verified is False + assert box_api.box.events == [] + + +def _free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +async def _python(code: str, *argv: str) -> str: + process = await asyncio.create_subprocess_exec(sys.executable, "-c", code, *argv, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + stdout, stderr = await process.communicate() + assert process.returncode == 0, stderr.decode() + return stdout.decode().strip() + + +@pytest.mark.asyncio +async def test_the_door_probe_answers_as_expected_against_a_real_door(): + enable_socket() + upstream_port, door_port = _free_port(), _free_port() + upstream = await asyncio.create_subprocess_exec(sys.executable, "-m", "http.server", "--bind", "127.0.0.1", + str(upstream_port), stdout=asyncio.subprocess.DEVNULL, + stderr=asyncio.subprocess.DEVNULL) + async with httpx.AsyncClient(trust_env=False) as client: + door = uvicorn.Server(uvicorn.Config(Door(f"127.0.0.1:{upstream_port}", "the-token", client), + host="127.0.0.1", port=door_port, lifespan="off", log_level="warning")) + serving = asyncio.ensure_future(door.serve()) + try: + answer = await _python(shared_box_selftest._DOOR, "127.0.0.1", str(door_port), SLOT_TOKEN_HEADER, + "the-token") + finally: + door.should_exit = True + await serving + upstream.terminate() + await upstream.wait() + + assert answer in next(probe.expected for probe in PROBES if probe.name == "door") + + +@pytest.mark.asyncio +async def test_the_reach_probe_counts_only_a_connection_that_opens_or_is_refused_as_reached(): + enable_socket() + with socket.socket() as listening: + listening.bind(("127.0.0.1", 0)) + listening.listen() + open_port, closed_port = listening.getsockname()[1], _free_port() + + reached = await _python(shared_box_selftest._REACH, f"127.0.0.1:{open_port}", f"127.0.0.1:{closed_port}") + unreachable = await _python(shared_box_selftest._REACH, "999.0.0.1:80") + + assert reached == f"reached 127.0.0.1:{open_port} open, 127.0.0.1:{closed_port} refused" + assert unreachable == "blocked" + + +@pytest.mark.parametrize("info, nnp, answer", [ + pytest.param({"DefaultRuntime": "runsc", "SecurityOptions": ["name=seccomp", "name=userns", + "name=no-new-privileges"]}, "1", "ok", id="all set"), + pytest.param({"DefaultRuntime": "runsc", "SecurityOptions": ["name=userns"]}, "0", "ok", id="nnp not asked for"), + pytest.param({"DefaultRuntime": "runc", "SecurityOptions": ["name=userns"]}, "0", "the default runtime is runc", + id="runc"), + pytest.param({"DefaultRuntime": "runsc", "SecurityOptions": []}, "0", "no userns in []", id="no userns"), + pytest.param({"DefaultRuntime": "runsc", "SecurityOptions": ["name=userns"]}, "1", + "no no-new-privileges in ['name=userns']", id="nnp missing"), +]) +@pytest.mark.asyncio +async def test_the_docker_probe_passes_only_gvisor_by_default_in_a_user_namespace(info, nnp, answer): + process = await asyncio.create_subprocess_exec(sys.executable, "-c", shared_box_selftest._DOCKER_INFO, "runsc", nnp, + stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE) + stdout, _ = await process.communicate(json.dumps(info).encode()) + + assert stdout.decode().strip() == answer + + +def test_every_probe_container_runs_the_base_the_gateway_image_is_built_on(): + dockerfile = Path(gateway_package.__file__).parent / "Dockerfile" + + assert dockerfile.read_text().splitlines()[0] == f"FROM {shared_box_selftest.PROBE_IMAGE}" diff --git a/tst/unit/providers/sandbox_providers/shared_box_walls_test.py b/tst/unit/providers/sandbox_providers/shared_box_walls_test.py index b6c25f969..3409f29ad 100644 --- a/tst/unit/providers/sandbox_providers/shared_box_walls_test.py +++ b/tst/unit/providers/sandbox_providers/shared_box_walls_test.py @@ -26,6 +26,7 @@ slot_bridges, slot_networks, upstream_resolvers, + walls_check_script, walls_firewall_script, ) @@ -536,3 +537,89 @@ def test_every_slot_network_has_its_own_bridge_name_that_linux_accepts(): assert slot_bridges(7) == ("aes7env", "aes7web") with pytest.raises(ValueError): slot_bridges(SLOT_COUNT) + + +# A stand-in for iptables or ip6tables that answers ``-C`` and ``-S`` from a model's tables: STATE/.chains lists +# its chains, raw ones as ``raw:``, and STATE/.rules holds each rule as ``\t``. +_CHECK_STUB = """#!BASH +args=() +for arg in "$@"; do [ "$arg" = -w ] || args+=("$arg"); done +table=filter +if [ "${args[0]}" = -t ]; then table=${args[1]}; args=("${args[@]:2}"); fi +op=${args[0]} chain=${args[1]} rule="${args[*]:2}" +key=$chain; [ "$table" = filter ] || key="$table:$chain" +state=STATE/${0##*/} +found=1 +while IFS= read -r line; do [ "$line" = "$key" ] && found=0; done < "$state.chains" +[ "$found" = 0 ] || exit 1 +[ "$op" = -C ] || echo "-N $chain" +while IFS= read -r line; do + if [ "$op" = -C ]; then [ "$line" = "$key $rule" ] && exit 0 + elif [ "${line%% *}" = "$key" ]; then echo "-A $chain ${line#* }"; fi +done < "$state.rules" +[ "$op" != -C ] +""" + + +def _check_under_bash(tmp_path, table: FakeIptables) -> str: + """The last line the check script prints, run under bash against ``table``'s rules and kernel settings.""" + bash = shutil.which("bash") + (tmp_path / "bin").mkdir() + for tool, family in TOOLS.items(): + chains = table.tables[family] + (tmp_path / f"{tool}.chains").write_text("".join(f"{chain}\n" for chain in chains)) + (tmp_path / f"{tool}.rules").write_text( + "".join(f"{chain}\t{' '.join(rule)}\n" for chain, rules in chains.items() for rule in rules)) + stub = tmp_path / "bin" / tool + stub.write_text(_CHECK_STUB.replace("BASH", bash).replace("STATE", str(tmp_path))) + stub.chmod(0o755) + for knob in RP_FILTER_KNOBS: + path = tmp_path / knob.lstrip("/") + path.parent.mkdir(parents=True, exist_ok=True) + if knob in table.settings: + path.write_text(table.settings[knob]) + script = walls_check_script(RESOLVERS).replace(" /proc/sys/", f" {tmp_path}/proc/sys/") + done = subprocess.run([bash, "-c", script], capture_output=True, text=True, + env={"PATH": f"{tmp_path / 'bin'}:/usr/bin:/bin"}) + assert done.returncode == 0, done.stderr + return done.stdout.strip().splitlines()[-1] + + +def test_the_check_passes_a_box_whose_firewall_is_the_walls(tmp_path, walled): + assert _check_under_bash(tmp_path, walled) == "ok" + + +def _drop_resolver_rule(table: FakeIptables) -> str: + rule = next(r for r in table.chains["AGENTENV-WALLS-FWD"] if "--dport" in r) + table.chains["AGENTENV-WALLS-FWD"].remove(rule) + return f"iptables AGENTENV-WALLS-FWD lacks {' '.join(rule)}" + + +def _add_rule(table: FakeIptables) -> str: + table.chains["AGENTENV-WALLS-IN"].append(("-j", "RETURN")) + return "iptables AGENTENV-WALLS-IN doesn't hold exactly its 2 rules" + + +def _unhook_ipv6_raw(table: FakeIptables) -> str: + table.tables[6]["raw:PREROUTING"].clear() + return f"ip6tables raw PREROUTING lacks -i {SLOT_BRIDGE_PREFIX}+ -j DROP" + + +def _loosen_rp_filter(table: FakeIptables) -> str: + table.settings[RP_FILTER_KNOBS[1]] = "0" + return f"{RP_FILTER_KNOBS[1]} is not 1" + + +def _drop_ipv6_walls(table: FakeIptables) -> str: + del table.tables[6]["AGENTENV-WALLS-FWD"] + return f"ip6tables AGENTENV-WALLS-FWD lacks -i {SLOT_BRIDGE_PREFIX}+ -j DROP" + + +def test_the_check_counts_every_way_the_firewall_differs_from_the_walls_and_names_the_first(tmp_path, walled): + problems = [_drop_resolver_rule(walled), _add_rule(walled), _unhook_ipv6_raw(walled), _loosen_rp_filter(walled), + _drop_ipv6_walls(walled)] + + answer = _check_under_bash(tmp_path, walled) + + # Dropping a rule, or a whole chain, also leaves its chain short of its rules. + assert answer == f"walls problems: 7; the first: {problems[0]}" From 70e67406bb911c0e8d0b02c29cfefd7e40a581e2 Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Sat, 21 Nov 2026 01:29:12 -0500 Subject: [PATCH 10/15] fix(sandbox-providers): the private-range probe skips public resolvers, which a slot may reach The first live run failed closed on 1.1.1.1:80: Modal's resolv.conf lists public resolvers after 172.21.0.1, and the probe counted all of them as private. Co-Authored-By: Claude Opus 5.5 --- .../sandbox_providers/shared_box_selftest.py | 14 ++++++++++---- .../sandbox_providers/shared_box_walls.py | 4 ++-- .../sandbox_providers/shared_box_selftest_test.py | 15 ++++++++++++++- 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/agent_env/providers/sandbox_providers/shared_box_selftest.py b/src/agent_env/providers/sandbox_providers/shared_box_selftest.py index 4b787b028..21225c361 100644 --- a/src/agent_env/providers/sandbox_providers/shared_box_selftest.py +++ b/src/agent_env/providers/sandbox_providers/shared_box_selftest.py @@ -38,7 +38,7 @@ ) from agent_env.providers.env_providers.stack_layout import StackLayout from agent_env.providers.sandbox_providers.sandbox import VmSandbox -from agent_env.providers.sandbox_providers.shared_box_walls import upstream_resolvers, walls_check_script +from agent_env.providers.sandbox_providers.shared_box_walls import PRIVATE_RANGES, upstream_resolvers, walls_check_script logger = logging.getLogger(__name__) @@ -328,6 +328,14 @@ async def run(box: VmSandbox, plan: ProbePlan) -> str: """ +def _private_range_targets(plan: ProbePlan) -> list[str]: + """Private addresses a slot must not reach, including a private resolver on a port other than DNS. A public + resolver such as 1.1.1.1 is internet, which a slot may reach, so it isn't one.""" + private_resolvers = [r for r in upstream_resolvers(plan.facts.resolv_conf) if any(r in n for n in PRIVATE_RANGES)] + return ["10.0.0.1:80", "169.254.169.254:80", "192.168.0.1:80", "100.64.0.1:80", + *(f"{r}:80" for r in private_resolvers)] + + def _blocked_from_inside(name: str, targets: Callable[[ProbePlan], list[str]]) -> Probe: """A probe that slot 0's prober reaches none of ``targets``: a connection that opens or is refused got there.""" async def run(box: VmSandbox, plan: ProbePlan) -> str: @@ -406,9 +414,7 @@ async def _probe_slots_tear_down(box: VmSandbox, plan: ProbePlan) -> str: f"{plan.other.peer_address}:{_PEER_PORT}", f"{plan.other.door_address}:{plan.other.door_port}"]), _blocked_from_inside("a_to_b_door_via_box_ip", lambda plan: [f"{plan.facts.address}:{plan.other.door_port}"]), _blocked_from_inside("a_to_box_ip", lambda plan: [f"{plan.facts.address}:{port}" for port in (22, 80, 2375)]), - _blocked_from_inside("a_to_private_ranges", lambda plan: [ - "10.0.0.1:80", "169.254.169.254:80", "192.168.0.1:80", "100.64.0.1:80", - *(f"{r}:80" for r in upstream_resolvers(plan.facts.resolv_conf))]), + _blocked_from_inside("a_to_private_ranges", _private_range_targets), _blocked_from_inside("a_ipv6", lambda plan: list(_PUBLIC_IPV6)), Probe("dns", frozenset({"answers"}), 30, _dns_answers_through_the_mounted_resolv_conf, needs_open_egress=True), Probe("internet", frozenset({"204"}), 45, _internet_is_reachable, needs_open_egress=True), diff --git a/src/agent_env/providers/sandbox_providers/shared_box_walls.py b/src/agent_env/providers/sandbox_providers/shared_box_walls.py index 4583e9397..871dd2624 100644 --- a/src/agent_env/providers/sandbox_providers/shared_box_walls.py +++ b/src/agent_env/providers/sandbox_providers/shared_box_walls.py @@ -24,7 +24,7 @@ # Every slot network's Linux bridge is named with this prefix, so the firewall can match slot traffic by the interface # it arrived on, which a container can't spoof as it can a source address. SLOT_BRIDGE_PREFIX = "aes" -_PRIVATE_RANGES = tuple(IPv4Network(n) for n in +PRIVATE_RANGES = tuple(IPv4Network(n) for n in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", "100.64.0.0/10")) FORWARD_CHAIN, INPUT_CHAIN = "AGENTENV-WALLS-FWD", "AGENTENV-WALLS-IN" _ESTABLISHED = "-m conntrack --ctstate ESTABLISHED,RELATED" @@ -111,7 +111,7 @@ def walls_rules(resolvers: Sequence[IPv4Address]) -> dict[str, dict[str, list[st forward += [f"-i {a} -o {b} -j RETURN" for a in bridges for b in bridges] forward += [f"{from_slot} -o {SLOT_BRIDGE_PREFIX}+ -j DROP", f"{_ESTABLISHED} -j RETURN"] forward += [f"{from_slot} -d {r}/32 -p {proto} --dport 53 -j RETURN" for r in resolvers for proto in ("udp", "tcp")] - forward += [f"{from_slot} -d {n} -j DROP" for n in _PRIVATE_RANGES] + forward += [f"{from_slot} -d {n} -j DROP" for n in PRIVATE_RANGES] return { "iptables": {FORWARD_CHAIN: forward, INPUT_CHAIN: [f"{_ESTABLISHED} -j RETURN", f"{from_slot} -j DROP"]}, "ip6tables": {FORWARD_CHAIN: [f"{from_slot} -j DROP"], INPUT_CHAIN: [f"{from_slot} -j DROP"]}, diff --git a/tst/unit/providers/sandbox_providers/shared_box_selftest_test.py b/tst/unit/providers/sandbox_providers/shared_box_selftest_test.py index d8a344f3c..a682d275c 100644 --- a/tst/unit/providers/sandbox_providers/shared_box_selftest_test.py +++ b/tst/unit/providers/sandbox_providers/shared_box_selftest_test.py @@ -35,7 +35,7 @@ TEARDOWNS = {StackLayout.for_slot(i).teardown_script for i in (0, 1)} PASSING = { "box_facts": json.dumps({"address": "10.0.0.5", "kernel": "6.1.0-modal", - "resolv_conf": "nameserver 172.21.0.1\n"}), + "resolv_conf": "nameserver 172.21.0.1\nnameserver 1.1.1.1\nnameserver 8.8.8.8\n"}), "docker_info": "ok", "firewall": "ok", "probe_slots_up": "up", @@ -252,3 +252,16 @@ def test_every_probe_container_runs_the_base_the_gateway_image_is_built_on(): dockerfile = Path(gateway_package.__file__).parent / "Dockerfile" assert dockerfile.read_text().splitlines()[0] == f"FROM {shared_box_selftest.PROBE_IMAGE}" + + +def test_a_slot_must_not_reach_a_private_resolver_off_dns_but_may_reach_a_public_one(): + facts = shared_box_selftest.BoxFacts(address="10.0.0.5", kernel="6.1.0-modal", + resolv_conf="nameserver 172.21.0.1\nnameserver 1.1.1.1\nnameserver 8.8.8.8\n") + targets = shared_box_selftest._private_range_targets(dataclasses.replace(_plan_stub(), facts=facts)) + assert "172.21.0.1:80" in targets + assert not {"1.1.1.1:80", "8.8.8.8:80"} & set(targets) + + +def _plan_stub() -> shared_box_selftest.ProbePlan: + return shared_box_selftest.ProbePlan(facts=shared_box_selftest.BoxFacts("", "", ""), slots=(None, None), + no_new_privileges=False, open_egress=True) From 14d300a21928eb7555e474d20c1d46f7fb71a016 Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Sat, 21 Nov 2026 01:38:08 -0500 Subject: [PATCH 11/15] fix(sandbox-providers): a shared box's runsc writes container files through to Docker, so images built on the box keep their layers gVisor's default rootfs overlay keeps a container's writes inside the sandbox, so a docker build RUN step on the box left nothing in its layer: the live self-test's door image had no httpx and the door never came up. With --overlay2=none the walls self-test passes on Modal, all 16 probes and the live-only checks. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py | 2 +- tst/unit/providers/sandbox_providers/modal_shared_box_test.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py index 0ef091924..a4a04f7d1 100644 --- a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py +++ b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py @@ -102,7 +102,7 @@ "edaa0b91e238ec5c27a25a1b9e00bf98113398eb62a0778d8d20d4e222f8b0e0") _SHARED_BOX_DOCKERD_CONFIG = { "default-runtime": "runsc", - "runtimes": {"runsc": {"path": "/usr/local/bin/runsc"}}, + "runtimes": {"runsc": {"path": "/usr/local/bin/runsc", "runtimeArgs": ["--overlay2=none"]}}, "userns-remap": "default", "no-new-privileges": True, "userland-proxy": False, diff --git a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py index f7e6ab263..771575f9f 100644 --- a/tst/unit/providers/sandbox_providers/modal_shared_box_test.py +++ b/tst/unit/providers/sandbox_providers/modal_shared_box_test.py @@ -315,7 +315,7 @@ def test_a_shared_box_runs_from_the_vm_image_plus_a_pinned_checksummed_runsc_and assert configure.endswith("> /etc/docker/daemon.json") assert json.loads(written) == { "default-runtime": "runsc", - "runtimes": {"runsc": {"path": "/usr/local/bin/runsc"}}, + "runtimes": {"runsc": {"path": "/usr/local/bin/runsc", "runtimeArgs": ["--overlay2=none"]}}, "userns-remap": "default", "no-new-privileges": True, "userland-proxy": False, From e61cee51e2a2fbabede16e2e4fd986aea05a7104 Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Mon, 23 Nov 2026 13:31:41 -0500 Subject: [PATCH 12/15] fix(sandbox-providers): name the shared-box timeout default, and keep the slot teardown test from leaking or colliding Both create_shared_box methods now share SHARED_BOX_DEFAULT_TIMEOUT_S. The slot teardown test brings its two stacks up inside the try, so a failed setup is still torn down, and holds a machine-wide file lock, so two runs on one Docker daemon never create and delete the same s43/s44 projects at once. Co-Authored-By: Claude Opus 5.5 --- .../sandbox_providers/modal_vm_sandbox.py | 8 +++++-- .../sandbox_providers/sandbox_provider.py | 3 ++- .../env_providers/slot_teardown_test.py | 22 ++++++++++++------- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py index a4a04f7d1..5dbbfff57 100644 --- a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py +++ b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py @@ -62,7 +62,11 @@ from agent_env.providers.sandbox_providers.disk_launcher import LAUNCH, RESET, launcher_variables, reset_input from agent_env.providers.sandbox_providers.local_docker.disk import exported_disk from agent_env.providers.sandbox_providers.sandbox import NetworkPolicy, Sandbox, VmSandbox, push_object_over_stdin -from agent_env.providers.sandbox_providers.sandbox_provider import SANDBOX_MODE_VM, SandboxProvider +from agent_env.providers.sandbox_providers.sandbox_provider import ( + SANDBOX_MODE_VM, + SHARED_BOX_DEFAULT_TIMEOUT_S, + SandboxProvider, +) from agent_env.providers.sandbox_providers.shared_box_walls import apply_walls_firewall if TYPE_CHECKING: @@ -457,7 +461,7 @@ async def create_shared_box( *, cpu: float = 0.5, memory: int = 8192, - timeout: int = 3600 * 2, + timeout: int = SHARED_BOX_DEFAULT_TIMEOUT_S, exposed_ports: Optional[list[int]] = None, setup_for_gateway: bool = True, attribution: Optional[Attribution] = None, diff --git a/src/agent_env/providers/sandbox_providers/sandbox_provider.py b/src/agent_env/providers/sandbox_providers/sandbox_provider.py index a6f9f9ae4..075f04ab5 100644 --- a/src/agent_env/providers/sandbox_providers/sandbox_provider.py +++ b/src/agent_env/providers/sandbox_providers/sandbox_provider.py @@ -32,6 +32,7 @@ SANDBOX_MODE_VM = "vm" SANDBOX_MODE_CONTAINER = "container" +SHARED_BOX_DEFAULT_TIMEOUT_S = 2 * 3600 class SandboxProviderTypeError(ConfigError): @@ -103,7 +104,7 @@ async def create_shared_box( *, cpu: float = 1.0, memory: int = 8192, - timeout: int = 3600 * 2, + timeout: int = SHARED_BOX_DEFAULT_TIMEOUT_S, exposed_ports: Optional[list[int]] = None, setup_for_gateway: bool = True, attribution: Optional[Attribution] = None, diff --git a/tst/integration/providers/env_providers/slot_teardown_test.py b/tst/integration/providers/env_providers/slot_teardown_test.py index b9303700a..c8c3aa738 100644 --- a/tst/integration/providers/env_providers/slot_teardown_test.py +++ b/tst/integration/providers/env_providers/slot_teardown_test.py @@ -2,8 +2,10 @@ scratch files, and leaves a neighbouring slot whole. The script runs in a throwaway Docker CLI container that holds the slots' dirs, so it never touches this machine's /app or /tmp. Needs Docker.""" +import fcntl import shutil import subprocess +import tempfile import uuid from pathlib import Path @@ -42,14 +44,18 @@ def two_slots(tmp_path: Path): pytest.skip(missing_capability_reason("docker_daemon")) compose_file = tmp_path / "docker-compose.yml" compose_file.write_text(COMPOSE) - for layout in (GONE, KEPT): - _docker("compose", "-p", layout.compose_project, "-f", str(compose_file), "up", "-d", "--quiet-pull") - try: - yield - finally: - for layout in (GONE, KEPT): - subprocess.run(["docker", "compose", "-p", layout.compose_project, "-f", str(compose_file), "down", "-v"], - capture_output=True) + with open(Path(tempfile.gettempdir()) / "agentenv-slot-teardown-test.lock", "a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + try: + for layout in (GONE, KEPT): + _docker("compose", "-p", layout.compose_project, "-f", str(compose_file), "up", "-d", "--quiet-pull") + yield + finally: + for layout in (GONE, KEPT): + subprocess.run( + ["docker", "compose", "-p", layout.compose_project, "-f", str(compose_file), "down", "-v"], + capture_output=True, + ) def _run_teardown_twice_beside_both_slots_files() -> str: From 3ac525fe25d22a92a4d4330fdd827bb519ea7f80 Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Mon, 23 Nov 2026 13:50:32 -0500 Subject: [PATCH 13/15] fix(env-providers): quoted secrets are masked in the logged compose, the door keeps no upstream cookies, and the live walls test skips with a named capability The generator quotes an env value holding ": " or a newline, and the redaction pattern missed the opening quote, so such a secret was logged in full. The door's shared httpx client kept upstream Set-Cookie responses and sent them on every later request, so a caller with no cookie could ride an earlier caller's session; its jar now accepts nothing, and only the caller's own Cookie header is forwarded. The live Modal walls test now skips as remote_sandbox, which CI's skip policy allows. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/door.py | 7 +++++-- .../env_providers/env_gateway_provider.py | 9 +++++++-- .../shared_box_walls_live_test.py | 4 +++- tst/unit/env/gateway/door_test.py | 20 +++++++++++++++++++ .../env_gateway_provider_test.py | 10 ++++++++++ 5 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/agent_env/env/gateway/door.py b/src/agent_env/env/gateway/door.py index fecc78c82..218df6424 100644 --- a/src/agent_env/env/gateway/door.py +++ b/src/agent_env/env/gateway/door.py @@ -16,6 +16,7 @@ import hmac import logging import os +from http.cookiejar import CookieJar, DefaultCookiePolicy import httpx import uvicorn @@ -179,9 +180,11 @@ async def _deny_websocket(scope, send, status: int, body: bytes) -> None: def door_client() -> httpx.AsyncClient: """The client a door forwards with: no timeout once connected, as a stream may stay open, no redirects followed, - and no proxy from the environment.""" + no proxy from the environment, and a cookie jar that keeps nothing, so a caller's session cookie never reaches the + next caller.""" return httpx.AsyncClient(timeout=httpx.Timeout(None, connect=_UPSTREAM_CONNECT_TIMEOUT_S), - follow_redirects=False, trust_env=False) + follow_redirects=False, trust_env=False, + cookies=CookieJar(policy=DefaultCookiePolicy(allowed_domains=[]))) async def serve(routes: dict[int, str], token: str) -> None: diff --git a/src/agent_env/providers/env_providers/env_gateway_provider.py b/src/agent_env/providers/env_providers/env_gateway_provider.py index 2a75b6bdb..4299f5e85 100644 --- a/src/agent_env/providers/env_providers/env_gateway_provider.py +++ b/src/agent_env/providers/env_providers/env_gateway_provider.py @@ -1790,7 +1790,7 @@ def _compose_name_problems(mcp_servers: list[MCPServerConfig], website_configs: # Compose `environment:` keys whose values are secrets and must be masked before the # rendered compose is logged. Matches the key to the left of the first '=' on an # ` - KEY=VALUE` env line. -_SECRET_ENV_KEY_RE = re.compile(r"^(\s*-\s*)([A-Za-z0-9_]*(?:SECRET|PASSWORD|TOKEN|API_KEY)[A-Za-z0-9_]*)=.*$") +_SECRET_ENV_KEY_RE = re.compile(r"^(\s*-\s*[\"']?)([A-Za-z0-9_]*(?:SECRET|PASSWORD|TOKEN|API_KEY)[A-Za-z0-9_]*)=.*$") _SETTINGS_LINE_RE = re.compile(rf'^(\s*-\s*["\'])({WEBSITE_SETTINGS_ENV})=.*$') @@ -1847,10 +1847,15 @@ def _network_lines(*networks: str) -> list[str]: return [" networks:", *(f" - {network}" for network in networks)] +def _masked(m: re.Match[str]) -> str: + quote = m[1][-1] if m[1][-1] in "\"'" else "" + return f"{m[1]}{m[2]}=***{quote}" + + def _redact_compose_secrets(compose_content: str) -> str: """Mask secret-valued env lines so the logged compose never carries a live secret, a site's settings among them.""" return "\n".join( - _SETTINGS_LINE_RE.sub(lambda m: f"{m[1]}{m[2]}=***{m[1][-1]}", _SECRET_ENV_KEY_RE.sub(r"\1\2=***", line)) + _SETTINGS_LINE_RE.sub(_masked, _SECRET_ENV_KEY_RE.sub(_masked, line)) for line in compose_content.splitlines() ) diff --git a/tst/integration/providers/sandbox_providers/shared_box_walls_live_test.py b/tst/integration/providers/sandbox_providers/shared_box_walls_live_test.py index 9d1ed25b3..d6b411072 100644 --- a/tst/integration/providers/sandbox_providers/shared_box_walls_live_test.py +++ b/tst/integration/providers/sandbox_providers/shared_box_walls_live_test.py @@ -30,11 +30,13 @@ SLOT_BRIDGE_PREFIX, ) +from tst.util.capabilities import REMOTE_SANDBOX, missing_capability_reason + pytestmark = [ pytest.mark.integration, pytest.mark.int_test_slow, pytest.mark.asyncio, - pytest.mark.skipif(os.environ.get("AGENTENV_LIVE_MODAL") != "1", reason="set AGENTENV_LIVE_MODAL=1 to run on Modal"), + pytest.mark.skipif(os.environ.get("AGENTENV_LIVE_MODAL") != "1", reason=missing_capability_reason(REMOTE_SANDBOX)), ] TUNNEL_PORT = 8000 diff --git a/tst/unit/env/gateway/door_test.py b/tst/unit/env/gateway/door_test.py index 8f92120aa..16ca4a5e1 100644 --- a/tst/unit/env/gateway/door_test.py +++ b/tst/unit/env/gateway/door_test.py @@ -48,7 +48,14 @@ async def _ws(websocket: WebSocket) -> None: await websocket.send_text(f"echo {message}") +async def _sign_in(_: Request) -> JSONResponse: + response = JSONResponse({}) + response.set_cookie("session", "first-callers-session") + return response + + _UPSTREAM = Starlette(routes=[Route("/echo", _echo, methods=["GET", "POST"]), Route("/stream", _stream), + Route("/sign-in", _sign_in), WebSocketRoute("/ws", _ws)]) @@ -112,6 +119,19 @@ async def test_with_the_token_a_request_passes_without_it_and_with_everything_el assert seen["headers"]["x-other"] == "kept" +@pytest.mark.asyncio +async def test_a_session_cookie_one_caller_got_never_reaches_the_next_caller(door_port): + async with httpx.AsyncClient() as first: + signed_in = await first.get(f"http://127.0.0.1:{door_port}/sign-in", headers=_token()) + assert "first-callers-session" in signed_in.headers["set-cookie"] + async with httpx.AsyncClient() as second: + fresh = (await second.get(f"http://127.0.0.1:{door_port}/echo", headers=_token())).json() + own = (await second.get(f"http://127.0.0.1:{door_port}/echo", + headers={**_token(), "Cookie": "session=second"})).json() + assert "cookie" not in fresh["headers"] + assert own["headers"]["cookie"] == "session=second" + + @pytest.mark.asyncio async def test_a_stream_passes_as_it_comes(door_port): async with httpx.AsyncClient() as client: diff --git a/tst/unit/providers/env_providers/env_gateway_provider_test.py b/tst/unit/providers/env_providers/env_gateway_provider_test.py index ea4d060f5..1d898124a 100644 --- a/tst/unit/providers/env_providers/env_gateway_provider_test.py +++ b/tst/unit/providers/env_providers/env_gateway_provider_test.py @@ -41,6 +41,7 @@ EnvironmentGatewayProvider, SidecarConfig, WebsiteConfig, + _environment_line, _redact_compose_secrets, ) from agent_env.providers.env_providers.env_provider import DeployRefused @@ -1231,6 +1232,15 @@ def test_compose_hands_the_control_token_to_the_gateway_alone(): state_instance=LocalPostgresStateProvider.default_instance()) +def test_a_secret_the_generator_quotes_is_masked_in_the_logged_compose(): + lines = [_environment_line("API_KEY", "abc: def"), _environment_line("DB_PASSWORD", "line one\nline two"), + _environment_line("PLAIN", "a: b")] + assert all('"' in line for line in lines) + redacted = _redact_compose_secrets("\n".join(lines)) + assert "abc" not in redacted and "line one" not in redacted + assert redacted.splitlines() == [' - "API_KEY=***"', ' - "DB_PASSWORD=***"', ' - "PLAIN=a: b"'] + + def test_redact_compose_secrets_masks_only_secret_env_lines(): """The logged compose masks *SECRET/PASSWORD/TOKEN env values but leaves everything else (image refs, ports, non-secret env, DATABASE_URL) intact.""" From bcfc436a082d66c386192c68cbb9b32afb34af36 Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Mon, 23 Nov 2026 14:49:52 -0500 Subject: [PATCH 14/15] test(env-providers): a quoted or multiline secret rendered by the real compose generator is masked in the log The generator writes a multiline value as one JSON-quoted line, so the redaction pattern sees the whole secret on that line. This renders both cases through create_docker_compose, checks the compose still reads back to the exact values, and checks the logged form carries none of them. Co-Authored-By: Claude Opus 5.5 --- .../env_gateway_provider_test.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tst/unit/providers/env_providers/env_gateway_provider_test.py b/tst/unit/providers/env_providers/env_gateway_provider_test.py index 1d898124a..49ae40c0f 100644 --- a/tst/unit/providers/env_providers/env_gateway_provider_test.py +++ b/tst/unit/providers/env_providers/env_gateway_provider_test.py @@ -1241,6 +1241,25 @@ def test_a_secret_the_generator_quotes_is_masked_in_the_logged_compose(): assert redacted.splitlines() == [' - "API_KEY=***"', ' - "DB_PASSWORD=***"', ' - "PLAIN=a: b"'] +def test_a_quoted_or_multiline_secret_in_a_rendered_compose_is_masked_and_the_compose_still_reads_back(): + from agent_env.env.envs.service_db import ServiceDBConfig + + secrets_in = {"VENDOR_API_KEY": "first: half", "SIGNING_PASSWORD": "-----BEGIN-----\nkey body\n-----END-----"} + rendered = EnvironmentGatewayProvider().create_docker_compose( + mcp_servers=[MCPServerConfig(image="mcp-slack", environment_name="slack", extra_env_vars=secrets_in)], + gateway_image="agent-gateway", + state_provider=LocalPostgresStateProvider(service_db_config=ServiceDBConfig()), + state_instance=LocalPostgresStateProvider.default_instance(), + ) + env = dict(item.split("=", 1) for item in yaml.safe_load(rendered)["services"]["slack"]["environment"]) + assert {key: env[key] for key in secrets_in} == secrets_in + + redacted = _redact_compose_secrets(rendered) + assert all(fragment not in redacted for fragment in ("first", "half", "BEGIN", "key body")) + redacted_env = dict(item.split("=", 1) for item in yaml.safe_load(redacted)["services"]["slack"]["environment"]) + assert {key: redacted_env[key] for key in secrets_in} == {"VENDOR_API_KEY": "***", "SIGNING_PASSWORD": "***"} + + def test_redact_compose_secrets_masks_only_secret_env_lines(): """The logged compose masks *SECRET/PASSWORD/TOKEN env values but leaves everything else (image refs, ports, non-secret env, DATABASE_URL) intact.""" From c1892768bbbe8a86163845b54f84e18f05c5c9ec Mon Sep 17 00:00:00 2001 From: Man Yin Kwok Date: Mon, 23 Nov 2026 15:49:58 -0500 Subject: [PATCH 15/15] fix(sandbox-providers): name the walls probes' time limits, wait for the door test's servers, and match the golden stack to main Each probe's limit is now one of four named budgets by the kind of work it waits on, and the scripts that run on the box name their own request and retry limits. The door probe test waits until its upstream and door accept connections, so CI no longer sees a 502 from a server that hasn't started. The default-stack golden file takes main's change: pgweb and db-mcp publish no ports, and the gateway reaches them by CONSOLE_URLS. Co-Authored-By: Claude Opus 5.5 --- .../sandbox_providers/shared_box_selftest.py | 54 ++++++++++++------- .../golden/default_stack_compose.yml | 5 +- .../shared_box_selftest_test.py | 21 ++++++++ 3 files changed, 57 insertions(+), 23 deletions(-) diff --git a/src/agent_env/providers/sandbox_providers/shared_box_selftest.py b/src/agent_env/providers/sandbox_providers/shared_box_selftest.py index 21225c361..d56ba687b 100644 --- a/src/agent_env/providers/sandbox_providers/shared_box_selftest.py +++ b/src/agent_env/providers/sandbox_providers/shared_box_selftest.py @@ -48,6 +48,15 @@ PROBE_MARKER = "# walls probe: " #: The whole run's limit, in seconds, past which the probe running is cut off and the walls are not verified. TOTAL_BUDGET_S = 300.0 +#: Each probe's own limit, in seconds, by the kind of work it waits on. +#: One command on the box or in a container that is already running. +ONE_COMMAND_S = 30 +#: One or a few connections from a running probe container, each with its own short timeout. +CONNECTIONS_S = 45 +#: Reading or changing the box's own state: the firewall's rules and counters, or removing the probe slots. +BOX_STATE_S = 60 +#: Building the door image and starting both probe slots' containers. +SLOTS_UP_S = 180 #: The gateway image's base, by digest: every probe container runs it. PROBE_IMAGE = ("public.ecr.aws/docker/library/python:3.11-slim" @@ -286,18 +295,22 @@ async def _slots_run_under_gvisor(box: VmSandbox, plan: ProbePlan) -> str: ])) +#: How long a probe script retries a request that fails, in seconds: a service just started may not answer yet. +_RETRY_WITHIN_S = 30 + _GET = """ import sys, time, urllib.request +REQUEST_TIMEOUT_S, RETRY_PAUSE_S = 5, 1 deadline = time.monotonic() + float(sys.argv[2]) while True: try: - print(urllib.request.urlopen(sys.argv[1], timeout=5).status) + print(urllib.request.urlopen(sys.argv[1], timeout=REQUEST_TIMEOUT_S).status) break except Exception as e: if time.monotonic() > deadline: print(type(e).__name__ + ": " + str(e)) break - time.sleep(1) + time.sleep(RETRY_PAUSE_S) """ @@ -305,19 +318,20 @@ def _peer_by_name(index: int) -> Callable[[VmSandbox, ProbePlan], Awaitable[str] async def run(box: VmSandbox, plan: ProbePlan) -> str: slot = plan.slots[index] url = f"http://{_PEER}:{_PEER_PORT}/" - return await _answer(box, f"slot_{index}_peer_by_name", slot.exec_in_prober("python", "-c", _GET, url, "30")) + return await _answer(box, f"slot_{index}_peer_by_name", slot.exec_in_prober("python", "-c", _GET, url, str(_RETRY_WITHIN_S))) return run _REACH = """ import socket, sys +CONNECT_TIMEOUT_S = 3 reached = [] for target in sys.argv[1:]: host, _, port = target.rpartition(":") host = host.strip("[]") try: with socket.socket(socket.AF_INET6 if ":" in host else socket.AF_INET) as s: - s.settimeout(3) + s.settimeout(CONNECT_TIMEOUT_S) s.connect((host, int(port))) reached.append(target + " open") except ConnectionRefusedError: @@ -340,7 +354,7 @@ def _blocked_from_inside(name: str, targets: Callable[[ProbePlan], list[str]]) - """A probe that slot 0's prober reaches none of ``targets``: a connection that opens or is refused got there.""" async def run(box: VmSandbox, plan: ProbePlan) -> str: return await _answer(box, name, plan.inside.exec_in_prober("python", "-c", _REACH, *targets(plan))) - return Probe(name, _BLOCKED, 45, run) + return Probe(name, _BLOCKED, CONNECTIONS_S, run) _DNS = """ @@ -363,22 +377,24 @@ async def _dns_answers_through_the_mounted_resolv_conf(box: VmSandbox, plan: Pro async def _internet_is_reachable(box: VmSandbox, plan: ProbePlan) -> str: - return await _answer(box, "internet", plan.inside.exec_in_prober("python", "-c", _GET, _CONNECTIVITY_URL, "30")) + return await _answer(box, "internet", plan.inside.exec_in_prober("python", "-c", _GET, _CONNECTIVITY_URL, + str(_RETRY_WITHIN_S))) _DOOR = """ import http.client, sys, time host, port, header, token = sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4] +REQUEST_TIMEOUT_S, UP_WITHIN_S, RETRY_PAUSE_S = 5, 30, 1 def status(target, value): - connection = http.client.HTTPConnection(host, port, timeout=5) + connection = http.client.HTTPConnection(host, port, timeout=REQUEST_TIMEOUT_S) try: connection.request("GET", target, headers={} if value is None else {header: value}) return connection.getresponse().status finally: connection.close() -deadline = time.monotonic() + 30 +deadline = time.monotonic() + UP_WITHIN_S while True: try: status("/", None) @@ -386,7 +402,7 @@ def status(target, value): except OSError: if time.monotonic() > deadline: raise - time.sleep(1) + time.sleep(RETRY_PAUSE_S) print(status("/", None), status("/", "wrong-" + token), status("/", token), status("//elsewhere/x", token)) """ @@ -404,20 +420,20 @@ async def _probe_slots_tear_down(box: VmSandbox, plan: ProbePlan) -> str: PROBES: tuple[Probe, ...] = ( - Probe("docker_info", frozenset({"ok"}), 30, _docker_runs_gvisor_in_a_user_namespace), - Probe("firewall", frozenset({"ok"}), 60, _firewall_holds_the_walls), - Probe("probe_slots_up", frozenset({"up"}), 180, _probe_slots_come_up), - Probe("slots_under_gvisor", frozenset({"gvisor"}), 30, _slots_run_under_gvisor), - Probe("slot_0_peer_by_name", frozenset({"200"}), 45, _peer_by_name(0)), - Probe("slot_1_peer_by_name", frozenset({"200"}), 45, _peer_by_name(1)), + Probe("docker_info", frozenset({"ok"}), ONE_COMMAND_S, _docker_runs_gvisor_in_a_user_namespace), + Probe("firewall", frozenset({"ok"}), BOX_STATE_S, _firewall_holds_the_walls), + Probe("probe_slots_up", frozenset({"up"}), SLOTS_UP_S, _probe_slots_come_up), + Probe("slots_under_gvisor", frozenset({"gvisor"}), ONE_COMMAND_S, _slots_run_under_gvisor), + Probe("slot_0_peer_by_name", frozenset({"200"}), CONNECTIONS_S, _peer_by_name(0)), + Probe("slot_1_peer_by_name", frozenset({"200"}), CONNECTIONS_S, _peer_by_name(1)), _blocked_from_inside("a_to_b_container_ip", lambda plan: [ f"{plan.other.peer_address}:{_PEER_PORT}", f"{plan.other.door_address}:{plan.other.door_port}"]), _blocked_from_inside("a_to_b_door_via_box_ip", lambda plan: [f"{plan.facts.address}:{plan.other.door_port}"]), _blocked_from_inside("a_to_box_ip", lambda plan: [f"{plan.facts.address}:{port}" for port in (22, 80, 2375)]), _blocked_from_inside("a_to_private_ranges", _private_range_targets), _blocked_from_inside("a_ipv6", lambda plan: list(_PUBLIC_IPV6)), - Probe("dns", frozenset({"answers"}), 30, _dns_answers_through_the_mounted_resolv_conf, needs_open_egress=True), - Probe("internet", frozenset({"204"}), 45, _internet_is_reachable, needs_open_egress=True), - Probe("door", frozenset({"401 401 200 400"}), 45, _door_takes_only_its_token), - Probe("probe_slots_torn_down", frozenset({"torn down"}), 60, _probe_slots_tear_down), + Probe("dns", frozenset({"answers"}), ONE_COMMAND_S, _dns_answers_through_the_mounted_resolv_conf, needs_open_egress=True), + Probe("internet", frozenset({"204"}), CONNECTIONS_S, _internet_is_reachable, needs_open_egress=True), + Probe("door", frozenset({"401 401 200 400"}), CONNECTIONS_S, _door_takes_only_its_token), + Probe("probe_slots_torn_down", frozenset({"torn down"}), BOX_STATE_S, _probe_slots_tear_down), ) diff --git a/tst/unit/providers/env_providers/golden/default_stack_compose.yml b/tst/unit/providers/env_providers/golden/default_stack_compose.yml index f4ef237cb..562a0bcd4 100644 --- a/tst/unit/providers/env_providers/golden/default_stack_compose.yml +++ b/tst/unit/providers/env_providers/golden/default_stack_compose.yml @@ -24,8 +24,6 @@ services: environment: - PGWEB_DATABASE_URL=postgres://agentenv:agentenv@servicedb:5432/agentenv?sslmode=disable - PGWEB_LOCK_SESSION=true - ports: - - "10.0.0.5:9081:8081" networks: - env-network @@ -38,8 +36,6 @@ services: environment: - DATABASE_URI=postgresql://agentenv:agentenv@servicedb:5432/agentenv command: --transport=streamable-http --streamable-http-host=0.0.0.0 --access-mode=unrestricted - ports: - - "10.0.0.5:19767:8000" networks: - env-network @@ -130,6 +126,7 @@ services: - REST_PROXY_URLS=mcp-slack=http://slack:18765,mcp-calc=http://calc:18765,mcp-browser=http://browser:18765,shop=http://shop-website-backend:8000,blog=http://blog-website-backend:8000,feed=http://feed-website-backend:8000,desk=https://desk.example.com - GATEWAY_MODE=performance - SERVICE_DB_URL=postgresql://agentenv:agentenv@servicedb:5432/agentenv + - CONSOLE_URLS=pgweb=http://pgweb:8081,db-mcp=http://db-mcp:8000 - AGENTENV_CONTROL_TOKEN=ctl-token - CONTROL_TOKEN_CHILDREN=desk - COMPUTERS=desk diff --git a/tst/unit/providers/sandbox_providers/shared_box_selftest_test.py b/tst/unit/providers/sandbox_providers/shared_box_selftest_test.py index a682d275c..5ad2a14b0 100644 --- a/tst/unit/providers/sandbox_providers/shared_box_selftest_test.py +++ b/tst/unit/providers/sandbox_providers/shared_box_selftest_test.py @@ -177,6 +177,25 @@ async def test_a_box_not_set_up_for_a_gateway_runs_no_probe_and_stays_unverified assert box_api.box.events == [] +LISTEN_WITHIN_S = 10 + + +async def _until_listening(port: int) -> None: + """Waits until something accepts connections on loopback ``port``; a server started a moment ago may not yet.""" + deadline = asyncio.get_running_loop().time() + LISTEN_WITHIN_S + while True: + try: + _, writer = await asyncio.open_connection("127.0.0.1", port) + except OSError: + if asyncio.get_running_loop().time() > deadline: + raise + await asyncio.sleep(0.05) + else: + writer.close() + await writer.wait_closed() + return + + def _free_port() -> int: with socket.socket() as s: s.bind(("127.0.0.1", 0)) @@ -203,6 +222,8 @@ async def test_the_door_probe_answers_as_expected_against_a_real_door(): host="127.0.0.1", port=door_port, lifespan="off", log_level="warning")) serving = asyncio.ensure_future(door.serve()) try: + await _until_listening(upstream_port) + await _until_listening(door_port) answer = await _python(shared_box_selftest._DOOR, "127.0.0.1", str(door_port), SLOT_TOKEN_HEADER, "the-token") finally: