File size: 5,574 Bytes
d8328bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Sandboxed Python execution environment for the NexaSci tool server."""

from __future__ import annotations

import builtins
import io
import os
import queue
import shutil
import sys
import tempfile
import traceback
from contextlib import redirect_stderr, redirect_stdout
from dataclasses import dataclass
from multiprocessing import Event, Process, Queue, get_context
from pathlib import Path
from typing import Dict, Iterable, List, Sequence

from tools.schemas import ArtifactRecord, PythonRunRequest, PythonRunResponse

try:  # POSIX-only module; guard for portability.
    import resource
except ImportError:  # pragma: no cover - platform specific.
    resource = None  # type: ignore


ALLOWED_BUILTINS: Sequence[str] = (
    "abs",
    "all",
    "any",
    "bool",
    "complex",
    "dict",
    "enumerate",
    "float",
    "int",
    "len",
    "list",
    "map",
    "max",
    "min",
    "pow",
    "print",
    "range",
    "round",
    "set",
    "slice",
    "sorted",
    "str",
    "sum",
    "tuple",
    "zip",
)


DEFAULT_ALLOWED_MODULES: Sequence[str] = (
    "math",
    "statistics",
    "numpy",
    "scipy",
    "pandas",
    "sympy",
    "matplotlib",
    "matplotlib.pyplot",
    "seaborn",
)


@dataclass(frozen=True)
class SandboxConfig:
    """Configuration describing the sandbox constraints."""

    timeout_s: int = 10
    memory_limit_mb: int = 2048
    working_directory: Path = Path(tempfile.gettempdir()) / "nexasci_python_sandbox"
    allowed_modules: Sequence[str] = DEFAULT_ALLOWED_MODULES

    def ensure_directory(self) -> None:
        """Create the sandbox working directory if it does not already exist."""

        self.working_directory.mkdir(parents=True, exist_ok=True)


def _restricted_builtins() -> Dict[str, object]:
    """Return a dictionary of safe builtins exposed to sandboxed code."""

    return {name: getattr(builtins, name) for name in ALLOWED_BUILTINS}


def _apply_memory_limit(memory_limit_mb: int) -> None:
    """Apply a per-process address space limit if supported by the platform."""

    if resource is None:
        return
    soft_limit = hard_limit = memory_limit_mb * 1024 * 1024
    try:
        resource.setrlimit(resource.RLIMIT_AS, (soft_limit, hard_limit))
    except (ValueError, resource.error):  # pragma: no cover - platform differences.
        pass


def _sandbox_worker(
    code: str,
    queue_: Queue,
    allowed_modules: Sequence[str],
    memory_limit_mb: int,
    work_dir: Path,
    stop_event: Event,
) -> None:
    """Execute user code inside a sandboxed process and report results via queue."""

    stdout_buffer = io.StringIO()
    stderr_buffer = io.StringIO()

    _apply_memory_limit(memory_limit_mb)

    os.chdir(work_dir)

    safe_globals: Dict[str, object] = {"__builtins__": _restricted_builtins()}

    for module_name in allowed_modules:
        try:
            module = __import__(module_name)
            safe_globals[module_name.split(".")[0]] = module
        except Exception as exc:  # pragma: no cover - defensive.
            stderr_buffer.write(f"Failed to import allowed module '{module_name}': {exc}\n")

    try:
        compiled = compile(code, "<sandbox>", "exec")
        with redirect_stdout(stdout_buffer), redirect_stderr(stderr_buffer):
            exec(compiled, safe_globals, {})
    except Exception:  # pragma: no cover - propagate errors to stderr.
        traceback.print_exc(file=stderr_buffer)
    finally:
        queue_.put(
            {
                "stdout": stdout_buffer.getvalue(),
                "stderr": stderr_buffer.getvalue(),
            }
        )
        stop_event.set()


def _collect_artifacts(directory: Path) -> List[ArtifactRecord]:
    """Collect non-code artifacts generated within the sandbox directory."""

    artifacts: List[ArtifactRecord] = []
    for path in directory.iterdir():
        if path.is_dir():
            continue
        if path.suffix == ".py":
            continue
        artifacts.append(
            ArtifactRecord(
                name=path.name,
                path=str(path),
                mime_type=None,
            )
        )
    return artifacts


def execute_python(request: PythonRunRequest, config: SandboxConfig) -> PythonRunResponse:
    """Execute Python code within the configured sandbox."""

    config.ensure_directory()
    run_dir = Path(tempfile.mkdtemp(dir=config.working_directory))
    queue_: Queue = get_context("spawn").Queue()
    stop_event: Event = get_context("spawn").Event()

    process = Process(
        target=_sandbox_worker,
        kwargs={
            "code": request.code,
            "queue_": queue_,
            "allowed_modules": config.allowed_modules,
            "memory_limit_mb": config.memory_limit_mb,
            "work_dir": run_dir,
            "stop_event": stop_event,
        },
        daemon=True,
    )
    process.start()

    try:
        stop_event.wait(timeout=request.timeout_s or config.timeout_s)
    finally:
        if process.is_alive():
            process.terminate()
        process.join(timeout=1)

    stdout = ""
    stderr = ""
    try:
        result = queue_.get_nowait()
        stdout = result.get("stdout", "")
        stderr = result.get("stderr", "")
    except queue.Empty:
        stderr = "Execution timed out or produced no output."

    artifacts = _collect_artifacts(run_dir)

    shutil.rmtree(run_dir, ignore_errors=True)

    return PythonRunResponse(stdout=stdout, stderr=stderr, artifacts=artifacts)


__all__ = ["DEFAULT_ALLOWED_MODULES", "SandboxConfig", "execute_python"]