test: validate grpc data connections with local docker and opcua cli
This commit is contained in:
@@ -1,13 +1,14 @@
|
||||
"""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.
|
||||
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
|
||||
@@ -26,6 +27,7 @@ class ProcessResult:
|
||||
timed_out: bool
|
||||
truncated: bool
|
||||
duration_seconds: float
|
||||
cancelled: bool = False
|
||||
|
||||
|
||||
_SECRET_FLAGS = {"-P", "--password", "--api-key", "--apikey", "--token", "--secret"}
|
||||
@@ -75,7 +77,7 @@ def _positive_finite(value, name):
|
||||
|
||||
|
||||
class _Capture:
|
||||
def __init__(self, limit, secrets):
|
||||
def __init__(self, limit, secrets, observer=None):
|
||||
self.limit = limit
|
||||
self.secrets = secrets
|
||||
self.used = 0
|
||||
@@ -83,6 +85,7 @@ class _Capture:
|
||||
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")
|
||||
@@ -94,39 +97,60 @@ class _Capture:
|
||||
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):
|
||||
# Keep enough uncommitted text to redact a credential spanning reads.
|
||||
keep = max((len(secret) for secret in self.secrets), default=1) - 1
|
||||
# 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 = pipe.read(4096)
|
||||
chunk = getattr(pipe, "read1", pipe.read)(4096)
|
||||
if not chunk:
|
||||
pending += decoder.decode(b"", final=True)
|
||||
self.append(name, pending)
|
||||
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_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:]
|
||||
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):
|
||||
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 command is never retried. Timeout is recorded even if termination
|
||||
returns exit zero. An injected Popen factory is intended for pure unit tests.
|
||||
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(
|
||||
@@ -134,6 +158,10 @@ def run_process(argv, *, timeout, secrets=(), max_output_bytes=1024 * 1024,
|
||||
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},
|
||||
@@ -154,41 +182,79 @@ def run_process(argv, *, timeout, secrets=(), max_output_bytes=1024 * 1024,
|
||||
except Exception:
|
||||
raise ProcessError("failed to start validation child") from None
|
||||
|
||||
capture = _Capture(max_output_bytes, secret_values)
|
||||
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:
|
||||
try:
|
||||
returncode = process.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
timed_out = True
|
||||
process.terminate()
|
||||
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:
|
||||
process.kill()
|
||||
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:
|
||||
process.kill()
|
||||
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=cleanup_timeout)
|
||||
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):
|
||||
failed = True
|
||||
else:
|
||||
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()
|
||||
@@ -198,4 +264,4 @@ def run_process(argv, *, timeout, secrets=(), max_output_bytes=1024 * 1024,
|
||||
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))
|
||||
max(0.0, clock() - started), cancelled)
|
||||
|
||||
Reference in New Issue
Block a user