"""runjail - the environment every run of project code gets (revised 12.0, round-3 design P0, step R2). A project's checks, tests and programs are not Oracle7. They run without Oracle7's own state and store locations, with a private home and temporary folder, and with the head's own listening port refused even on loopback (the network scope guard in bench.GUARD reads O7_DENY_PORTS). Before this, a hostile repository's test could rewrite the hole record, the writing and reflection state, or post "go" to the head (round-3 COMBINED_DESIGN S1). What is removed is named by the names Oracle7 itself gives its settings (the ORACLE7_, ORACLE_ and O7_ families), so a setting added later is covered without editing this file. Would not solve: a program not written in Python ignores the port guard (bench.GUARD's own limit); a run with the head's operating-system user can still open files by absolute path. """ import hashlib import os from pathlib import Path OWN = ("ORACLE7_", "ORACLE_", "O7_") # Oracle7's own setting families KEEP = {"O7_NET_SCOPE", "O7_DENY_PORTS"} # set below for the run itself def run(args, timeout=None, **kw): """12.0.2: subprocess.run, bounded for what it starts: the command runs in its own process group, and past its time the whole group is killed, so a shell's children and a test's own processes do not outlive the check (a repair candidate's hung tests ran on for hours after the shell was killed). Same result and TimeoutExpired as subprocess.run.""" import signal import subprocess kw.pop("start_new_session", None) capture = kw.pop("capture_output", False) if capture: kw["stdout"] = kw.get("stdout", subprocess.PIPE) kw["stderr"] = kw.get("stderr", subprocess.PIPE) data = kw.pop("input", None) if data is not None: kw["stdin"] = subprocess.PIPE p = subprocess.Popen(args, start_new_session=True, **kw) try: out, err = p.communicate(data, timeout=timeout) except subprocess.TimeoutExpired: try: os.killpg(p.pid, signal.SIGKILL) except OSError: p.kill() p.communicate() raise return subprocess.CompletedProcess(args, p.returncode, out, err) def head_ports(): """the ports the head listens on (set by server.main at start)""" return [p for p in (os.environ.get("ORACLE7_HEAD_PORT") or "").split(",") if p.strip().isdigit()] def _private(root): """a home and temp folder for runs in this project, outside the project and outside Oracle7's state records""" import tempfile base = Path(tempfile.gettempdir()) / "oracle7-runs" # never under the state folder ($HOME/.. must not reach it) d = base / hashlib.sha256(str(root or "-").encode()).hexdigest()[:16] for sub in ("home", "tmp"): (d / sub).mkdir(parents=True, exist_ok=True) return d / "home", d / "tmp" def _guard_dir(): """the network scope guard (bench.GUARD) as a sitecustomize every Python run loads first""" from bench import GUARD import tempfile g = Path(tempfile.gettempdir()) / "oracle7-runs" / "guard" # not under the state folder: its path is on every run's g.mkdir(parents=True, exist_ok=True) f = g / "sitecustomize.py" if not f.is_file() or f.read_text() != GUARD: f.write_text(GUARD) return g def env(base=None, root=None, net_scope=(), **extra): """-> the environment for one run of project code under `root`: Oracle7's own settings removed, a private home and temp folder, the network scope guard first on the path, the head's ports refused""" deny, g = head_ports(), _guard_dir() e = {k: v for k, v in dict(os.environ if base is None else base).items() if not (k.startswith(OWN) and k not in KEEP)} home, tmp = _private(root) e["HOME"] = e["USERPROFILE"] = str(home) # Python's home is USERPROFILE on Windows, HOME elsewhere for k in ("TMPDIR", "TEMP", "TMP"): e[k] = str(tmp) if os.name == "nt": # per-user application folders on Windows e["APPDATA"] = e["LOCALAPPDATA"] = str(home) e["O7_DENY_PORTS"] = ",".join(deny) e["O7_NET_SCOPE"] = ",".join(net_scope or []) e.update({k: str(v) for k, v in extra.items()}) e["PYTHONPATH"] = str(g) + (os.pathsep + e["PYTHONPATH"] if e.get("PYTHONPATH") else "") return e