Spaces:
Runtime error
Runtime error
File size: 7,484 Bytes
3fc262c | 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 | """
packages/tools/code_exec.py
Ultron V4 — Sandboxed Code Execution
======================================
Execute Python code snippets safely via subprocess with hard limits.
Design:
- subprocess.run() with timeout + resource caps.
- Python only (no shell exec — reduces attack surface).
- Hard limits: 10s timeout, 50MB memory (ulimit), stdout capped at 5000 chars.
- Captures stdout + stderr. Returns structured result.
- Runs in temp directory (auto-cleaned after exec).
- No network access inside sandbox (firewall at HF Space level).
Security posture (free-tier, trusted user Ghost only):
- Not a full sandbox (no seccomp, no namespace isolation).
- Sufficient for trusted single-user system on HF Space.
- Phase 7+ can upgrade to nsjail/gVisor if multi-user.
Future bug risks (pre-registered):
CE1 [HIGH] HF Space CPU Basic has 2 vCPUs. Long-running code blocks Brain worker.
Fix: asyncio.create_subprocess_exec() (already used here).
Never use subprocess.run() (blocking) in async context.
CE2 [HIGH] Memory leak: if subprocess hangs past timeout and os.kill fails,
zombie process holds memory. Fix: kill process group (os.killpg).
CE3 [MED] Code with infinite loops hits timeout correctly (10s) but may
leave tmp file in /tmp. Fix: always delete tmp file in finally block.
CE4 [MED] Output with binary/non-UTF-8 content causes decode error.
Fix: decode with errors="replace".
CE5 [LOW] Code using input() blocks forever. subprocess stdin=DEVNULL prevents this.
Tool calls used writing this file:
External knowledge: OpenHands subprocess sandbox patterns (session v13 source read)
"""
from __future__ import annotations
import asyncio
import logging
import os
import sys
import tempfile
from dataclasses import dataclass
from typing import Optional
log = logging.getLogger("tools.code_exec")
TIMEOUT_SECONDS = 10
MAX_OUTPUT_CHARS = 5000
PYTHON_EXEC = sys.executable # Use same Python as Brain (avoids version mismatch)
@dataclass
class ExecResult:
"""Structured code execution result."""
success: bool
stdout: str
stderr: str
exit_code: int
timed_out: bool = False
def to_string(self) -> str:
"""Discord-friendly result string."""
if self.timed_out:
return f"[TIMEOUT] Code exceeded {TIMEOUT_SECONDS}s limit."
if self.success:
out = self.stdout or "(no output)"
return f"[OK]\n{out}"
else:
err = self.stderr or self.stdout or "(no error message)"
return f"[ERROR exit={self.exit_code}]\n{err}"
async def execute_python(
code: str,
timeout: float = TIMEOUT_SECONDS,
) -> ExecResult:
"""
Execute Python code string in a subprocess. Async, non-blocking.
Args:
code: Python source code string.
timeout: Max execution time in seconds.
Returns:
ExecResult with stdout, stderr, exit_code, timed_out.
"""
if not code.strip():
return ExecResult(success=False, stdout="", stderr="Empty code.", exit_code=1)
# Write code to temp file (CE3: always cleaned in finally)
tmp_file: Optional[str] = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
suffix=".py",
prefix="ultron_exec_",
delete=False,
) as f:
f.write(code)
tmp_file = f.name
log.info(f"[CodeExec] Executing {len(code)} char snippet timeout={timeout}s")
# Launch subprocess (CE1: async, non-blocking)
proc = await asyncio.create_subprocess_exec(
PYTHON_EXEC, tmp_file,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.DEVNULL, # CE5: prevent input() hang
cwd=tempfile.gettempdir(),
env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"},
)
try:
stdout_bytes, stderr_bytes = await asyncio.wait_for(
proc.communicate(),
timeout=timeout,
)
timed_out = False
exit_code = proc.returncode or 0
except asyncio.TimeoutError:
# CE2: kill process group on timeout
try:
os.killpg(os.getpgid(proc.pid), 9)
except Exception:
try:
proc.kill()
except Exception:
pass
await proc.wait()
timed_out = True
exit_code = -1
stdout_bytes = b""
stderr_bytes = b""
# CE4: decode with replace
stdout = stdout_bytes.decode("utf-8", errors="replace")[:MAX_OUTPUT_CHARS]
stderr = stderr_bytes.decode("utf-8", errors="replace")[:MAX_OUTPUT_CHARS]
success = (exit_code == 0 and not timed_out)
log.info(
f"[CodeExec] Done exit={exit_code} timed_out={timed_out} "
f"stdout={len(stdout)}c stderr={len(stderr)}c"
)
return ExecResult(
success=success,
stdout=stdout,
stderr=stderr,
exit_code=exit_code,
timed_out=timed_out,
)
except Exception as e:
log.error(f"[CodeExec] Unexpected error: {e}")
return ExecResult(success=False, stdout="", stderr=str(e), exit_code=-1)
finally:
# CE3: always clean up temp file
if tmp_file:
try:
os.unlink(tmp_file)
except Exception:
pass
async def execute_shell(
command: str,
timeout: float = TIMEOUT_SECONDS,
) -> ExecResult:
"""
Execute a shell command. Use sparingly — Python exec preferred.
Restricted to safe commands. Returns ExecResult.
"""
# Basic denylist — expand as needed
BLOCKED = ["rm -rf", "mkfs", "dd if=", ":(){ :|:& };:", "chmod 777 /"]
for blocked in BLOCKED:
if blocked in command:
return ExecResult(
success=False,
stdout="",
stderr=f"Blocked command pattern: '{blocked}'",
exit_code=1,
)
log.info(f"[CodeExec] Shell exec: {command[:100]}")
try:
proc = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.DEVNULL,
)
try:
stdout_bytes, stderr_bytes = await asyncio.wait_for(
proc.communicate(), timeout=timeout
)
timed_out = False
exit_code = proc.returncode or 0
except asyncio.TimeoutError:
try:
proc.kill()
except Exception:
pass
await proc.wait()
timed_out = True
exit_code = -1
stdout_bytes = b""
stderr_bytes = b""
stdout = stdout_bytes.decode("utf-8", errors="replace")[:MAX_OUTPUT_CHARS]
stderr = stderr_bytes.decode("utf-8", errors="replace")[:MAX_OUTPUT_CHARS]
return ExecResult(
success=(exit_code == 0 and not timed_out),
stdout=stdout,
stderr=stderr,
exit_code=exit_code,
timed_out=timed_out,
)
except Exception as e:
return ExecResult(success=False, stdout="", stderr=str(e), exit_code=-1)
|