"""Per-episode workspaces and command execution for the coding tasks. The server runs as root inside its container; every command the policy runs, and every test run, executes as the unprivileged `nobody` user in the episode's workspace, with CPU, memory, file-size and process limits applied by a shell prelude (no preexec_fn, which can deadlock in threaded servers). The server's code and the bug catalog are root-only, so the policy cannot read hidden tests or the original sources. Outside a root container (local development) commands run as the current user. """ import os import shutil import signal import subprocess import tempfile import threading from pathlib import Path NOBODY = 65534 LIMITS = "ulimit -t 120 -v 4000000 -f 100000 -u 512 2>/dev/null; " MAX_OUTPUT = 4000 _SLOTS = threading.BoundedSemaphore(4) AS_ROOT = hasattr(os, "geteuid") and os.geteuid() == 0 def new_workspace(prefix: str = "ws-") -> Path: path = Path(tempfile.mkdtemp(prefix=prefix)) if AS_ROOT: os.chown(path, NOBODY, NOBODY) path.chmod(0o755 if not AS_ROOT else 0o700) return path def give_to_nobody(root: Path): if not AS_ROOT: return for dirpath, dirnames, filenames in os.walk(root): os.chown(dirpath, NOBODY, NOBODY) for name in filenames: p = os.path.join(dirpath, name) if not os.path.islink(p): os.chown(p, NOBODY, NOBODY) def remove(path: Path): shutil.rmtree(path, ignore_errors=True) def _drain(stream, chunks, keep=200_000): kept = 0 while block := stream.read(8192): if kept < keep: chunks.append(block[:keep - kept]) kept += len(chunks[-1]) def run(command: str, cwd: Path, timeout: int = 60, env_extra: dict | None = None) -> tuple[int, str]: """Run a shell command as nobody in cwd. Returns (exit code, combined output, tail-trimmed).""" env = {"PATH": "/usr/local/bin:/usr/bin:/bin", "HOME": str(cwd), "LANG": "C.UTF-8", "PYTHONDONTWRITEBYTECODE": "1", "PYTHONPATH": f"{cwd}:{cwd}/src", "TMPDIR": str(cwd), "MPLBACKEND": "Agg", **(env_extra or {})} kwargs = dict(user=NOBODY, group=NOBODY, extra_groups=[]) if AS_ROOT else {} with _SLOTS: proc = subprocess.Popen(["/bin/sh", "-c", LIMITS + command], cwd=cwd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace", start_new_session=True, **kwargs) chunks = [] reader = threading.Thread(target=_drain, args=(proc.stdout, chunks), daemon=True) reader.start() try: proc.wait(timeout=timeout) timed_out = False except subprocess.TimeoutExpired: timed_out = True try: # stop everything the command started os.killpg(proc.pid, signal.SIGKILL) except (ProcessLookupError, PermissionError): pass proc.wait() reader.join(2) out = "".join(chunks) if timed_out: out += f"\n[timed out after {timeout} s]" return (124 if timed_out else proc.returncode), out def trim(out: str, limit: int = MAX_OUTPUT) -> str: if len(out) <= limit: return out return f"[... {len(out) - limit} characters cut ...]\n" + out[-limit:]