"""Run model-controlled processes as perf-agent, apart from the CI uid's secrets. The CI uid (spindle-workflow) holds WISP_APP_PASSWORD and OPENROUTER_API_KEY in its environment. The daemon, CLI and kernels run model output, so they run as perf-agent through `sudo -n -u perf-agent env -i`, with only ENV_ALLOWLIST passed through, and write only under a 0700 directory perf-agent creates. A different uid cannot read the CI processes' /proc//environ or memory; `Sandbox.open` probes the supplied protected PIDs before measurement and raises if it observes readable data. """ from __future__ import annotations import os from pathlib import Path import subprocess import time USER = "perf-agent" ENV_ALLOWLIST = ("PATH", "TANGLED_REF", "TANGLED_PIPELINE_KIND") class IsolationError(RuntimeError): pass def sudo(*argv, **kwargs): return subprocess.run(["sudo", "-n", "-u", USER, *argv], **kwargs) class Sandbox: def __init__(self, directory: Path): self.directory = directory self.closed = False @classmethod def open(cls, protected_pids): """Probe the uid split and return a sandbox, or raise IsolationError.""" if sudo("true", capture_output=True).returncode: raise IsolationError(f"sudo -n -u {USER} is not available") for pid in protected_pids: for name in ("environ", "mem"): probe = sudo("cat", f"/proc/{pid}/{name}", capture_output=True) if probe.returncode == 0 and probe.stdout: raise IsolationError(f"{USER} can read /proc/{pid}/{name}") if sudo("test", "-r", "test/perf/run.py").returncode: raise IsolationError(f"{USER} cannot read the checkout") made = sudo( "mktemp", "-d", "/tmp/perf-agent.XXXXXX", capture_output=True, text=True ) if made.returncode: raise IsolationError("perf-agent cannot create its private directory") directory = Path(made.stdout.strip()) mode = sudo("stat", "-c", "%a", str(directory), capture_output=True, text=True) if mode.stdout.strip() != "700": raise IsolationError(f"{directory} is not 0700") for path in (directory / "home", directory / "tmp"): sudo("mkdir", str(path), check=True) return cls(directory) def run(self, argv, extra_env, timeout): """Run argv as perf-agent with the allowlisted environment plus extra_env.""" environment = { name: os.environ[name] for name in ENV_ALLOWLIST if name in os.environ } environment.update( HOME=str(self.directory / "home"), TMPDIR=str(self.directory / "tmp"), ALBEDO_TEST_TMP=str(self.directory / "tmp"), LANG="C.UTF-8", ALBEDO_NO_BROWSER="1", PYTHONDONTWRITEBYTECODE="1", **extra_env, ) assignments = [f"{name}={value}" for name, value in environment.items()] return sudo("env", "-i", *assignments, *argv, timeout=timeout) def can_execute(self, path): return sudo("test", "-x", str(path)).returncode == 0 def read(self, path: Path): """Bytes of a file perf-agent wrote, or None when it does not exist.""" result = sudo("cat", str(path), capture_output=True) return result.stdout if result.returncode == 0 else None def close(self): """End the model-controlled uid and verify cleanup before publication.""" if self.closed: return killed = sudo("pkill", "-KILL", "-u", USER, capture_output=True) if killed.returncode not in (0, 1): raise IsolationError("could not stop perf-agent processes") deadline = time.monotonic() + 5 while True: remaining = sudo("pgrep", "-u", USER, capture_output=True) if remaining.returncode == 1: break if remaining.returncode != 0 or time.monotonic() >= deadline: raise IsolationError("could not verify perf-agent process cleanup") time.sleep(0.05) sudo("rm", "-rf", str(self.directory), capture_output=True, check=True) self.closed = True