File size: 12,644 Bytes
adf68aa c786dae adf68aa c786dae adf68aa | 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 | """Contract runner: isolated interpreter, bounded resources, no bot I/O except stdio/imports.
With PYBOT_SANDBOX_URL set, runs go to a sidecar (`python sandbox.py serve`, same image) instead."""
from __future__ import annotations
import base64
import hmac
import io
import json
import logging
import os
import signal
import subprocess
import sys
import tarfile
import tempfile
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from legion.isolation import command as isolate_command
from legion.world import ToolError
# The sidecar's caps: a request, and an extracted tree. Merges send main + the PR's whole tree
# for the shared tests: main grows by about one file per merge, so the cap allows a long run.
MAX_REQUEST_BYTES, MAX_TREE_BYTES, MAX_TREE_MEMBERS = 64 << 20, 64 << 20, 20000
log = logging.getLogger(__name__)
SHIM = r'''
import sys, os, resource, runpy
root = os.path.realpath(sys.argv[1])
resource.setrlimit(resource.RLIMIT_AS, (512 << 20, 512 << 20))
resource.setrlimit(resource.RLIMIT_CPU, (300, 300))
resource.setrlimit(resource.RLIMIT_FSIZE, (1 << 20, 1 << 20))
resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64))
resource.setrlimit(resource.RLIMIT_NPROC, (0, 0))
sys.dont_write_bytecode = True
sys.path.insert(0, root)
allowed = set(sys.stdlib_module_names) | {'bot'}
blocked = {'ctypes', '_ctypes', '_posixsubprocess', 'subprocess', 'socket', '_socket', 'multiprocessing'}
def audit(event, args):
if event == 'import':
name = args[0].split('.')[0]
if name not in allowed or name in blocked:
raise PermissionError('only standard-library bot imports are allowed')
if event == 'open':
path, mode, flags = args
if not isinstance(path, (str, bytes, os.PathLike)):
raise PermissionError('file access is disabled')
path = os.path.realpath(os.fsdecode(path))
if flags & (os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND):
raise PermissionError('file writes are disabled')
roots = (root + os.sep, os.path.realpath(sys.base_prefix) + os.sep)
if not path.startswith(roots) or not path.endswith(('.py', '.pyc', '.so')):
raise PermissionError('file access is disabled except module loading')
if event.startswith(('socket.', 'subprocess.', 'ctypes.', 'os.kill', 'signal.')) or event in {
'os.system', 'os.exec', 'os.fork', 'os.forkpty', 'os.posix_spawn', 'os.kill', 'os.killpg',
'os.remove', 'os.rename', 'os.mkdir', 'os.rmdir', 'os.chmod', 'os.link',
'os.symlink', 'os.truncate', 'os.putenv', 'os.unsetenv'}:
raise PermissionError('bot side effects are disabled')
import signal, _signal
# Signals to other processes: os.kill/killpg and signal.pthread_kill raise audit events
# (blocked above); pidfd_send_signal does not, so remove every sender from the modules.
for module in (os, sys.modules.get('posix'), signal, _signal):
for name in ('kill', 'killpg', 'pthread_kill', 'pidfd_send_signal'):
if module is not None and hasattr(module, name):
delattr(module, name)
sys.addaudithook(audit)
runpy.run_module('bot', run_name='__main__')
'''
# The repository's own tests matching a pattern under tests/ (python -m unittest discover -s
# tests -p <pattern>, as agents run them). Same limits as the bot; tests may read any file, so
# its hook keeps only the side-effect blocks (the sidecar has no namespaces to stop them).
TESTS_SHIM = r'''
import sys, os, resource, unittest
root = os.path.realpath(sys.argv[1])
resource.setrlimit(resource.RLIMIT_AS, (512 << 20, 512 << 20))
resource.setrlimit(resource.RLIMIT_FSIZE, (1 << 20, 1 << 20))
resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64))
resource.setrlimit(resource.RLIMIT_NPROC, (0, 0))
sys.dont_write_bytecode = True
sys.path.insert(0, root)
blocked = {'ctypes', '_ctypes', '_posixsubprocess', 'subprocess', 'socket', '_socket', 'multiprocessing'}
def audit(event, args):
if event == 'import' and args[0].split('.')[0] in blocked:
raise PermissionError('test imports of ' + args[0] + ' are disabled')
if event == 'open' and args[2] & (os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND):
raise PermissionError('file writes are disabled')
if event.startswith(('socket.', 'subprocess.', 'ctypes.', 'os.kill', 'signal.')) or event in {
'os.system', 'os.exec', 'os.fork', 'os.forkpty', 'os.posix_spawn', 'os.kill', 'os.killpg',
'os.remove', 'os.rename', 'os.mkdir', 'os.rmdir', 'os.chmod', 'os.link',
'os.symlink', 'os.truncate', 'os.putenv', 'os.unsetenv'}:
raise PermissionError('test side effects are disabled')
sys.addaudithook(audit)
tests = os.path.join(root, 'tests')
suite = (unittest.defaultTestLoader.discover(tests, pattern=sys.argv[2], top_level_dir=tests)
if os.path.isdir(tests) else unittest.TestSuite())
sys.exit(not unittest.TextTestRunner().run(suite).wasSuccessful())
'''
def run(root: Path, lines: list[str], timeout: float = 300, isolate: bool = True) -> dict:
if not lines or len(lines) > 200 or any(not isinstance(x, str) or '\n' in x or '\r' in x
or len(x) > 16000 for x in lines):
return {"ok": False, "status": "supply 1–200 single input lines (at most 16000 chars each)"}
if isolate and (url := os.environ.get("PYBOT_SANDBOX_URL")): # the sidecar: no secrets in its container
# .py only: all the shim lets a bot open
return _remote(os.path.expandvars(url), root, {"lines": lines, "timeout": timeout}, "*.py")
return _local(root, lines, timeout, isolate)
def run_tests(root: Path, pattern: str, timeout: float = 60, isolate: bool = True) -> dict:
"""Run root's tests/ files matching pattern, isolated like run() (in the sidecar with
PYBOT_SANDBOX_URL). ok when they pass (or none match); status "timeout" past timeout;
output: their combined output (1 MiB)."""
if isolate and (url := os.environ.get("PYBOT_SANDBOX_URL")): # tests read data files: the whole tree
return _remote(os.path.expandvars(url), root, {"tests": pattern, "timeout": timeout}, "*")
with tempfile.TemporaryDirectory() as tmp, open(Path(tmp) / "out", "w+b") as out:
status = _isolated(root, tmp, [TESTS_SHIM, str(root.resolve()), pattern], b"", timeout,
out, out, isolate)
out.seek(0)
return {"ok": status == "ok", "status": status,
"output": out.read(1 << 20).decode(errors="replace")}
def _remote(url: str, root: Path, payload: dict, files: str) -> dict:
"""POST payload and the tree's files matching the glob to the sidecar; its reply."""
buf, sent = io.BytesIO(), 0
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for f in sorted(root.rglob(files)):
# regular files only: the sidecar refuses links (and never gets a link's target)
if ".git" not in f.relative_to(root).parts and f.is_file() and not f.is_symlink():
tar.add(f, f.relative_to(root).as_posix())
sent += 1
body = json.dumps({**payload, "tree": base64.b64encode(buf.getvalue()).decode()}).encode()
req = urllib.request.Request(f"{url.rstrip('/')}/run", body, method="POST", headers={
"Content-Type": "application/json",
"X-Sandbox-Token": os.environ.get("PYBOT_SANDBOX_TOKEN", "")})
try:
with urllib.request.urlopen(req, timeout=payload["timeout"] + 30) as r:
return json.load(r)
except (OSError, ValueError) as e: # never "your bot failed" when the runner is down
if isinstance(e, urllib.error.HTTPError): # it answered and refused: say why in the log
log.warning("sandbox sidecar refused a %s run: HTTP %s (%d files, %d bytes sent)",
"tests" if "tests" in payload else "bot", e.code,
sent, len(body))
raise ToolError(f"bot runner unavailable ({type(e).__name__}); retry later", "busy",
retry_after_s=30) from None
def _isolated(root: Path, tmp: str, args: list[str], data: bytes, timeout: float, out, err,
isolate: bool = True) -> str:
"""Run `python -I -S -c *args` (isolated: root read-only), data on stdin; the status."""
argv = [sys.executable, "-I", "-S", "-c", *args]
if isolate:
argv = isolate_command(argv, Path(tmp) / "root", cwd=root.resolve(),
readonly=[root.resolve()], python_only=True)
proc = subprocess.Popen(argv, cwd=tmp, env={}, stdin=subprocess.PIPE, stdout=out, stderr=err,
start_new_session=True)
try:
proc.communicate(data, timeout=timeout)
return "ok" if proc.returncode == 0 else f"exit {proc.returncode}"
except subprocess.TimeoutExpired:
os.killpg(proc.pid, signal.SIGKILL)
proc.wait()
return "timeout"
def _local(root: Path, lines: list[str], timeout: float, isolate: bool = True) -> dict:
with (tempfile.TemporaryDirectory() as tmp,
open(Path(tmp) / "out", "w+b") as out,
open(Path(tmp) / "err", "w+b") as err):
status = _isolated(root, tmp, [SHIM, str(root.resolve())],
('\n'.join(lines) + '\n').encode(), timeout, out, err, isolate)
out.seek(0)
err.seek(0)
replies = out.read(1 << 20).decode(errors="replace").splitlines()
ok = status == "ok" and len(replies) == len(lines) and all(x.strip() for x in replies)
return {"ok": ok, "status": status, "replies": replies,
"stderr": err.read(4096).decode(errors="replace"), "timeout_s": timeout}
class _Handler(BaseHTTPRequestHandler):
"""POST /run {lines, timeout, tree: base64 tar.gz} -> run()'s dict, or {tests: pattern,
timeout, tree} -> run_tests()'s. The sidecar only: `unshare` is blocked in HF Jobs
containers, so the job boundary (no secrets) replaces it."""
def do_POST(self):
token = os.environ.get("PYBOT_SANDBOX_TOKEN", "")
n = int(self.headers.get("Content-Length") or 0)
if self.path != "/run" or not token or not hmac.compare_digest(
self.headers.get("X-Sandbox-Token", ""), token) or not 0 < n <= MAX_REQUEST_BYTES:
return self._send(403, {"ok": False, "status": "refused"})
try:
req = json.loads(self.rfile.read(n))
timeout = min(300, float(req.get("timeout", 300))) # 300 first: an int, as local
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "tree"
with tarfile.open(fileobj=io.BytesIO(base64.b64decode(req["tree"])), mode="r:gz") as t:
count = total = 0
for m in t: # before extracting: a small .tar.gz can expand hugely
count, total = count + 1, total + m.size
if count > MAX_TREE_MEMBERS or total > MAX_TREE_BYTES or not (m.isfile() or m.isdir()):
raise ValueError("tree: too many or too large members, or not files and dirs")
t.extractall(root, filter="data") # no absolute paths, links or ../
if "tests" in req:
if not isinstance(req["tests"], str):
raise ValueError("tests")
out = run_tests(root, req["tests"], timeout, isolate=False)
elif not isinstance(req["lines"], list):
raise ValueError("lines") # run() checks each line
else:
out = run(root, req["lines"], timeout, isolate=False)
except (KeyError, ValueError, TypeError, tarfile.TarError, OSError) as e:
return self._send(400, {"ok": False, "status": f"bad request: {type(e).__name__}"})
self._send(200, out)
def _send(self, code, obj):
data = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
if __name__ == "__main__" and sys.argv[1:] == ["serve"]:
if not os.environ.get("PYBOT_SANDBOX_TOKEN"):
sys.exit("sandbox.py serve: PYBOT_SANDBOX_TOKEN is not set") # else every call is refused
from legion.isolation import protect_supervisor
protect_supervisor() # a bot under this uid cannot read this process's env or memory
ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8000"))), _Handler).serve_forever()
|