rhscope.sandbox¶
Code sandbox for evaluating untrusted Python snippets.
Two backends:
``subprocess`` (default) - a fresh Python subprocess with
-Iisolated mode, a wall-clock timeout, and (on POSIX)resource.setrlimitfor CPU + memory caps. Fast and dependency-free, but not a hard security boundary - a determined attacker can still make network requests and read the filesystem outside the tempdir. Use for model output you understand the provenance of.``docker`` (opt-in) - runs the snippet in a Docker container with
--network=none, dropped capabilities, read-only filesystem, and resource limits. Requires Docker installed and therhscopeuser in thedockergroup (or equivalent). This is a reasonable isolation boundary for untrusted code - not a formal security guarantee, but substantially better than the subprocess backend.
Use:
from rhscope.sandbox import run_python
result = run_python("print(2 + 2)", timeout_seconds=5) # subprocess
result = run_python("print(2 + 2)", backend="docker") # Docker
assert result.ok and result.stdout.strip() == "4"
- class rhscope.sandbox.SandboxResult(exit_code, stdout, stderr, timed_out, duration_seconds)[source]¶
Bases:
objectOutcome of a sandboxed Python run.
- Variables:
exit_code (int) – Subprocess exit code.
0is conventionally success;-signalon POSIX indicates termination by signal.stdout (str) – Captured standard output.
stderr (str) – Captured standard error.
timed_out (bool) – True iff the subprocess was killed by the wall-clock timer.
duration_seconds (float) – Elapsed wall time in seconds.
- Parameters:
- rhscope.sandbox.run_python(code, *, timeout_seconds=10.0, memory_mb=512, cpu_seconds=None, stdin=None, env=None, extra_files=None, backend='subprocess', docker_image='python:3.11-slim')[source]¶
Run a Python snippet in the chosen sandbox backend.
- Parameters:
code (str) – Python source to execute.
timeout_seconds (float) – Wall-clock limit; the subprocess / container is killed if exceeded.
memory_mb (int | None) – Memory cap in MB. Applied via
rlimiton POSIX subprocess backend and via--memoryfor Docker.cpu_seconds (float | None) – CPU-time cap on POSIX subprocess; also drives
--cpusfor Docker. Defaults totimeout_seconds.stdin (str | None) – Optional text to pipe into the subprocess’s stdin.
env (dict[str, str] | None) – Explicit environment variables (replaces the parent env).
Noneinherits from the parent for subprocess; an empty dict for Docker.extra_files (dict[str, str] | None) – Mapping
{relative_path: contents}to materialize in the sandbox working directory before execution.backend (Literal['subprocess', 'docker']) –
"subprocess"(default, fast) or"docker"(network-disabled, read-only FS, dropped capabilities).docker_image (str) – Image tag to run when
backend="docker". Should have Python available atpython.
- Returns:
SandboxResultwith captured outputs and timing.- Raises:
RuntimeError – If
backend="docker"and Docker is not installed or the daemon is not reachable.- Return type: