Files
lmxopcua/scripts/validation/grpc-data/processes.py
T

268 lines
11 KiB
Python

"""Bounded subprocess execution for the local validation gate.
Real subprocesses start in a fresh owned process group; POSIX cancellation and
timeouts signal only that group. Callers must not use wrappers that detach
descendants. There is no process-name scan, global kill, or Docker reaper.
"""
from dataclasses import dataclass
import codecs
import math
import os
import signal
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
cancelled: bool = False
_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, observer=None):
self.limit = limit
self.secrets = secrets
self.used = 0
self.truncated = False
self.lock = threading.Lock()
self.parts = {"stdout": [], "stderr": []}
self.failures = []
self.observer = observer
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"))
if retained and self.observer is not None:
self.observer(stream, retained)
def drain(self, name, pipe):
# Only an actual secret prefix can delay live output. Complete matches
# are consumed before carrying a suffix, bounding even self-overlap.
pending = ""
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
try:
while True:
chunk = getattr(pipe, "read1", pipe.read)(4096)
if not chunk:
pending += decoder.decode(b"", final=True)
safe, _ = _redact_stream_prefix(pending, self.secrets, final=True)
self.append(name, safe)
break
pending += decoder.decode(chunk) if isinstance(chunk, bytes) else chunk
safe, pending = _redact_stream_prefix(pending, self.secrets)
self.append(name, safe)
except Exception:
# Do not include raw exception text: pipes/factories may mention argv.
with self.lock:
self.failures.append(name)
def _redact_stream_prefix(pending, secrets, *, final=False):
"""Consume complete matches and retain only a genuine unresolved secret-prefix suffix."""
secrets = tuple(secret for secret in secrets if secret)
safe = []
while pending:
keep = 0 if final else max((length for secret in secrets
for length in range(1, min(len(secret), len(pending) + 1))
if pending.endswith(secret[:length])), default=0)
frontier = len(pending) - keep
matches = [(start, -len(secret), secret) for secret in secrets
if (start := pending.find(secret)) >= 0 and start < frontier]
if not matches:
safe.append(pending[:frontier])
return "".join(safe), pending[frontier:]
start, _, secret = min(matches)
safe.extend((pending[:start], "[REDACTED]"))
# A match crossing the frontier is consumed in full. Any overlapping
# candidate already contains redacted characters and cannot leak intact.
pending = pending[start + len(secret):]
return "".join(safe), ""
def run_process(argv, *, timeout, secrets=(), max_output_bytes=1024 * 1024,
popen=None, clock=time.monotonic, cleanup_timeout=2.0, cwd=None, environment=None, observer=None,
cancellation_event=None):
"""Execute argv once, draining both streams while bounding retained evidence.
A timed-out or cancelled command is never retried. Either state 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 observer is not None and not callable(observer):
raise ProcessError("output observer must be callable")
if cancellation_event is not None and not callable(getattr(cancellation_event, "is_set", None)):
raise ProcessError("cancellation signal must expose is_set")
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, observer)
readers = [threading.Thread(target=capture.drain, args=(name, getattr(process, name)), daemon=True)
for name in ("stdout", "stderr")]
timed_out = False
cancelled = False
failed = False
returncode = None
for reader in readers:
reader.start()
def stop_owned(force=False):
if popen is None and os.name != "nt":
try:
os.killpg(process.pid, signal.SIGKILL if force else signal.SIGTERM)
except ProcessLookupError:
pass
else:
(process.kill if force else process.terminate)()
try:
if cancellation_event is None:
try:
returncode = process.wait(timeout=timeout)
except subprocess.TimeoutExpired:
timed_out = True
else:
deadline = started + timeout
while True:
if cancellation_event.is_set():
cancelled = True
break
remaining = deadline - clock()
if remaining <= 0:
timed_out = True
break
try:
returncode = process.wait(timeout=min(.1, remaining))
break
except subprocess.TimeoutExpired:
continue
if timed_out or cancelled:
stop_owned()
try:
returncode = process.wait(timeout=cleanup_timeout)
except subprocess.TimeoutExpired:
stop_owned(force=True)
returncode = process.wait(timeout=cleanup_timeout)
if popen is None and os.name != "nt":
# The leader can exit on TERM while a silent same-group child
# survives. Escalate the exact owned group independently of EOF.
stop_owned(force=True)
except BaseException:
failed = True
try:
stop_owned(force=True)
returncode = process.wait(timeout=cleanup_timeout)
except BaseException:
pass
finally:
drain_deadline = clock() + cleanup_timeout
for reader in readers:
reader.join(timeout=max(0, drain_deadline - clock()))
# 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):
try:
stop_owned(force=True)
drain_deadline = clock() + cleanup_timeout
for reader in readers:
reader.join(timeout=max(0, drain_deadline - clock()))
except BaseException:
failed = True
failed = failed or any(reader.is_alive() for reader in readers) or not (timed_out or cancelled)
if not any(reader.is_alive() for reader in readers):
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), cancelled)