File size: 1,728 Bytes
0109502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
import json, shutil, subprocess, tempfile
from pathlib import Path
from .sandbox import ExecutionResult

def docker_available() -> bool:
    return shutil.which("docker") is not None

def run_code_docker(code: str, timeout_seconds: int = 3,
                    image: str = "python-lora-sandbox:latest") -> ExecutionResult:
    if not docker_available():
        raise RuntimeError("Docker is required for production sandbox mode but was not found on PATH.")

    with tempfile.TemporaryDirectory(prefix="py_lora_docker_") as td:
        code_path = Path(td) / "candidate.py"
        code_path.write_text(code, encoding="utf-8")
        cmd = [
            "docker", "run", "--rm",
            "--network", "none",
            "--read-only",
            "--cap-drop", "ALL",
            "--security-opt", "no-new-privileges",
            "--pids-limit", "32",
            "--memory", "256m",
            "--cpus", "1",
            "--tmpfs", "/tmp:rw,noexec,nosuid,size=32m",
            "--user", "65534:65534",
            "-v", f"{code_path.resolve()}:/work/candidate.py:ro",
            "-w", "/work",
            image, "python", "-I", "/work/candidate.py",
        ]
        try:
            p = subprocess.run(cmd, text=True, capture_output=True, timeout=timeout_seconds + 5)
            return ExecutionResult(
                True, p.returncode == 0, False, p.returncode,
                p.stdout[-4000:], p.stderr[-4000:],
                "passed" if p.returncode == 0 else "failed",
                "docker_hardened", None
            )
        except subprocess.TimeoutExpired:
            return ExecutionResult(True, False, True, None, "", "", "failed", "docker_hardened", None)