File size: 11,322 Bytes
ea3ef49
 
8628c98
ea3ef49
 
 
 
 
 
 
 
93ccb02
8628c98
ea3ef49
8628c98
93ccb02
8628c98
 
 
 
 
 
 
 
 
5844be3
 
ea3ef49
8628c98
ea3ef49
8628c98
 
 
 
 
 
 
5844be3
93ccb02
8628c98
 
ea3ef49
 
 
 
 
 
 
93ccb02
ea3ef49
93ccb02
ea3ef49
8628c98
56440ff
8628c98
ea3ef49
93ccb02
 
 
 
ea3ef49
8628c98
 
 
ea3ef49
93ccb02
 
 
5844be3
93ccb02
 
 
 
 
 
 
 
 
ea3ef49
8628c98
 
 
ea3ef49
 
 
8628c98
 
ea3ef49
 
 
 
 
 
 
 
 
 
8628c98
ea3ef49
 
 
8628c98
ea3ef49
 
 
93ccb02
8628c98
 
ea3ef49
 
 
 
5844be3
93ccb02
8628c98
 
ea3ef49
 
 
 
 
 
8628c98
ea3ef49
 
 
 
8628c98
 
 
 
 
 
 
 
 
 
 
 
ea3ef49
 
8628c98
 
 
ea3ef49
 
 
 
 
 
 
93ccb02
 
 
 
8628c98
 
ea3ef49
8628c98
ea3ef49
8628c98
 
 
 
ea3ef49
 
 
8628c98
 
ea3ef49
 
 
 
 
 
93ccb02
ea3ef49
 
 
 
 
 
 
 
 
 
 
8628c98
 
ea3ef49
8628c98
ea3ef49
8628c98
 
 
 
 
ea3ef49
 
 
5844be3
 
 
 
ea3ef49
8628c98
ea3ef49
8628c98
 
 
 
 
 
 
 
 
ea3ef49
93ccb02
8628c98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fedbe97
 
8628c98
fedbe97
8628c98
 
 
 
 
 
fedbe97
8628c98
 
 
 
 
ea3ef49
 
 
8628c98
ea3ef49
 
 
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
"""
Execution Runner Engines.
Supports fast local subprocess execution and isolated air-gapped Docker sandboxes.
"""

import os
import shutil
import subprocess
import sys
import tempfile
import time
import uuid
from typing import Dict, Optional

from language_core.runtime_events import redact_sensitive_text
from runtime_environment.active_runs import GLOBAL_ACTIVE_RUNS
from runtime_environment.env_injection import (
    create_ephemeral_docker_env_file,
    remove_ephemeral_env_file,
    resolve_runner_workspace_env,
)
from runtime_environment.process_utils import (
    DEFAULT_PACKAGE_CACHE_DIR, ExecutionResult, build_docker_run_command,
    get_sanitized_env, kill_process_tree, resolve_package_cache_dir,
)


class LocalSubprocessRunner:
    """Fast local subprocess execution engine with active tracking, credential scrubbing, and tree cleanup."""

    def __init__(
        self,
        timeout_sec: float = 5.0,
        run_id: Optional[str] = None,
        package_cache_dir: Optional[str] = None,
        workspace_env: Optional[Dict[str, str]] = None,
    ):
        self.timeout_sec = min(float(timeout_sec), 5.0) if timeout_sec and float(timeout_sec) > 0 else 5.0
        self.run_id = run_id
        self.package_cache_dir = package_cache_dir
        self.workspace_env = workspace_env

    def execute_code(self, python_code: str) -> ExecutionResult:
        start_time = time.perf_counter()
        with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False, encoding="utf-8") as temp_file:
            temp_file.write(python_code)
            temp_path = temp_file.name

        proc = None
        try:
            proc = subprocess.Popen(
                [sys.executable, temp_path],
                stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
                cwd=tempfile.gettempdir(),
                env=get_sanitized_env(package_cache_dir=self.package_cache_dir, workspace_env=self.workspace_env),
            )
            if self.run_id:
                GLOBAL_ACTIVE_RUNS.record_process(self.run_id, proc)

            stdout, stderr = proc.communicate(timeout=self.timeout_sec)
            return ExecutionResult(
                success=(proc.returncode == 0), exit_code=proc.returncode,
                stdout=redact_sensitive_text(stdout or ""), stderr=redact_sensitive_text(stderr or ""),
                duration_ms=(time.perf_counter() - start_time) * 1000.0, mode="local_subprocess",
            )
        except subprocess.TimeoutExpired:
            if proc:
                try:
                    kill_process_tree(proc)
                except Exception:
                    pass
                try:
                    stdout, stderr = proc.communicate(timeout=1.0)
                except Exception:
                    stdout, stderr = "", ""
            else:
                stdout, stderr = "", ""
            stdout_str = stdout if isinstance(stdout, str) else (stdout.decode() if stdout else "")
            return ExecutionResult(
                success=False, exit_code=-1, stdout=stdout_str,
                stderr=f"Execution timed out after {self.timeout_sec} seconds.",
                duration_ms=(time.perf_counter() - start_time) * 1000.0, mode="local_subprocess",
            )
        except Exception as exc:
            return ExecutionResult(
                success=False, exit_code=-1, stdout="", stderr=str(exc),
                duration_ms=(time.perf_counter() - start_time) * 1000.0, mode="local_subprocess",
            )
        finally:
            if os.path.exists(temp_path):
                try:
                    os.remove(temp_path)
                except OSError:
                    pass


class DockerSandboxRunner:
    """Isolated container engine with manylinux glibc compatibility, memory/CPU caps, and --network none."""

    def __init__(
        self,
        image_name: str = "python:3.12-slim",
        memory_limit: str = "128m",
        cpu_limit: str = "0.5",
        timeout_sec: float = 5.0,
        run_id: Optional[str] = None,
        package_cache_dir: Optional[str] = None,
        workspace_env: Optional[Dict[str, str]] = None,
    ):
        self.image_name = image_name
        self.memory_limit = memory_limit
        self.cpu_limit = cpu_limit
        self.timeout_sec = min(float(timeout_sec), 5.0) if timeout_sec and float(timeout_sec) > 0 else 5.0
        self.run_id = run_id
        self.package_cache_dir = package_cache_dir
        self.workspace_env = workspace_env

    @staticmethod
    def is_docker_available() -> bool:
        if shutil.which("docker") is None:
            return False
        try:
            res = subprocess.run(["docker", "info"], capture_output=True, timeout=3.0)
            return res.returncode == 0
        except Exception:
            return False

    def build_docker_command(self, temp_dir: str, container_name: str, env_file: Optional[str] = None) -> list[str]:
        """Construct air-gapped Docker command with optional read-only cached packages mount."""
        return build_docker_run_command(
            temp_dir=temp_dir,
            container_name=container_name,
            image_name=self.image_name,
            memory_limit=self.memory_limit,
            cpu_limit=self.cpu_limit,
            package_cache_dir=self.package_cache_dir,
            env_file=env_file,
        )

    def execute_code(self, python_code: str) -> ExecutionResult:
        if not self.is_docker_available():
            raise RuntimeError(
                "[ERR-SANDBOX-UNAVAILABLE] Docker daemon is not running or accessible on the host machine."
            )

        start_time = time.perf_counter()
        temp_dir = tempfile.mkdtemp(prefix="alli_sandbox_")
        script_path = os.path.join(temp_dir, "script.py")
        with open(script_path, "w", encoding="utf-8") as file:
            file.write(python_code)

        container_name = f"alli_sandbox_{uuid.uuid4().hex[:12]}"
        if self.run_id:
            GLOBAL_ACTIVE_RUNS.record_container(self.run_id, container_name)

        env_file = create_ephemeral_docker_env_file(resolve_runner_workspace_env(self.workspace_env))
        docker_cmd = self.build_docker_command(temp_dir, container_name, env_file=env_file)
        try:
            process = subprocess.run(docker_cmd, capture_output=True, text=True, timeout=self.timeout_sec)
            duration_ms = (time.perf_counter() - start_time) * 1000.0
            if process.returncode == 125:
                raise RuntimeError(
                    f"[ERR-SANDBOX-UNAVAILABLE] Docker daemon failed to start sandbox container: {process.stderr.strip()}"
                )
            return ExecutionResult(
                success=(process.returncode == 0),
                exit_code=process.returncode,
                stdout=redact_sensitive_text(process.stdout),
                stderr=redact_sensitive_text(process.stderr),
                duration_ms=duration_ms,
                mode="docker_sandbox",
                memory_limit=self.memory_limit,
                cpu_limit=self.cpu_limit,
            )
        except subprocess.TimeoutExpired:
            subprocess.run(["docker", "rm", "-f", container_name], capture_output=True, timeout=5.0)
            duration_ms = (time.perf_counter() - start_time) * 1000.0
            return ExecutionResult(
                success=False,
                exit_code=-1,
                stdout="",
                stderr=f"Docker container timed out after {self.timeout_sec}s and was terminated.",
                duration_ms=duration_ms,
                mode="docker_sandbox",
                memory_limit=self.memory_limit,
                cpu_limit=self.cpu_limit,
            )
        except RuntimeError:
            raise
        except Exception as exc:
            raise RuntimeError(f"[ERR-SANDBOX-UNAVAILABLE] Docker sandbox execution failed: {exc}") from exc
        finally:
            remove_ephemeral_env_file(env_file)
            try:
                subprocess.run(["docker", "rm", "-f", container_name], capture_output=True, timeout=5.0)
            except Exception:
                pass
            shutil.rmtree(temp_dir, ignore_errors=True)


# Phase 15 Production Sandbox Alias
AirGappedDockerRunner = DockerSandboxRunner


class RuntimeRunner:
    """Unified fail-closed runtime dispatcher with zero silent Docker-to-host downgrades."""

    def __init__(
        self,
        default_mode: str = "auto",
        timeout_sec: float = 5.0,
        run_id: Optional[str] = None,
        package_cache_dir: Optional[str] = None,
        sandbox_required: bool = False,
        workspace_env: Optional[Dict[str, str]] = None,
    ):
        self.default_mode = default_mode
        self.run_id = run_id
        self.package_cache_dir = package_cache_dir
        self.sandbox_required = sandbox_required
        self.local_runner = LocalSubprocessRunner(
            timeout_sec=timeout_sec, run_id=run_id, package_cache_dir=package_cache_dir, workspace_env=workspace_env
        )
        self.docker_runner = DockerSandboxRunner(
            timeout_sec=timeout_sec, run_id=run_id, package_cache_dir=package_cache_dir, workspace_env=workspace_env
        )

    def _run_docker_strict(self, python_code: str, enforcement_msg: str) -> ExecutionResult:
        if not self.docker_runner.is_docker_available():
            raise RuntimeError(f"[ERR-SANDBOX-UNAVAILABLE] {enforcement_msg}")
        try:
            return self.docker_runner.execute_code(python_code)
        except RuntimeError as exc:
            msg = str(exc)
            if "[ERR-SANDBOX-UNAVAILABLE]" in msg:
                raise
            raise RuntimeError(f"[ERR-SANDBOX-UNAVAILABLE] Docker sandbox execution failed: {msg}") from exc

    def run(self, python_code: str, mode: Optional[str] = None, sandbox_required: Optional[bool] = None) -> ExecutionResult:
        selected_mode = (mode or self.default_mode or "auto").strip().lower()
        enforce_docker = os.environ.get("ENFORCE_DOCKER_SANDBOX", "false").lower() in ("true", "1", "yes")
        is_production = os.environ.get("STAGE", "development").lower() == "production"
        require_sandbox = self.sandbox_required if sandbox_required is None else bool(sandbox_required)

        if enforce_docker or require_sandbox or (is_production and selected_mode in ("docker", "docker_sandbox", "auto")):
            return self._run_docker_strict(
                python_code,
                "Docker sandbox is enforced (production environment, ENFORCE_DOCKER_SANDBOX=true, or sandbox_required=True), "
                "but Docker daemon is not running or accessible. Execution failed closed for security.",
            )

        if selected_mode in ("docker", "docker_sandbox"):
            return self._run_docker_strict(
                python_code,
                "Docker sandbox was explicitly requested, but Docker daemon is not available or misconfigured. Execution failed closed.",
            )

        if selected_mode == "auto":
            if self.docker_runner.is_docker_available():
                return self.docker_runner.execute_code(python_code)
            return self.local_runner.execute_code(python_code)

        return self.local_runner.execute_code(python_code)