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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,19 @@
_DISK_IDLE_TIMEOUT_S = 30 * 60


#: The most bytes of arguments an exec sends as argv; Modal rejects one past ~48 KB. A longer one goes over stdin.
_MAX_EXEC_ARG_BYTES = 32 * 1024
#: Reads a NUL-separated argv from stdin and runs it, with no input of its own. Linux caps one argument at 128 KiB
#: (MAX_ARG_STRLEN), so a shell's ``-c`` script goes into a file that the shell reads, removes and evals, keeping its $0
#: and $@. Another program's ``-c`` (python3, say) is left as it is.
_FROM_STDIN = (
'mapfile -d "" -t a && '
'if [ "${#a[@]}" -ge 3 ] && [ "${a[1]}" = -c ] && case "${a[0]##*/}" in bash|sh) true;; *) false;; esac; then '
r'f=$(mktemp) && printf %s "${a[2]}" > "$f" && a[2]="eval \"\$(cat -- $f && rm -f -- $f)\""; fi && '
'exec "${a[@]}" </dev/null'
)


class ModalVmSandbox(VmSandbox):
"""A Modal VM sandbox (runtime="vm") presented through the VmSandbox contract.

Expand Down Expand Up @@ -172,7 +185,18 @@ async def exec(self, *command: str):
# helpers prefix commands with "sudo" (sandbox.py). Strip it, exactly like
# LocalSandbox.exec does, so those helpers work unchanged.
cmd = [c for c in command if c != "sudo"]
process = await self._sb.exec.aio(*cmd, text=False)
if sum(len(c.encode()) + 1 for c in cmd) <= _MAX_EXEC_ARG_BYTES:
process = await self._sb.exec.aio(*cmd, text=False)
return _ModalProcessAdapter(process)
# Past Modal's exec limit (a parallel load of many signed image URLs, say), the argv goes over stdin and the
# sandbox reads it back, as kosa8 does through a file.
process = await self._sb.exec.aio("bash", "-c", _FROM_STDIN, text=False)
argv = b"".join(c.encode() + b"\0" for c in cmd)
for i in range(0, len(argv), _MAX_EXEC_ARG_BYTES):
process.stdin.write(argv[i:i + _MAX_EXEC_ARG_BYTES])
await process.stdin.drain.aio()
process.stdin.write_eof()
await process.stdin.drain.aio()
return _ModalProcessAdapter(process)

async def _exec_with_stdin(self, script: str, stdin: AsyncIterator[bytes]) -> tuple[int, str, str]:
Expand Down
72 changes: 72 additions & 0 deletions tst/unit/providers/sandbox_providers/modal_vm_sandbox_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,78 @@ async def fake_exec(*cmd, text=False):
assert captured["cmd"] == ("docker", "images")


@pytest.mark.asyncio
async def test_exec_past_modals_arg_limit_sends_the_argv_over_stdin():
# A parallel load of many signed image URLs runs past Modal's exec limit; the argv goes over stdin instead.
sb = MagicMock()
sb.object_id = "sb-test"
captured: dict = {}
process = MagicMock()
process.stdin.drain.aio = AsyncMock()

async def fake_exec(*cmd, text=False):
captured["cmd"] = cmd
return process

sb.exec.aio = fake_exec
script = " & ".join(f"(curl -fsSL 'https://b/img{i}?{'x' * 2400}' | docker load)" for i in range(36)) + " & wait"
await ModalVmSandbox(sb, {}).exec("sudo", "bash", "-c", script)

assert captured["cmd"] == ("bash", "-c", mvs._FROM_STDIN)
sent = b"".join(call.args[0] for call in process.stdin.write.call_args_list)
assert sent == b"bash\0-c\0" + script.encode() + b"\0"
assert all(len(call.args[0]) <= mvs._MAX_EXEC_ARG_BYTES for call in process.stdin.write.call_args_list)
process.stdin.write_eof.assert_called_once()


def _bash_has_mapfile_d() -> bool:
import subprocess

return subprocess.run(["bash", "-c", 'mapfile -d "" a </dev/null'], capture_output=True).returncode == 0


@pytest.mark.skipif(not _bash_has_mapfile_d(), reason="needs bash 4.4+ (mapfile -d), as the VM has")
def test_from_stdin_runs_a_nul_separated_argv():
# The wrapper reads the argv back intact: quotes, spaces, newlines and all.
import subprocess

argv = ["bash", "-c", 'printf "%s|" "$@"', "_", "a b", "it's", "x\ny"]
out = subprocess.run(["bash", "-c", mvs._FROM_STDIN], input=b"".join(a.encode() + b"\0" for a in argv),
capture_output=True, check=True)
assert out.stdout == b"a b|it's|x\ny|"


@pytest.mark.skipif(not _bash_has_mapfile_d(), reason="needs bash 4.4+ (mapfile -d), as the VM has")
def test_from_stdin_runs_a_script_past_linuxs_128_kib_argument_limit(tmp_path):
# One argument past MAX_ARG_STRLEN can't be exec'd; the -c script runs from a file, with its $0 and $@, and the
# file is gone after.
import os
import subprocess

script = "# " + "x" * (200 * 1024) + '\nprintf "%s|" "$0" "$@"'
argv = ["bash", "-c", script, "name", "a b", "c"]
out = subprocess.run(["bash", "-c", mvs._FROM_STDIN], input=b"".join(a.encode() + b"\0" for a in argv),
capture_output=True, check=True, env={**os.environ, "TMPDIR": str(tmp_path)})
assert out.stdout == b"name|a b|c|"
assert list(tmp_path.iterdir()) == []


@pytest.mark.skipif(not _bash_has_mapfile_d(), reason="needs bash 4.4+ (mapfile -d), as the VM has")
def test_from_stdin_leaves_another_programs_dash_c_as_it_is(tmp_path):
# Only a shell's -c is a shell script; python3 -c gets its own source, not the eval.
import os
import shutil
import subprocess

python = shutil.which("python3")
source = "# " + "x" * (40 * 1024) + "\nimport sys; print(sys.argv[1:])"
argv = [python, "-c", source, "a b"]
out = subprocess.run(["bash", "-c", mvs._FROM_STDIN], input=b"".join(a.encode() + b"\0" for a in argv),
capture_output=True, check=True, env={**os.environ, "TMPDIR": str(tmp_path)})
assert out.stdout == b"['a b']\n"
assert list(tmp_path.iterdir()) == []


@pytest.mark.asyncio
async def test_setup_starts_dockerd_polls_until_ready_and_skips_iptables():
s = _sandbox()
Expand Down
Loading