Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(sandbox): enforce local exec output and process limits (#1150)

XZH72ef3e01203e
diff --git a/deeptutor/services/sandbox/backends.py b/deeptutor/services/sandbox/backends.py
index 892cb6e51..c1f5a89da 100644
--- a/deeptutor/services/sandbox/backends.py
+++ b/deeptutor/services/sandbox/backends.py
@@ -22,6 +22,7 @@ import locale
import os
from pathlib import Path
import shutil
+import signal
import sys
import httpx
@@ -228,10 +229,15 @@ class BwrapBackend(SandboxBackend):
*argv,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
+ start_new_session=sys.platform != "win32",
)
except FileNotFoundError:
return ExecResult(error="bwrap not found on host")
- return await _communicate(process, request.limits.timeout_s)
+ return await _communicate(
+ process,
+ request.limits.timeout_s,
+ request.limits.max_output_chars,
+ )
async def health(self) -> tuple[bool, str]:
if shutil.which(self._bwrap) is None:
@@ -330,6 +336,7 @@ class RestrictedSubprocessBackend(SandboxBackend):
stderr=asyncio.subprocess.PIPE,
cwd=cwd,
env=env,
+ start_new_session=sys.platform != "win32",
)
elif sys.platform == "win32":
process = await asyncio.create_subprocess_exec(
@@ -342,6 +349,7 @@ class RestrictedSubprocessBackend(SandboxBackend):
stderr=asyncio.subprocess.PIPE,
cwd=cwd,
env=env,
+ start_new_session=sys.platform != "win32",
)
else:
process = await asyncio.create_subprocess_shell(
@@ -350,37 +358,112 @@ class RestrictedSubprocessBackend(SandboxBackend):
stderr=asyncio.subprocess.PIPE,
cwd=cwd,
env=env,
+ start_new_session=sys.platform != "win32",
)
except Exception as exc:
return ExecResult(error=f"{type(exc).__name__}: {exc}")
- return await _communicate(process, request.limits.timeout_s)
+ return await _communicate(
+ process,
+ request.limits.timeout_s,
+ request.limits.max_output_chars,
+ )
-async def _communicate(process: asyncio.subprocess.Process, timeout_s: int) -> ExecResult:
+async def _capture_limited(
+ stream: asyncio.StreamReader | None,
+ max_chars: int,
+) -> bytes:
+ """Drain a process stream while retaining bounded head and tail samples."""
+ if stream is None:
+ return b""
+ if max_chars <= 0:
+ while await stream.read(64 * 1024):
+ pass
+ return b""
+
+ head = bytearray()
+ tail = bytearray()
+ total_bytes = 0
+ while True:
+ chunk = await stream.read(64 * 1024)
+ if not chunk:
+ break
+ total_bytes += len(chunk)
+ head_capacity = max_chars - len(head)
+ if head_capacity:
+ accepted = chunk[:head_capacity]
+ head.extend(accepted)
+ chunk = chunk[len(accepted) :]
+ if chunk:
+ tail.extend(chunk)
+ if len(tail) > max_chars:
+ del tail[: len(tail) - max_chars]
+
+ if total_bytes <= max_chars:
+ return bytes(head)
+
+ prefix_size = max_chars // 2
+ suffix_size = max_chars - prefix_size
+ prefix = head[:prefix_size]
+ suffix = tail[-suffix_size:] if suffix_size else bytearray()
+ dropped = total_bytes - len(prefix) - len(suffix)
+ marker = f"\n\n... ({dropped:,} bytes truncated) ...\n\n".encode()
+ return bytes(prefix) + marker + bytes(suffix)
+
+
+async def _terminate_process_tree(process: asyncio.subprocess.Process) -> None:
+ if process.returncode is not None:
+ return
+
+ if sys.platform != "win32":
+ killed_group = False
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ killed_group = True
+ except (ProcessLookupError, PermissionError):
+ pass
+ if not killed_group:
+ process.kill()
+ return
+
+ # ``Process.kill`` only terminates powershell.exe; taskkill's /T flag also
+ # tears down python/compiler children started by it.
try:
- stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout_s)
+ killer = await asyncio.create_subprocess_exec(
+ "taskkill",
+ "/PID",
+ str(process.pid),
+ "/T",
+ "/F",
+ stdout=asyncio.subprocess.DEVNULL,
+ stderr=asyncio.subprocess.DEVNULL,
+ )
+ with suppress(asyncio.TimeoutError):
+ await asyncio.wait_for(killer.wait(), timeout=5.0)
+ except OSError:
+ # Extremely unusual (PATH corruption / stripped-down host), but still
+ # return a timeout result instead of masking it.
+ process.kill()
+
+
+async def _communicate(
+ process: asyncio.subprocess.Process,
+ timeout_s: int,
+ max_output_chars: int,
+) -> ExecResult:
+ stdout_task = asyncio.create_task(_capture_limited(process.stdout, max_output_chars))
+ stderr_task = asyncio.create_task(_capture_limited(process.stderr, max_output_chars))
+ wait_task = asyncio.create_task(process.wait())
+ try:
+ _, stdout, stderr = await asyncio.wait_for(
+ asyncio.gather(wait_task, stdout_task, stderr_task),
+ timeout=timeout_s,
+ )
except asyncio.TimeoutError:
- if sys.platform == "win32" and process.pid:
- # ``Process.kill`` only terminates powershell.exe; taskkill's /T
- # flag also tears down python/compiler children started by it.
- try:
- killer = await asyncio.create_subprocess_exec(
- "taskkill",
- "/PID",
- str(process.pid),
- "/T",
- "/F",
- stdout=asyncio.subprocess.DEVNULL,
- stderr=asyncio.subprocess.DEVNULL,
- )
- with suppress(asyncio.TimeoutError):
- await asyncio.wait_for(killer.wait(), timeout=5.0)
- except OSError:
- # Extremely unusual (PATH corruption / stripped-down host),
- # but still return a timeout result instead of masking it.
- process.kill()
- else:
- process.kill()
+ for task in (wait_task, stdout_task, stderr_task):
+ task.cancel()
+ await asyncio.gather(wait_task, stdout_task, stderr_task, return_exceptions=True)
+ await _terminate_process_tree(process)
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(process.wait(), timeout=5.0)
return ExecResult(timed_out=True, exit_code=124)
diff --git a/tests/services/sandbox/test_sandbox.py b/tests/services/sandbox/test_sandbox.py
index 31dd456e2..edc41ae48 100644
--- a/tests/services/sandbox/test_sandbox.py
+++ b/tests/services/sandbox/test_sandbox.py
@@ -4,6 +4,8 @@ from __future__ import annotations
import asyncio
import os
+import shlex
+import sys
import pytest
@@ -234,6 +236,45 @@ async def test_restricted_subprocess_timeout() -> None:
assert result.exit_code == 124
+async def test_restricted_subprocess_caps_output_while_draining_streams() -> None:
+ backend = RestrictedSubprocessBackend()
+ result = await backend.exec(
+ ExecRequest(
+ command="python3 -c \"print('x' * 50_000, end='')\"",
+ limits=ResourceLimits(timeout_s=10, max_output_chars=1_000),
+ )
+ )
+
+ assert result.ok
+ assert result.stdout.startswith("x")
+ assert result.stdout.endswith("x")
+ assert "bytes truncated" in result.stdout
+ assert len(result.stdout) < 1_500
+
+
[email protected](sys.platform == "win32", reason="POSIX process groups")
+async def test_restricted_subprocess_timeout_kills_descendants(tmp_path) -> None:
+ pid_file = tmp_path / "background.pid"
+ command = f"sleep 30 & echo $! > {shlex.quote(str(pid_file))}; sleep 30"
+ backend = RestrictedSubprocessBackend()
+
+ result = await backend.exec(ExecRequest(command=command, limits=ResourceLimits(timeout_s=1)))
+
+ assert result.timed_out
+ assert result.exit_code == 124
+ child_pid = int(pid_file.read_text().strip())
+ for _ in range(40):
+ try:
+ os.kill(child_pid, 0)
+ except ProcessLookupError:
+ break
+ await asyncio.sleep(0.05)
+ else:
+ pytest.fail("sandbox timeout left a descendant process running")
+
+
@pytest.mark.asyncio
async def test_service_disabled_when_no_backend() -> None:
svc = SandboxService(SandboxSettings(runner_url="", allow_subprocess=False))