File size: 8,553 Bytes
92c4ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
"""
Container Sandbox

Lightweight Docker-based sandbox for executing untrusted code generated
by the Auto-Dev engines. Implements the SandboxProtocol interface.

Security constraints:
- Ephemeral containers (destroyed after each execution)
- No network access (--network=none)
- Memory limit (256MB)
- Execution timeout (60s default)
- Read-only filesystem with tmpfs for /tmp

Fallback: If Docker is unavailable, uses subprocess isolation with
resource limits (Linux) or basic subprocess timeout (macOS/Windows).
"""

import asyncio
import json
import logging
import subprocess
import tempfile
import time
from pathlib import Path
from typing import Any

logger = logging.getLogger(__name__)

DOCKER_IMAGE = "python:3.11-slim"
DEFAULT_TIMEOUT = 60
DEFAULT_MEMORY_LIMIT = "256m"


class ContainerSandbox:
    """
    Docker-based sandbox implementing SandboxProtocol.

    Falls back to subprocess isolation if Docker is unavailable.
    """

    def __init__(
        self,
        docker_image: str = DOCKER_IMAGE,
        timeout: int = DEFAULT_TIMEOUT,
        memory_limit: str = DEFAULT_MEMORY_LIMIT,
        enable_network: bool = False,
    ):
        self.docker_image = docker_image
        self.timeout = timeout
        self.memory_limit = memory_limit
        self.enable_network = enable_network
        self._docker_available: bool | None = None

    @property
    def docker_available(self) -> bool:
        """Check if Docker is available on the system."""
        if self._docker_available is None:
            try:
                result = subprocess.run(
                    ["docker", "info"],
                    capture_output=True,
                    timeout=5,
                )
                self._docker_available = result.returncode == 0
            except (FileNotFoundError, subprocess.TimeoutExpired):
                self._docker_available = False
                logger.info(
                    "Docker not available — ContainerSandbox will use subprocess fallback"
                )
        return self._docker_available

    async def execute_raw_python(
        self,
        tenant_id: str,
        code: str,
        input_params: dict[str, Any] | None = None,
        timeout: int | None = None,
        safety_level: str = "MEDIUM_RISK",
        **kwargs,
    ) -> dict[str, Any]:
        """
        Execute Python code in an isolated environment.

        Args:
            tenant_id: Tenant ID for tracking
            code: Python code to execute
            input_params: Input parameters passed as JSON on stdin
            timeout: Override default timeout
            safety_level: Ignored in upstream (used by SaaS)

        Returns:
            {
                "status": "success" | "failed",
                "output": str,
                "execution_seconds": float,
                "environment": "docker" | "subprocess",
            }
        """
        effective_timeout = timeout or self.timeout
        params = input_params or {}

        if self.docker_available:
            return await self._execute_docker(
                code, params, effective_timeout, tenant_id
            )
        return await self._execute_subprocess(
            code, params, effective_timeout, tenant_id
        )

    async def _execute_docker(
        self,
        code: str,
        input_params: dict[str, Any],
        timeout: int,
        tenant_id: str,
    ) -> dict[str, Any]:
        """Execute code in a Docker container."""
        start_time = time.monotonic()

        # Write code to a temp file that will be mounted
        with tempfile.NamedTemporaryFile(
            mode="w", suffix=".py", delete=False
        ) as f:
            # Wrap code with input parameter injection
            wrapper = self._build_execution_wrapper(code, input_params)
            f.write(wrapper)
            code_path = f.name

        try:
            cmd = [
                "docker",
                "run",
                "--rm",
                f"--memory={self.memory_limit}",
                f"--cpus=1",
                "--read-only",
                "--tmpfs",
                "/tmp:rw,noexec,nosuid,size=64m",
                "-v",
                f"{code_path}:/sandbox/script.py:ro",
            ]

            if not self.enable_network:
                cmd.extend(["--network", "none"])

            cmd.extend([self.docker_image, "python", "/sandbox/script.py"])

            process = await asyncio.create_subprocess_exec(
                *cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )

            try:
                stdout, stderr = await asyncio.wait_for(
                    process.communicate(), timeout=timeout
                )
            except asyncio.TimeoutError:
                process.kill()
                await process.wait()
                return {
                    "status": "failed",
                    "output": f"Execution timed out after {timeout}s",
                    "execution_seconds": time.monotonic() - start_time,
                    "environment": "docker",
                }

            elapsed = time.monotonic() - start_time
            output = stdout.decode("utf-8", errors="replace").strip()
            errors = stderr.decode("utf-8", errors="replace").strip()

            if process.returncode == 0:
                return {
                    "status": "success",
                    "output": output,
                    "execution_seconds": round(elapsed, 3),
                    "environment": "docker",
                }
            else:
                return {
                    "status": "failed",
                    "output": errors or output,
                    "execution_seconds": round(elapsed, 3),
                    "environment": "docker",
                }
        finally:
            Path(code_path).unlink(missing_ok=True)

    async def _execute_subprocess(
        self,
        code: str,
        input_params: dict[str, Any],
        timeout: int,
        tenant_id: str,
    ) -> dict[str, Any]:
        """
        Fallback: execute code in a subprocess with basic timeout isolation.

        WARNING: This provides weaker isolation than Docker. It should only be
        used for local development when Docker is not available.
        """
        start_time = time.monotonic()
        wrapper = self._build_execution_wrapper(code, input_params)

        with tempfile.NamedTemporaryFile(
            mode="w", suffix=".py", delete=False
        ) as f:
            f.write(wrapper)
            code_path = f.name

        try:
            process = await asyncio.create_subprocess_exec(
                "python3",
                code_path,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )

            try:
                stdout, stderr = await asyncio.wait_for(
                    process.communicate(), timeout=timeout
                )
            except asyncio.TimeoutError:
                process.kill()
                await process.wait()
                return {
                    "status": "failed",
                    "output": f"Execution timed out after {timeout}s",
                    "execution_seconds": time.monotonic() - start_time,
                    "environment": "subprocess",
                }

            elapsed = time.monotonic() - start_time
            output = stdout.decode("utf-8", errors="replace").strip()
            errors = stderr.decode("utf-8", errors="replace").strip()

            if process.returncode == 0:
                return {
                    "status": "success",
                    "output": output,
                    "execution_seconds": round(elapsed, 3),
                    "environment": "subprocess",
                }
            else:
                return {
                    "status": "failed",
                    "output": errors or output,
                    "execution_seconds": round(elapsed, 3),
                    "environment": "subprocess",
                }
        finally:
            Path(code_path).unlink(missing_ok=True)

    @staticmethod
    def _build_execution_wrapper(code: str, input_params: dict[str, Any]) -> str:
        """Wrap user code with input parameter injection."""
        params_json = json.dumps(input_params)
        return f"""
import json
import sys

# Inject input parameters
_INPUT_PARAMS = json.loads('''{params_json}''')

# User code
{code}
"""