"""Bounded subprocess execution for the local validation gate. Only the immediate child is owned here. Real subprocesses start in a fresh process group; callers must not use shell wrappers that detach grandchildren. There is no process-name scan, global kill, Docker reaper, or inherited fixture configuration. """ from dataclasses import dataclass import codecs import math import os import subprocess import threading import time class ProcessError(RuntimeError): """The command could not be safely executed or collected.""" @dataclass(frozen=True) class ProcessResult: argv: tuple[str, ...] returncode: int stdout: str stderr: str timed_out: bool truncated: bool duration_seconds: float _SECRET_FLAGS = {"-P", "--password", "--api-key", "--apikey", "--token", "--secret"} def _argv_secrets(argv): found = [] hide_next = False for argument in argv: if hide_next: found.append(argument) hide_next = False elif argument in _SECRET_FLAGS: hide_next = True elif "=" in argument and argument.split("=", 1)[0] in _SECRET_FLAGS: found.append(argument.split("=", 1)[1]) return found def redact_argv(argv): """Return evidence-safe argv, independently of explicit secret registration.""" safe = [] hide_next = False for argument in argv: if hide_next: safe.append("[REDACTED]") hide_next = False elif argument in _SECRET_FLAGS: safe.append(argument) hide_next = True elif "=" in argument and argument.split("=", 1)[0] in _SECRET_FLAGS: safe.append(argument.split("=", 1)[0] + "=[REDACTED]") else: safe.append(argument) return tuple(safe) def redact_text(text, secrets=()): for secret in sorted({value for value in secrets if value}, key=len, reverse=True): text = text.replace(secret, "[REDACTED]") return text def _positive_finite(value, name): if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0: raise ProcessError(f"{name} must be positive and finite") class _Capture: def __init__(self, limit, secrets): self.limit = limit self.secrets = secrets self.used = 0 self.truncated = False self.lock = threading.Lock() self.parts = {"stdout": [], "stderr": []} self.failures = [] def append(self, stream, text): encoded = redact_text(text, self.secrets).encode("utf-8") with self.lock: remaining = self.limit - self.used if len(encoded) > remaining: self.truncated = True retained = encoded[:remaining].decode("utf-8", errors="ignore") if retained: self.parts[stream].append(retained) self.used += len(retained.encode("utf-8")) def drain(self, name, pipe): # Keep enough uncommitted text to redact a credential spanning reads. keep = max((len(secret) for secret in self.secrets), default=1) - 1 pending = "" decoder = codecs.getincrementaldecoder("utf-8")(errors="replace") try: while True: chunk = pipe.read(4096) if not chunk: pending += decoder.decode(b"", final=True) self.append(name, pending) break pending += decoder.decode(chunk) if isinstance(chunk, bytes) else chunk safe_length = max(0, len(pending) - keep) for secret in self.secrets: start = pending.find(secret, max(0, safe_length - len(secret) + 1)) if start >= 0 and start < safe_length < start + len(secret): safe_length = start self.append(name, pending[:safe_length]) pending = pending[safe_length:] except Exception: # Do not include raw exception text: pipes/factories may mention argv. with self.lock: self.failures.append(name) def run_process(argv, *, timeout, secrets=(), max_output_bytes=1024 * 1024, popen=None, clock=time.monotonic, cleanup_timeout=2.0, cwd=None, environment=None): """Execute argv once, draining both streams while bounding retained evidence. A timed-out command is never retried. Timeout is recorded even if termination returns exit zero. An injected Popen factory is intended for pure unit tests. The caller supplies an explicit environment when fixture isolation is needed. """ if not isinstance(argv, (list, tuple)) or not argv or any( not isinstance(argument, str) or "\0" in argument for argument in argv) or not argv[0]: raise ProcessError("a nonempty argv sequence is required") _positive_finite(timeout, "timeout") _positive_finite(cleanup_timeout, "cleanup timeout") if type(max_output_bytes) is not int or not 0 < max_output_bytes <= 64 * 1024 * 1024: raise ProcessError("capture limit must be between 1 and 67108864 bytes") secret_values = tuple(sorted({str(value) for value in (*secrets, *_argv_secrets(argv)) if value}, key=len, reverse=True)) safe_argv = tuple(redact_text(value, secret_values) for value in redact_argv(argv)) started = clock() factory = subprocess.Popen if popen is None else popen options = {"stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "stdin": subprocess.DEVNULL, "shell": False, "cwd": cwd} if environment is not None: options["env"] = dict(environment) if os.name == "nt": options["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP else: options["start_new_session"] = True try: process = factory(list(argv), **options) except Exception: raise ProcessError("failed to start validation child") from None capture = _Capture(max_output_bytes, secret_values) readers = [threading.Thread(target=capture.drain, args=(name, getattr(process, name)), daemon=True) for name in ("stdout", "stderr")] timed_out = False failed = False returncode = None for reader in readers: reader.start() try: try: returncode = process.wait(timeout=timeout) except subprocess.TimeoutExpired: timed_out = True process.terminate() try: returncode = process.wait(timeout=cleanup_timeout) except subprocess.TimeoutExpired: process.kill() returncode = process.wait(timeout=cleanup_timeout) except BaseException: failed = True try: process.kill() returncode = process.wait(timeout=cleanup_timeout) except BaseException: pass finally: for reader in readers: reader.join(timeout=cleanup_timeout) # A detached descendant holding a pipe is an error, never a successful # capture. Do not block indefinitely trying to close a buffered pipe while # another thread is inside read(); daemon readers allow bounded return. if any(reader.is_alive() for reader in readers): failed = True else: for name in ("stdout", "stderr"): try: getattr(process, name).close() except Exception: failed = True if failed or capture.failures or type(returncode) is not int: raise ProcessError("failed to collect validation child within cleanup deadline") from None return ProcessResult(safe_argv, returncode, "".join(capture.parts["stdout"]), "".join(capture.parts["stderr"]), timed_out, capture.truncated, max(0.0, clock() - started))