"""Exact-command execution for the disposable acceptance runtime.""" import os import signal import stat import subprocess from pathlib import Path class RuntimeError(Exception): pass class Runtime: def __init__(self, root, commands, environment): self.root = Path(root) info = self.root.stat() if (self.root.resolve() != self.root or not self.root.is_dir() or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) & 0o077): raise RuntimeError("Runtime requires a private, canonical directory") self.commands = frozenset(tuple(command) for command in commands) for command in self.commands: executable = Path(command[0]) if not executable.is_absolute() or not executable.is_file(): raise RuntimeError("An absolute executable path is required") self.environment = dict(environment) def start(self, command, *, cwd, output=None): cwd = Path(cwd) if (tuple(command) not in self.commands or cwd.resolve() != cwd or not cwd.is_relative_to(self.root)): raise RuntimeError("Command or working directory is not authorised") return subprocess.Popen( command, cwd=cwd, env=self.environment, stdin=subprocess.DEVNULL, stdout=output if output is not None else subprocess.DEVNULL, stderr=subprocess.STDOUT, start_new_session=True, ) @staticmethod def stop(process): try: os.killpg(process.pid, signal.SIGTERM) except ProcessLookupError: pass except PermissionError: if process.poll() is None: raise try: process.wait(timeout=5) except subprocess.TimeoutExpired: try: os.killpg(process.pid, signal.SIGKILL) except ProcessLookupError: pass process.wait() def run(self, command, *, cwd, timeout=60, output=None): process = self.start(command, cwd=cwd, output=output) try: if process.wait(timeout=timeout): raise RuntimeError("Authorised command failed") except BaseException: self.stop(process) raise