test: prepare isolated grpc data integration helpers
This commit is contained in:
@@ -0,0 +1,210 @@
|
||||
"""Evidence validators for the repository CLI's current human-readable output.
|
||||
|
||||
These functions validate individual healthy operations, not the complete P10
|
||||
scenario matrix. A process exit of zero alone is never success. Subscription
|
||||
summary text must come from a fresh run-owned --summary-file; stdout alone is
|
||||
insufficient. Integration orchestration and explicit denial/fault expectations
|
||||
will be connected once the production fixture graph exists.
|
||||
"""
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import ipaddress
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from processes import ProcessResult
|
||||
|
||||
|
||||
class CliGateError(RuntimeError):
|
||||
"""Missing or unsuccessful CLI evidence."""
|
||||
|
||||
|
||||
def _process_ok(result):
|
||||
if not isinstance(result, ProcessResult) or result.timed_out or result.returncode != 0 or result.truncated:
|
||||
raise CliGateError("CLI failed, timed out, or produced truncated evidence")
|
||||
if not isinstance(result.stdout, str) or not result.stdout.strip():
|
||||
raise CliGateError("CLI stdout evidence is missing")
|
||||
|
||||
|
||||
def _field(text, name):
|
||||
values = re.findall(rf"^{re.escape(name)}:[ \t]*(.*)$", text, re.M)
|
||||
if len(values) != 1:
|
||||
raise CliGateError(f"CLI evidence needs exactly one {name} field")
|
||||
return values[0].strip()
|
||||
|
||||
|
||||
def _timestamp(value):
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except (ValueError, TypeError):
|
||||
raise CliGateError("CLI timestamp is missing or invalid") from None
|
||||
if parsed.tzinfo is None:
|
||||
raise CliGateError("CLI timestamp must carry a timezone")
|
||||
return value
|
||||
|
||||
|
||||
def validate_read(result, *, expected_node):
|
||||
_process_ok(result)
|
||||
if _field(result.stdout, "Node") != expected_node:
|
||||
raise CliGateError("CLI read returned a different node")
|
||||
status = _field(result.stdout, "Status")
|
||||
if status != "Good":
|
||||
raise CliGateError("CLI read status is not Good")
|
||||
value = _field(result.stdout, "Value")
|
||||
if not value:
|
||||
raise CliGateError("CLI read value is missing")
|
||||
return {"node": expected_node, "status": status, "value": value,
|
||||
"source_time": _timestamp(_field(result.stdout, "Source Time")),
|
||||
"server_time": _timestamp(_field(result.stdout, "Server Time"))}
|
||||
|
||||
|
||||
def validate_write(result, *, expected_node):
|
||||
_process_ok(result)
|
||||
successes = re.findall(r"^Write successful: (.+?) = (.+)$", result.stdout, re.M)
|
||||
if "Write failed:" in result.stdout or len(successes) != 1 or successes[0][0] != expected_node:
|
||||
raise CliGateError("CLI write lacks an exact successful node confirmation")
|
||||
return {"node": expected_node, "accepted_value": successes[0][1].strip()}
|
||||
|
||||
|
||||
_COUNTERS = {
|
||||
"total": "Total subscribed",
|
||||
"ever_bad": " Ever went BAD during window",
|
||||
"never_bad": " NEVER went bad (suspect)",
|
||||
"good": " Last status GOOD",
|
||||
"bad": " Last status NOT-GOOD",
|
||||
"never": " No update received at all",
|
||||
}
|
||||
_SUMMARY_HEADING = "==================== SUMMARY ===================="
|
||||
|
||||
|
||||
def _summary(text):
|
||||
if not isinstance(text, str) or text.count(_SUMMARY_HEADING) != 1:
|
||||
raise CliGateError("CLI summary file/header is missing or ambiguous")
|
||||
counters = {}
|
||||
for field, label in _COUNTERS.items():
|
||||
value = _field(text, label)
|
||||
if not re.fullmatch(r"\d+", value):
|
||||
raise CliGateError("CLI summary counter is invalid")
|
||||
counters[field] = int(value)
|
||||
if counters["total"] <= 0 or counters["good"] + counters["bad"] + counters["never"] != counters["total"]:
|
||||
raise CliGateError("CLI summary item counts are inconsistent")
|
||||
if any(counters[field] > counters["total"] for field in ("ever_bad", "never_bad")):
|
||||
raise CliGateError("CLI summary quality counts are inconsistent")
|
||||
return counters
|
||||
|
||||
|
||||
def validate_subscription(result, *, summary_text, expected_nodes, require_change=True):
|
||||
"""Require all intended items attached, fresh Good updates, and both summaries.
|
||||
|
||||
The current CLI's Total subscribed counter is the number of *targets*, not
|
||||
the number of successful SubscribeAsync calls. The attachment line and every
|
||||
per-node notification therefore remain independently mandatory.
|
||||
"""
|
||||
_process_ok(result)
|
||||
if not isinstance(expected_nodes, (set, frozenset, list, tuple)) or not expected_nodes or any(
|
||||
not isinstance(node, str) or not node for node in expected_nodes):
|
||||
raise CliGateError("explicit expected subscription nodes are required")
|
||||
expected = set(expected_nodes)
|
||||
if "FAILED to subscribe" in result.stdout or "Failed to write summary file:" in result.stdout:
|
||||
raise CliGateError("CLI reported a per-item or summary-write failure")
|
||||
attached = re.findall(r"^Subscribed to (\d+)/(\d+) nodes \(interval: (\d+)ms\)\.", result.stdout, re.M)
|
||||
if len(attached) != 1 or any(int(value) != len(expected) for value in attached[0][:2]) or int(attached[0][2]) <= 0:
|
||||
raise CliGateError("CLI did not attach every intended subscription")
|
||||
file_counts = _summary(summary_text)
|
||||
stdout_counts = _summary(result.stdout)
|
||||
if file_counts != stdout_counts:
|
||||
raise CliGateError("CLI file/stdout summaries disagree")
|
||||
if file_counts["total"] != len(expected) or file_counts["good"] != len(expected) or any(
|
||||
file_counts[field] for field in ("bad", "never", "ever_bad")):
|
||||
raise CliGateError("CLI summary contains missing or non-Good updates")
|
||||
notifications = {node: [] for node in expected}
|
||||
for line in result.stdout.splitlines():
|
||||
match = re.fullmatch(r"\[([^\]]+)\] (.+?) = (.*) \(([^()]*)\)", line)
|
||||
if match is None:
|
||||
continue
|
||||
timestamp, node, value, status = match.groups()
|
||||
if node not in expected:
|
||||
raise CliGateError("CLI notification refers to an unexpected node")
|
||||
_timestamp(timestamp)
|
||||
if status != "Good":
|
||||
raise CliGateError("CLI notification status is not Good")
|
||||
notifications[node].append(value)
|
||||
for values in notifications.values():
|
||||
if not values:
|
||||
raise CliGateError("CLI subscription has no per-node notifications")
|
||||
if require_change and len(set(values)) < 2:
|
||||
raise CliGateError("CLI subscription has no changing per-node values")
|
||||
return {"notifications": {node: len(values) for node, values in notifications.items()},
|
||||
"summary": file_counts}
|
||||
|
||||
|
||||
def _local_endpoint(url):
|
||||
try:
|
||||
parsed = urlsplit(url)
|
||||
host = parsed.hostname
|
||||
local = host == "localhost" or ipaddress.ip_address(host).is_loopback
|
||||
return (parsed.scheme == "opc.tcp" and local and parsed.port is not None and
|
||||
1 <= parsed.port <= 65535 and not parsed.username and not parsed.password and
|
||||
not parsed.query and not parsed.fragment)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def build_cli_argv(dll, command, endpoint, credential, *, node=None, value=None,
|
||||
summary_file=None, duration=30, interval=200, recursive=False, depth=6,
|
||||
partner_endpoint=None):
|
||||
"""Build portable argv from a published DLL and current supported CLI flags.
|
||||
|
||||
Returned argv contains the key solely to pass it to the CLI, which currently
|
||||
exposes no credential-file flag. Feed it directly to processes.run_process;
|
||||
persist only that wrapper's redacted ProcessResult argv.
|
||||
"""
|
||||
dll = Path(dll)
|
||||
if not dll.is_absolute() or dll.suffix.lower() != ".dll":
|
||||
raise CliGateError("a published CLI DLL absolute path is required")
|
||||
if command not in {"connect", "browse", "read", "write", "subscribe", "redundancy"}:
|
||||
raise CliGateError("unsupported CLI command")
|
||||
if not _local_endpoint(endpoint) or (partner_endpoint is not None and not _local_endpoint(partner_endpoint)):
|
||||
raise CliGateError("CLI endpoints must use allocated loopback OPC UA ports")
|
||||
if not isinstance(credential, str) or not credential:
|
||||
raise CliGateError("a presented CLI credential is required")
|
||||
argv = ["dotnet", str(dll), command, "-u", endpoint, "-U", "apikey", "-P", credential]
|
||||
if partner_endpoint is not None:
|
||||
argv.extend(["-F", partner_endpoint])
|
||||
if command in {"browse", "read", "write", "subscribe"}:
|
||||
if not isinstance(node, str) or not node:
|
||||
raise CliGateError("an explicit resolved NodeId is required")
|
||||
argv.extend(["-n", node])
|
||||
if command == "write":
|
||||
if value is None:
|
||||
raise CliGateError("an explicit write value is required")
|
||||
argv.extend(["-v", str(value)])
|
||||
if command == "browse" and recursive:
|
||||
if type(depth) is not int or depth <= 0:
|
||||
raise CliGateError("browse depth must be positive")
|
||||
argv.extend(["-r", "-d", str(depth)])
|
||||
if command == "subscribe":
|
||||
if summary_file is None or not Path(summary_file).is_absolute() or type(duration) is not int or duration <= 0 or type(interval) is not int or interval <= 0:
|
||||
raise CliGateError("subscriptions require a run-owned absolute summary path and positive duration/interval")
|
||||
argv.extend(["-i", str(interval), "--duration", str(duration), "--summary-file", str(summary_file)])
|
||||
if recursive:
|
||||
if type(depth) is not int or depth <= 0:
|
||||
raise CliGateError("subscription depth must be positive")
|
||||
argv.extend(["-r", "--max-depth", str(depth)])
|
||||
return argv
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--run-id", required=True)
|
||||
parser.add_argument("--scenario", required=True)
|
||||
parser.parse_args(argv)
|
||||
print("grpc-data CLI gate: scenario prerequisites not configured; production rig, published CLI, "
|
||||
"restricted manifest, and concrete scenario assertions are required", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,201 @@
|
||||
"""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))
|
||||
@@ -0,0 +1,429 @@
|
||||
"""Pure safety and polling boundaries for the future standalone local rig.
|
||||
|
||||
This module does not implement bring-up, migration, authoring, secret provisioning,
|
||||
or scenario execution. Those actions need the real P04–P09 composition. In
|
||||
particular, a validated safety manifest is not evidence that a rig is ready.
|
||||
HTTP and resource deletion are explicit callbacks so unit tests never use Docker
|
||||
or a network. The coordinator owns connecting these boundaries to real tools.
|
||||
"""
|
||||
import argparse
|
||||
import ipaddress
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import tempfile
|
||||
import time
|
||||
from urllib.parse import urljoin, urlsplit
|
||||
import uuid
|
||||
|
||||
|
||||
class RigError(RuntimeError):
|
||||
"""The local gate cannot safely proceed."""
|
||||
|
||||
|
||||
RUN_LABEL = "otopcua.grpc-data.run"
|
||||
PROJECT_LABEL = "com.docker.compose.project"
|
||||
_RUN_PATTERN = re.compile(r"[a-z0-9][a-z0-9-]{0,47}\Z")
|
||||
_SERVICE_PATTERN = re.compile(r"[a-z][a-z0-9-]{0,62}\Z")
|
||||
_URL_PATTERN = re.compile(r"[a-zA-Z][a-zA-Z0-9+.-]*://[^\s;\"'<>]+")
|
||||
_DB_HOST_PATTERN = re.compile(r"(?:^|[;(\s])(?:Server|Host|Data\s+Source|Address|Addr|Network\s+Address)\s*=\s*([^;)\s]+)", re.I)
|
||||
|
||||
|
||||
def validate_local_docker(endpoint):
|
||||
"""Allow only a local Unix socket or the local Windows Docker named pipe."""
|
||||
if not isinstance(endpoint, str) or not endpoint or any(character in endpoint for character in "\r\n\0"):
|
||||
raise RigError("Docker requires an explicit local socket endpoint")
|
||||
try:
|
||||
parsed = urlsplit(endpoint)
|
||||
except ValueError:
|
||||
raise RigError("invalid Docker socket endpoint") from None
|
||||
if parsed.query or parsed.fragment:
|
||||
raise RigError("Docker socket endpoint cannot have a query or fragment")
|
||||
if parsed.scheme == "unix" and not parsed.netloc and parsed.path.startswith("/") and parsed.path != "/":
|
||||
if ".." not in Path(parsed.path).parts:
|
||||
return
|
||||
if endpoint.lower().startswith("npipe:////./pipe/") and parsed.path[len("//./pipe/"):] and ".." not in parsed.path.split("/"):
|
||||
return
|
||||
raise RigError("Docker daemon must use a local unix socket or npipe; remote/TCP contexts are forbidden")
|
||||
|
||||
|
||||
def validate_docker_context(context, *, environment):
|
||||
"""Validate the actual `docker context inspect` row and overriding variables.
|
||||
|
||||
A context name is not locality evidence. The caller must obtain this row
|
||||
read-only for the selected context before any Docker mutation.
|
||||
"""
|
||||
if not isinstance(context, dict) or not isinstance(environment, dict):
|
||||
raise RigError("Docker context inspection and environment are required")
|
||||
name = context.get("Name")
|
||||
try:
|
||||
endpoint = context["Endpoints"]["docker"]["Host"]
|
||||
except (KeyError, TypeError):
|
||||
raise RigError("Docker context has no inspected daemon endpoint") from None
|
||||
if not isinstance(name, str) or not name:
|
||||
raise RigError("Docker context has no name")
|
||||
validate_local_docker(endpoint)
|
||||
if environment.get("DOCKER_HOST"):
|
||||
validate_local_docker(environment["DOCKER_HOST"])
|
||||
if environment["DOCKER_HOST"] != endpoint:
|
||||
raise RigError("Docker host override differs from the inspected context")
|
||||
if environment.get("DOCKER_CONTEXT") and environment["DOCKER_CONTEXT"] != name:
|
||||
raise RigError("Docker context override differs from the inspected context")
|
||||
|
||||
|
||||
def _loopback(host):
|
||||
if host == "localhost":
|
||||
return True
|
||||
try:
|
||||
address = ipaddress.ip_address(host)
|
||||
return address.is_loopback or bool(getattr(address, "ipv4_mapped", None) and address.ipv4_mapped.is_loopback)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def _host_allowed(host, services):
|
||||
return isinstance(host, str) and (_loopback(host) or host in services)
|
||||
|
||||
|
||||
def _plain_host(value):
|
||||
value = value.strip().strip("\"'")
|
||||
if value.lower().startswith("tcp:"):
|
||||
value = value[4:]
|
||||
if value.startswith("["):
|
||||
end = value.find("]")
|
||||
return value[1:end] if end >= 0 else value
|
||||
if value.count(":") > 1:
|
||||
return value
|
||||
return re.split(r"[,:/\\]", value, maxsplit=1)[0]
|
||||
|
||||
|
||||
def validate_fixture_endpoints(document, *, local_services):
|
||||
"""Reject endpoint escape in resolved Compose/config/seed data, without DNS.
|
||||
|
||||
Pass resolved data, never a YAML file with uninterpreted environment expansion.
|
||||
Image registries are build inputs; endpoint URLs, SQL connection hosts, and
|
||||
host/server/address configuration values must name an explicit local service
|
||||
or loopback. No arbitrary private subnet is treated as local.
|
||||
"""
|
||||
services = set(local_services)
|
||||
if not services or any(not isinstance(name, str) or not _SERVICE_PATTERN.fullmatch(name) for name in services):
|
||||
raise RigError("an explicit local service allowlist is required")
|
||||
|
||||
def check_host(host):
|
||||
if not _host_allowed(host, services):
|
||||
# Do not echo source values: a malformed URL/connection can contain a key.
|
||||
raise RigError("fixture endpoint is outside loopback and run-owned service DNS")
|
||||
|
||||
def walk(value, key=""):
|
||||
if isinstance(value, dict):
|
||||
for child_key, child in value.items():
|
||||
walk(child, str(child_key))
|
||||
elif isinstance(value, (list, tuple)):
|
||||
for child in value:
|
||||
walk(child, key)
|
||||
elif isinstance(value, str):
|
||||
if "${" in value:
|
||||
raise RigError("fixture configuration must be fully resolved")
|
||||
urls = _URL_PATTERN.findall(value)
|
||||
for url in urls:
|
||||
try:
|
||||
parsed = urlsplit(url)
|
||||
host = parsed.hostname
|
||||
except ValueError:
|
||||
raise RigError("fixture endpoint URL is invalid") from None
|
||||
check_host(host)
|
||||
if parsed.username is not None or parsed.password is not None:
|
||||
raise RigError("fixture endpoint URLs cannot contain credentials")
|
||||
db_hosts = _DB_HOST_PATTERN.findall(value)
|
||||
for host in db_hosts:
|
||||
check_host(_plain_host(host))
|
||||
suffix = re.split(r"__|:", key)[-1].lower()
|
||||
if not urls and not db_hosts and suffix in {"host", "hostname", "publichostname", "server", "address", "endpoint"}:
|
||||
check_host(_plain_host(value))
|
||||
# An IP endpoint hidden in an unfamiliar option must not pass merely
|
||||
# because its key does not match an expected Host/Server suffix.
|
||||
for match in re.findall(r"(?<![\w.])(?:\d{1,3}\.){3}\d{1,3}(?![\w.])", value):
|
||||
check_host(match)
|
||||
walk(document)
|
||||
|
||||
|
||||
def _port(value):
|
||||
return type(value) is int and 1 <= value <= 65535
|
||||
|
||||
|
||||
def _required_text(value):
|
||||
return isinstance(value, str) and bool(value.strip())
|
||||
|
||||
|
||||
def validate_manifest(manifest, *, expected_run_id=None):
|
||||
"""Validate the version-1 safety subset; this does not declare readiness."""
|
||||
if not isinstance(manifest, dict) or type(manifest.get("schema_version")) is not int or manifest["schema_version"] != 1:
|
||||
raise RigError("unsupported rig manifest schema version")
|
||||
run_id = manifest.get("run_id")
|
||||
if not isinstance(run_id, str) or not _RUN_PATTERN.fullmatch(run_id):
|
||||
raise RigError("unsafe rig run id")
|
||||
if expected_run_id is not None and run_id != expected_run_id:
|
||||
raise RigError("manifest run id does not match requested run")
|
||||
project = f"grpc-data-{run_id}"
|
||||
if manifest.get("project") != project:
|
||||
raise RigError("manifest project is not run-owned")
|
||||
labels = manifest.get("labels")
|
||||
if not isinstance(labels, dict) or labels.get(RUN_LABEL) != run_id or labels.get(PROJECT_LABEL) != project:
|
||||
raise RigError("manifest requires exact run and Compose project labels")
|
||||
services = manifest.get("services")
|
||||
if not isinstance(services, list) or not services or len(set(services)) != len(services) or any(
|
||||
not isinstance(name, str) or not _SERVICE_PATTERN.fullmatch(name) for name in services):
|
||||
raise RigError("manifest requires unique run-local services")
|
||||
endpoints = manifest.get("endpoints")
|
||||
if not isinstance(endpoints, dict) or not endpoints:
|
||||
raise RigError("manifest has no allocated endpoints")
|
||||
used_ports = set()
|
||||
for endpoint in endpoints.values():
|
||||
if not isinstance(endpoint, dict) or endpoint.get("scheme") not in {"http", "https", "opc.tcp", "tcp"}:
|
||||
raise RigError("manifest endpoint scheme is invalid")
|
||||
if not _loopback(endpoint.get("host")) or endpoint.get("container_host") not in services:
|
||||
raise RigError("manifest endpoints require loopback and local service DNS")
|
||||
host_port = endpoint.get("host_port")
|
||||
if not _port(host_port) or not _port(endpoint.get("container_port")) or host_port in used_ports:
|
||||
raise RigError("manifest ports must be valid, distinct allocated host ports")
|
||||
used_ports.add(host_port)
|
||||
nodes = manifest.get("nodes")
|
||||
if not isinstance(nodes, dict) or not nodes:
|
||||
raise RigError("manifest has no expected node identities")
|
||||
applications = set()
|
||||
for node, identity in nodes.items():
|
||||
if node not in services or not isinstance(identity, dict) or not _required_text(identity.get("cluster_id")):
|
||||
raise RigError("manifest node cluster identity is missing")
|
||||
application = identity.get("application_uri")
|
||||
if not _required_text(application) or not urlsplit(application).scheme or application in applications:
|
||||
raise RigError("manifest application URI must be explicit and unique")
|
||||
applications.add(application)
|
||||
resources = manifest.get("resources")
|
||||
if not isinstance(resources, list):
|
||||
raise RigError("manifest resource inventory is missing")
|
||||
identities = set()
|
||||
for resource in resources:
|
||||
if not isinstance(resource, dict) or resource.get("kind") not in {"container", "network", "volume", "image"} or not _required_text(resource.get("id")):
|
||||
raise RigError("invalid recorded resource identity")
|
||||
resource_labels = resource.get("labels")
|
||||
if not isinstance(resource_labels, dict) or any(resource_labels.get(key) != labels[key] for key in (RUN_LABEL, PROJECT_LABEL)):
|
||||
raise RigError("recorded resource lacks exact run/project ownership")
|
||||
identity = (resource["kind"], resource["id"])
|
||||
if identity in identities:
|
||||
raise RigError("duplicate manifest resource identity")
|
||||
identities.add(identity)
|
||||
|
||||
|
||||
def cleanup_owned(manifest, observed_resources, *, remove):
|
||||
"""Delete recorded resources only after validating the whole observed inventory.
|
||||
|
||||
The callback must delete by exact type/id. Never use compose down, prune,
|
||||
project-name prefixes, or process/container name matching as a substitute.
|
||||
Missing recorded resources are harmless during interrupted-setup cleanup.
|
||||
"""
|
||||
validate_manifest(manifest)
|
||||
observed = {}
|
||||
for resource in observed_resources:
|
||||
if not isinstance(resource, dict) or not _required_text(resource.get("kind")) or not _required_text(resource.get("id")):
|
||||
raise RigError("invalid resource observation")
|
||||
identity = (resource["kind"], resource["id"])
|
||||
if identity in observed:
|
||||
raise RigError("ambiguous duplicate resource observation")
|
||||
observed[identity] = resource
|
||||
selected = []
|
||||
for recorded in manifest["resources"]:
|
||||
identity = (recorded["kind"], recorded["id"])
|
||||
resource = observed.get(identity)
|
||||
if resource is None:
|
||||
continue
|
||||
labels = resource.get("labels")
|
||||
if not isinstance(labels, dict) or any(labels.get(key) != manifest["labels"][key] for key in (RUN_LABEL, PROJECT_LABEL)):
|
||||
raise RigError("recorded resource ownership does not match current observation")
|
||||
selected.append(identity)
|
||||
for kind, resource_id in selected:
|
||||
remove(kind, resource_id)
|
||||
|
||||
|
||||
def atomic_write_secret(path, secret, *, replace=os.replace):
|
||||
"""Publish a same-directory 0600 file without exposing a permissive partial file."""
|
||||
path = Path(path)
|
||||
if not isinstance(secret, str) or not secret:
|
||||
raise RigError("secret must be nonempty text")
|
||||
if path.is_symlink() or not path.parent.is_dir() or path.parent.is_symlink():
|
||||
raise RigError("secret destination must be a regular file in an existing local directory")
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
|
||||
try:
|
||||
os.fchmod(descriptor, 0o600)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
||||
descriptor = None
|
||||
stream.write(secret)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
replace(temporary, path)
|
||||
finally:
|
||||
if descriptor is not None:
|
||||
os.close(descriptor)
|
||||
try:
|
||||
os.unlink(temporary)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def _duration(value, name):
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
|
||||
raise RigError(f"{name} must be positive and finite")
|
||||
|
||||
|
||||
def _deployment_id(value):
|
||||
if not isinstance(value, str):
|
||||
raise RigError("deployment identity is missing")
|
||||
try:
|
||||
canonical = str(uuid.UUID(value))
|
||||
except (ValueError, AttributeError):
|
||||
raise RigError("deployment identity is invalid") from None
|
||||
if canonical != value:
|
||||
raise RigError("deployment identity must be canonical")
|
||||
return canonical
|
||||
|
||||
|
||||
def _status_complete(body, deployment_id, revision, expected_nodes):
|
||||
if not isinstance(body, dict) or body.get("deploymentId") != deployment_id or body.get("revisionHash") != revision:
|
||||
raise RigError("deployment poll identity or revision mismatch")
|
||||
state = body.get("status")
|
||||
if state not in {"Dispatching", "AwaitingApplyAcks", "Sealed"} or body.get("failureReason"):
|
||||
raise RigError("deployment failed, degraded, or returned an unexpected state")
|
||||
nodes = body.get("nodes")
|
||||
if not isinstance(nodes, list):
|
||||
raise RigError("deployment poll has no node outcomes")
|
||||
seen = set()
|
||||
for node in nodes:
|
||||
if not isinstance(node, dict) or node.get("nodeId") not in expected_nodes or node["nodeId"] in seen:
|
||||
raise RigError("deployment poll has duplicate or unexpected nodes")
|
||||
seen.add(node["nodeId"])
|
||||
if node.get("status") not in {"Applying", "Applied"} or node.get("failureReason"):
|
||||
raise RigError("node apply failed, degraded, or returned an unexpected state")
|
||||
if node["status"] == "Applied" and not _required_text(node.get("appliedAtUtc")):
|
||||
raise RigError("node Applied outcome lacks an apply timestamp")
|
||||
if state != "Sealed":
|
||||
return False
|
||||
if seen != expected_nodes or any(node["status"] != "Applied" for node in nodes):
|
||||
raise RigError("sealed deployment lacks successful outcomes for all intended nodes")
|
||||
return True
|
||||
|
||||
|
||||
def deploy_and_wait(base_url, api_key, expected_nodes, *, request, timeout=120, poll_interval=1,
|
||||
clock=time.monotonic, sleep=time.sleep, created_by="grpc-data-local-gate"):
|
||||
"""Trigger one deployment and verify its revision and every node's apply row.
|
||||
|
||||
request(method, url, headers=..., json_body=..., timeout=...) returns a
|
||||
(HTTP status, headers, decoded JSON body) tuple. It must disable redirects,
|
||||
enforce the passed request deadline and bound response decoding. No raw
|
||||
transport exception or credential-bearing body is included in gate errors.
|
||||
There is no POST retry, including after a transport failure or HTTP 409.
|
||||
Runtime-observed revision/catalog readiness remains an additional gate.
|
||||
"""
|
||||
_duration(timeout, "deploy timeout")
|
||||
_duration(poll_interval, "poll interval")
|
||||
if not callable(request) or not _required_text(api_key):
|
||||
raise RigError("deployment request callback and API key are required")
|
||||
if not isinstance(expected_nodes, (set, frozenset, list, tuple)) or not expected_nodes or any(
|
||||
not _required_text(node) for node in expected_nodes):
|
||||
raise RigError("explicit expected deployment node identities are required")
|
||||
expected_nodes = set(expected_nodes)
|
||||
try:
|
||||
base = urlsplit(base_url)
|
||||
valid = base.scheme in {"http", "https"} and _loopback(base.hostname) and _port(base.port)
|
||||
except (ValueError, TypeError):
|
||||
valid = False
|
||||
if not valid or base.username or base.password or base.path not in {"", "/"} or base.query or base.fragment:
|
||||
raise RigError("deployment API must use an explicit loopback origin and allocated port")
|
||||
if created_by is not None and not _required_text(created_by):
|
||||
raise RigError("createdBy must be nonempty text or None for a bodyless POST")
|
||||
origin = base_url.rstrip("/")
|
||||
deadline = clock() + timeout
|
||||
headers = {"X-Api-Key": api_key}
|
||||
|
||||
def call(method, url, body=None):
|
||||
remaining = deadline - clock()
|
||||
if remaining <= 0:
|
||||
raise RigError("deployment polling deadline timeout")
|
||||
try:
|
||||
response = request(method, url, headers=dict(headers), json_body=body, timeout=remaining)
|
||||
except Exception:
|
||||
raise RigError("deployment request failed; trigger was not retried") from None
|
||||
if not isinstance(response, (tuple, list)) or len(response) != 3:
|
||||
raise RigError("deployment transport returned an invalid response")
|
||||
if clock() >= deadline:
|
||||
raise RigError("deployment request exceeded polling deadline timeout")
|
||||
return response
|
||||
|
||||
status, response_headers, body = call("POST", origin + "/api/deployments",
|
||||
None if created_by is None else {"createdBy": created_by})
|
||||
if status == 409:
|
||||
raise RigError("another deployment is in flight; no new trigger was sent")
|
||||
if not isinstance(body, dict) or (status, body.get("outcome")) not in {(202, "Accepted"), (200, "NoChanges")}:
|
||||
raise RigError("deployment trigger was rejected or returned an unexpected outcome")
|
||||
deployment_id = _deployment_id(body.get("deploymentId"))
|
||||
revision = body.get("revisionHash")
|
||||
if not _required_text(revision):
|
||||
raise RigError("deployment trigger has no expected revision")
|
||||
expected_location = f"/api/deployments/{deployment_id}"
|
||||
if not isinstance(response_headers, dict):
|
||||
raise RigError("deployment response headers are invalid")
|
||||
location = next((value for key, value in response_headers.items() if key.lower() == "location"), None)
|
||||
if status == 202 and not location:
|
||||
raise RigError("accepted deployment has no Location")
|
||||
poll_url = origin + expected_location
|
||||
if location is not None:
|
||||
if not isinstance(location, str) or urljoin(origin + "/", location) != poll_url:
|
||||
raise RigError("deployment Location does not match the same local origin and deployment")
|
||||
while True:
|
||||
status, _, body = call("GET", poll_url)
|
||||
if status != 200:
|
||||
raise RigError("deployment status resource did not return HTTP 200")
|
||||
if _status_complete(body, deployment_id, revision, expected_nodes):
|
||||
return body
|
||||
remaining = deadline - clock()
|
||||
if remaining <= 0:
|
||||
raise RigError("deployment polling deadline timeout")
|
||||
sleep(min(poll_interval, remaining))
|
||||
|
||||
|
||||
_PREREQUISITES = {
|
||||
"preflight": ("docker_context_inspector", "resolved_composition"),
|
||||
"up": ("resolved_composition", "current_source_image_builder", "local_sql_migrator",
|
||||
"pair_starter", "health_role_catalog_observer", "tls_and_scoped_secret_provisioner"),
|
||||
"seed": ("production_validating_seeder", "namespace_identity_resolver", "credential_file_writer"),
|
||||
"deploy": ("deployment_transport", "intended_node_identities", "runtime_revision_observer"),
|
||||
"down": ("restricted_manifest", "resource_label_inspector", "exact_resource_remover"),
|
||||
}
|
||||
|
||||
|
||||
def require_production_prerequisites(action, available):
|
||||
"""Report incomplete wiring rather than fabricating successful rig actions."""
|
||||
if action not in _PREREQUISITES:
|
||||
raise RigError("unknown rig action")
|
||||
missing = [name for name in _PREREQUISITES[action] if not available.get(name)]
|
||||
if missing:
|
||||
raise RigError(f"{action} prerequisites not configured: {', '.join(missing)}")
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=tuple(_PREREQUISITES))
|
||||
parser.add_argument("--run-id")
|
||||
arguments = parser.parse_args(argv)
|
||||
try:
|
||||
if arguments.action != "preflight" and (not arguments.run_id or not _RUN_PATTERN.fullmatch(arguments.run_id)):
|
||||
raise RigError("a safe explicit --run-id is required")
|
||||
require_production_prerequisites(arguments.action, {})
|
||||
except RigError as error:
|
||||
print(f"grpc-data rig: {error}", file=__import__("sys").stderr)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Current CLI text and fake-process units; no subprocess or network is started."""
|
||||
import io
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import cli_gate
|
||||
import processes
|
||||
|
||||
|
||||
NODE = "ns=7;s=unit/device/counter"
|
||||
KEY = "unit-presented-secret"
|
||||
|
||||
|
||||
def result(stdout="", stderr="", returncode=0, timed_out=False, truncated=False):
|
||||
return processes.ProcessResult(argv=("dotnet", "unit.dll"), returncode=returncode,
|
||||
stdout=stdout, stderr=stderr, timed_out=timed_out,
|
||||
truncated=truncated, duration_seconds=0.1)
|
||||
|
||||
|
||||
def summary(total=1, good=1, bad=0, never=0):
|
||||
return ("\n==================== SUMMARY ====================\n"
|
||||
f"Total subscribed: {total}\n"
|
||||
" Ever went BAD during window: 0\n"
|
||||
" NEVER went bad (suspect): 1\n"
|
||||
f" Last status GOOD: {good}\n"
|
||||
f" Last status NOT-GOOD: {bad}\n"
|
||||
f" No update received at all: {never}\n")
|
||||
|
||||
|
||||
def subscription_output(values=(1, 2), attached=1):
|
||||
return (f"Subscribed to {attached}/1 nodes (interval: 200ms). Press Ctrl+C to stop and print summary.\n" +
|
||||
"".join(f"[2026-11-16T00:00:0{index}.0000000Z] {NODE} = {value} (Good)\n"
|
||||
for index, value in enumerate(values)) + summary())
|
||||
|
||||
|
||||
class ProcessSafetyTests(unittest.TestCase):
|
||||
def fake_process(self, stdout=b"output", stderr=b"error", waits=None):
|
||||
process = Mock()
|
||||
process.stdout = io.BytesIO(stdout)
|
||||
process.stderr = io.BytesIO(stderr)
|
||||
process.returncode = 0
|
||||
process.wait.side_effect = waits or [0]
|
||||
return process
|
||||
|
||||
def run_process(self, process, **kwargs):
|
||||
factory = Mock(return_value=process)
|
||||
output = processes.run_process(["dotnet", "unit.dll", "-P", KEY], timeout=1,
|
||||
secrets=[KEY], popen=factory, **kwargs)
|
||||
return output, factory
|
||||
|
||||
def test_argv_is_passed_without_shell_and_capture_is_separate(self):
|
||||
output, factory = self.run_process(self.fake_process())
|
||||
args, options = factory.call_args
|
||||
self.assertEqual(args[0], ["dotnet", "unit.dll", "-P", KEY])
|
||||
self.assertFalse(options.get("shell", False))
|
||||
self.assertEqual(options["stdout"], subprocess.PIPE)
|
||||
self.assertEqual(options["stderr"], subprocess.PIPE)
|
||||
self.assertEqual(output.stdout, "output")
|
||||
self.assertEqual(output.stderr, "error")
|
||||
self.assertNotIn(KEY, repr(output))
|
||||
|
||||
def test_shell_strings_empty_argv_and_unbounded_timeouts_rejected_before_spawn(self):
|
||||
for argv, timeout in (("dotnet unit.dll", 1), ([], 1), (["dotnet"], 0),
|
||||
(["dotnet"], float("inf")), (["dotnet"], float("nan"))):
|
||||
factory = Mock()
|
||||
with self.subTest(argv=argv, timeout=timeout), self.assertRaises(processes.ProcessError):
|
||||
processes.run_process(argv, timeout=timeout, popen=factory)
|
||||
factory.assert_not_called()
|
||||
|
||||
def test_timeout_terminates_then_kills_stubborn_process_with_bounded_waits(self):
|
||||
process = self.fake_process(waits=[subprocess.TimeoutExpired("unit", 1),
|
||||
subprocess.TimeoutExpired("unit", 1), -9])
|
||||
output, _ = self.run_process(process)
|
||||
self.assertTrue(output.timed_out)
|
||||
self.assertEqual(output.returncode, -9)
|
||||
process.terminate.assert_called_once()
|
||||
process.kill.assert_called_once()
|
||||
self.assertTrue(all(call.kwargs.get("timeout", 0) > 0 for call in process.wait.call_args_list))
|
||||
|
||||
def test_nonzero_exit_is_retained(self):
|
||||
output, _ = self.run_process(self.fake_process(waits=[7]))
|
||||
self.assertEqual(output.returncode, 7)
|
||||
self.assertFalse(output.timed_out)
|
||||
|
||||
def test_retained_output_is_bounded_and_both_streams_are_redacted(self):
|
||||
process = self.fake_process(stdout=(KEY + "x" * 4096).encode(), stderr=(KEY + "y" * 4096).encode())
|
||||
output, _ = self.run_process(process, max_output_bytes=128)
|
||||
self.assertTrue(output.truncated)
|
||||
self.assertLessEqual(len(output.stdout.encode()) + len(output.stderr.encode()), 128)
|
||||
self.assertNotIn(KEY, repr(output))
|
||||
|
||||
def test_chunk_boundary_secret_is_redacted_and_password_options_are_always_hidden(self):
|
||||
safe = processes.redact_argv(["dotnet", "unit.dll", "-P", KEY, "--password=another-secret",
|
||||
"--api-key", "third-secret"])
|
||||
self.assertNotIn(KEY, repr(safe))
|
||||
self.assertNotIn("another-secret", repr(safe))
|
||||
self.assertNotIn("third-secret", repr(safe))
|
||||
output, _ = self.run_process(self.fake_process(stdout=("x" * 4090 + KEY).encode()), max_output_bytes=8192)
|
||||
self.assertNotIn(KEY, output.stdout)
|
||||
self.assertIn("[REDACTED]", output.stdout)
|
||||
|
||||
def test_failure_while_waiting_still_cleans_up_owned_child(self):
|
||||
process = self.fake_process(waits=[RuntimeError("wait failed"), -9])
|
||||
with self.assertRaises(processes.ProcessError) as raised:
|
||||
self.run_process(process)
|
||||
self.assertTrue(process.terminate.called or process.kill.called)
|
||||
self.assertNotIn(KEY, str(raised.exception))
|
||||
|
||||
|
||||
class CliContentGateTests(unittest.TestCase):
|
||||
def test_good_read_requires_matching_node_value_status_and_timestamps(self):
|
||||
text = (f"Node: {NODE}\nValue: 42\nStatus: Good\n"
|
||||
"Source Time: 2026-11-16T00:00:00.0000000Z\nServer Time: 2026-11-16T00:00:00.0000000Z\n")
|
||||
evidence = cli_gate.validate_read(result(text), expected_node=NODE)
|
||||
self.assertEqual(evidence["value"], "42")
|
||||
self.assertEqual(evidence["status"], "Good")
|
||||
|
||||
def test_exit_zero_bad_uncertain_or_missing_read_fields_fail(self):
|
||||
for text in (f"Node: {NODE}\nValue: \nStatus: BadUserAccessDenied (BadUserAccessDenied)\n",
|
||||
f"Node: {NODE}\nValue: 42\nStatus: UncertainLastUsableValue\n",
|
||||
"", "Status: Good\n", f"Node: other\nValue: 42\nStatus: Good\n"):
|
||||
with self.subTest(text=text), self.assertRaises(cli_gate.CliGateError):
|
||||
cli_gate.validate_read(result(text), expected_node=NODE)
|
||||
|
||||
def test_write_success_requires_current_cli_confirmation_for_exact_node(self):
|
||||
cli_gate.validate_write(result(f"Write successful: {NODE} = 42\n"), expected_node=NODE)
|
||||
for text in ("Write failed: BadNotWritable\n", "", "Write successful: other = 42\n"):
|
||||
with self.subTest(text=text), self.assertRaises(cli_gate.CliGateError):
|
||||
cli_gate.validate_write(result(text), expected_node=NODE)
|
||||
|
||||
def test_timeout_nonzero_exit_and_truncated_evidence_cannot_pass(self):
|
||||
for output in (result(f"Write successful: {NODE} = 42", returncode=1),
|
||||
result(f"Write successful: {NODE} = 42", timed_out=True),
|
||||
result(f"Write successful: {NODE} = 42", truncated=True)):
|
||||
with self.subTest(output=output), self.assertRaises(cli_gate.CliGateError):
|
||||
cli_gate.validate_write(output, expected_node=NODE)
|
||||
|
||||
def validate_subscription(self, output=None, summary_text=None, **kwargs):
|
||||
return cli_gate.validate_subscription(result(subscription_output() if output is None else output),
|
||||
summary_text=summary() if summary_text is None else summary_text,
|
||||
expected_nodes={NODE}, require_change=True, **kwargs)
|
||||
|
||||
def test_subscription_requires_attachment_summary_and_changing_good_notifications(self):
|
||||
evidence = self.validate_subscription()
|
||||
self.assertGreaterEqual(evidence["notifications"][NODE], 2)
|
||||
|
||||
def test_summary_target_count_does_not_prove_any_item_actually_attached(self):
|
||||
with self.assertRaises(cli_gate.CliGateError):
|
||||
self.validate_subscription(output=subscription_output(attached=0))
|
||||
|
||||
def test_attached_subscription_without_notifications_fails(self):
|
||||
with self.assertRaises(cli_gate.CliGateError):
|
||||
self.validate_subscription(output=subscription_output(values=()))
|
||||
|
||||
def test_unchanged_notifications_and_wrong_node_fail(self):
|
||||
for output in (subscription_output(values=(1, 1)), subscription_output().replace(NODE, "ns=7;s=wrong")):
|
||||
with self.subTest(output=output), self.assertRaises(cli_gate.CliGateError):
|
||||
self.validate_subscription(output=output)
|
||||
|
||||
def test_missing_file_summary_and_stdout_summary_each_fail(self):
|
||||
for summary_text, output in (("", subscription_output()), (summary(), subscription_output().split("====")[0])):
|
||||
with self.subTest(summary_text=summary_text), self.assertRaises(cli_gate.CliGateError):
|
||||
self.validate_subscription(summary_text=summary_text, output=output)
|
||||
|
||||
def test_bad_notifications_partial_item_failure_and_missing_summary_counters_fail(self):
|
||||
for output, text in ((subscription_output().replace("(Good)", "(BadNoCommunication)"), summary()),
|
||||
(" FAILED to subscribe " + NODE + ": denied\n" + subscription_output(), summary()),
|
||||
(subscription_output(), summary(good=0, bad=1)),
|
||||
(subscription_output(), summary(good=0, never=1)),
|
||||
(subscription_output(), "==================== SUMMARY ====================\n")):
|
||||
with self.subTest(output=output, text=text), self.assertRaises(cli_gate.CliGateError):
|
||||
self.validate_subscription(output=output, summary_text=text)
|
||||
|
||||
def test_cli_builder_uses_published_dll_current_flags_and_keeps_secret_out_of_evidence(self):
|
||||
argv = cli_gate.build_cli_argv(Path("/unit/tools/ZB.MOM.WW.OtOpcUa.Client.CLI.dll"), "read",
|
||||
"opc.tcp://127.0.0.1:52113", KEY, node=NODE)
|
||||
self.assertEqual(argv[:3], ["dotnet", "/unit/tools/ZB.MOM.WW.OtOpcUa.Client.CLI.dll", "read"])
|
||||
self.assertEqual(argv[argv.index("-P") + 1], KEY)
|
||||
self.assertEqual(argv[argv.index("-n") + 1], NODE)
|
||||
self.assertNotIn("--json", argv)
|
||||
self.assertNotIn(KEY, repr(processes.redact_argv(argv)))
|
||||
|
||||
def test_cli_builder_rejects_exe_rebuilds_and_remote_endpoint(self):
|
||||
for dll, url in ((Path("/unit/tools/tool.exe"), "opc.tcp://127.0.0.1:52113"),
|
||||
(Path("/unit/tools/tool.dll"), "opc.tcp://10.100.0.35:4840")):
|
||||
with self.subTest(dll=dll, url=url), self.assertRaises(cli_gate.CliGateError):
|
||||
cli_gate.build_cli_argv(dll, "read", url, KEY, node=NODE)
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Safety units only: no Docker, HTTP, DNS, socket, or production fixture calls."""
|
||||
from copy import deepcopy
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import rig
|
||||
|
||||
|
||||
RUN = "unit-fixture-001"
|
||||
LABELS = {"otopcua.grpc-data.run": RUN,
|
||||
"com.docker.compose.project": f"grpc-data-{RUN}"}
|
||||
|
||||
|
||||
def manifest():
|
||||
return {
|
||||
"schema_version": 1, "run_id": RUN, "project": f"grpc-data-{RUN}",
|
||||
"labels": dict(LABELS),
|
||||
"services": ["sql", "device", "control-1", "control-2", "source-1", "source-2",
|
||||
"consumer-1", "consumer-2"],
|
||||
"endpoints": {
|
||||
"admin": {"scheme": "http", "host": "127.0.0.1", "host_port": 52111,
|
||||
"container_host": "control-1", "container_port": 9000},
|
||||
"source-1": {"scheme": "https", "host": "127.0.0.1", "host_port": 52112,
|
||||
"container_host": "source-1", "container_port": 4057}},
|
||||
"nodes": {"source-1": {"cluster_id": "SOURCE", "application_uri": "urn:unit:source-1"}},
|
||||
"resources": [{"kind": "container", "id": "unit-container", "labels": dict(LABELS)}],
|
||||
}
|
||||
|
||||
|
||||
class LocalDockerSafetyTests(unittest.TestCase):
|
||||
def test_accepts_only_local_unix_and_npipe_transports(self):
|
||||
for endpoint in ("unix:///var/run/docker.sock", "unix:///Users/unit/.docker/run/docker.sock",
|
||||
"npipe:////./pipe/docker_engine"):
|
||||
with self.subTest(endpoint=endpoint):
|
||||
rig.validate_local_docker(endpoint)
|
||||
|
||||
def test_rejects_remote_transports_even_on_loopback(self):
|
||||
for endpoint in ("ssh://unit@localhost", "tcp://127.0.0.1:2375", "tcp://10.100.0.35:2376",
|
||||
"http://localhost:2375", "unix://other-host/var/run/docker.sock", ""):
|
||||
with self.subTest(endpoint=endpoint), self.assertRaises(rig.RigError):
|
||||
rig.validate_local_docker(endpoint)
|
||||
|
||||
def test_context_resolution_cannot_hide_remote_endpoint(self):
|
||||
with self.assertRaises(rig.RigError):
|
||||
rig.validate_docker_context({"Name": "local-looking", "Endpoints": {
|
||||
"docker": {"Host": "ssh://unit@shared-host"}}}, environment={})
|
||||
|
||||
def test_remote_environment_override_rejected_even_with_local_context(self):
|
||||
context = {"Name": "desktop-linux", "Endpoints": {"docker": {"Host": "unix:///tmp/docker.sock"}}}
|
||||
for environment in ({"DOCKER_HOST": "tcp://localhost:2375"},
|
||||
{"DOCKER_CONTEXT": "other-context"}):
|
||||
with self.subTest(environment=environment), self.assertRaises(rig.RigError):
|
||||
rig.validate_docker_context(context, environment=environment)
|
||||
|
||||
def test_local_named_context_and_matching_override_allowed(self):
|
||||
context = {"Name": "desktop-linux", "Endpoints": {"docker": {"Host": "unix:///tmp/docker.sock"}}}
|
||||
rig.validate_docker_context(context, environment={"DOCKER_CONTEXT": "desktop-linux"})
|
||||
|
||||
def test_resolved_fixture_endpoints_allow_only_loopback_and_declared_services(self):
|
||||
document = {"services": {"source-1": {"environment": {
|
||||
"ConnectionStrings__ConfigDb": "Server=sql,1433;Database=fixture;Password=secret",
|
||||
"Mesh__Endpoint": "http://control-1:4055", "Device__Host": "device",
|
||||
"Security__Ldap__Server": "127.0.0.1"}}}}
|
||||
rig.validate_fixture_endpoints(document, local_services=set(manifest()["services"]))
|
||||
|
||||
def test_shared_endpoints_rejected_in_urls_sql_and_plain_host_options(self):
|
||||
for value in ({"url": "https://10.100.0.35:4057"},
|
||||
{"ConnectionStrings__ConfigDb": "Server=shared-db,1433;Database=x"},
|
||||
{"ConnectionStrings__FixturePg": "Host=10.100.0.35;Port=15432"},
|
||||
{"Oracle": "Data Source=10.100.0.35:11521/FREEPDB1"},
|
||||
{"Security__Ldap__Server": "shared-directory"},
|
||||
{"Device__Host": "host.docker.internal"},
|
||||
{"url": "http://[::ffff:10.100.0.35]:9000"},
|
||||
{"url": "http://${SHARED_HOST}:9000"}):
|
||||
with self.subTest(value=value), self.assertRaises(rig.RigError):
|
||||
rig.validate_fixture_endpoints(value, local_services=set(manifest()["services"]))
|
||||
|
||||
|
||||
class ManifestOwnershipTests(unittest.TestCase):
|
||||
def test_valid_manifest_accepts_dynamic_nondefault_loopback_ports(self):
|
||||
rig.validate_manifest(manifest(), expected_run_id=RUN)
|
||||
|
||||
def test_unknown_version_wrong_run_and_unsafe_project_rejected(self):
|
||||
for key, value in (("schema_version", 2), ("run_id", "../other"), ("project", "docker-dev")):
|
||||
candidate = manifest()
|
||||
candidate[key] = value
|
||||
with self.subTest(key=key), self.assertRaises(rig.RigError):
|
||||
rig.validate_manifest(candidate, expected_run_id=RUN)
|
||||
|
||||
def test_public_shared_duplicate_invalid_and_boolean_ports_rejected(self):
|
||||
for key, value in (("host", "0.0.0.0"), ("host", "10.100.0.35"), ("host_port", 52112),
|
||||
("host_port", 0), ("host_port", True), ("container_port", 65536),
|
||||
("container_host", "shared-host")):
|
||||
candidate = manifest()
|
||||
candidate["endpoints"]["admin"][key] = value
|
||||
with self.subTest(key=key, value=value), self.assertRaises(rig.RigError):
|
||||
rig.validate_manifest(candidate)
|
||||
|
||||
def test_missing_endpoint_node_identity_or_exact_ownership_fails(self):
|
||||
for mutate in (lambda m: m.update(endpoints={}), lambda m: m["nodes"]["source-1"].pop("cluster_id"),
|
||||
lambda m: m["labels"].pop("otopcua.grpc-data.run"),
|
||||
lambda m: m["resources"][0]["labels"].update({"otopcua.grpc-data.run": "other"})):
|
||||
candidate = manifest()
|
||||
mutate(candidate)
|
||||
with self.subTest(candidate=candidate), self.assertRaises(rig.RigError):
|
||||
rig.validate_manifest(candidate)
|
||||
|
||||
def test_cleanup_removes_only_recorded_ids_with_matching_run_and_project(self):
|
||||
candidate = manifest()
|
||||
observed = deepcopy(candidate["resources"])
|
||||
observed += [{"kind": "container", "id": "same-labels-unrecorded", "labels": dict(LABELS)},
|
||||
{"kind": "volume", "id": "developer-data", "labels": {}},
|
||||
{"kind": "container", "id": "another-run", "labels": {}}]
|
||||
removed = []
|
||||
rig.cleanup_owned(candidate, observed, remove=lambda kind, resource_id: removed.append((kind, resource_id)))
|
||||
self.assertEqual(removed, [("container", "unit-container")])
|
||||
|
||||
def test_cleanup_checks_all_ownership_before_first_deletion(self):
|
||||
candidate = manifest()
|
||||
candidate["resources"].append({"kind": "volume", "id": "unit-volume", "labels": dict(LABELS)})
|
||||
observed = deepcopy(candidate["resources"])
|
||||
observed[1]["labels"]["com.docker.compose.project"] = "docker-dev"
|
||||
removed = []
|
||||
with self.assertRaises(rig.RigError):
|
||||
rig.cleanup_owned(candidate, observed, remove=lambda *args: removed.append(args))
|
||||
self.assertEqual(removed, [])
|
||||
|
||||
def test_missing_resource_is_idempotent_but_duplicate_observations_fail(self):
|
||||
removed = []
|
||||
rig.cleanup_owned(manifest(), [], remove=lambda *args: removed.append(args))
|
||||
self.assertEqual(removed, [])
|
||||
with self.assertRaises(rig.RigError):
|
||||
rig.cleanup_owned(manifest(), manifest()["resources"] * 2,
|
||||
remove=lambda *args: removed.append(args))
|
||||
self.assertEqual(removed, [])
|
||||
|
||||
|
||||
class RestrictedSecretTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.path = Path(self.temp.name) / "credential.key"
|
||||
|
||||
def test_secret_is_restricted_before_atomic_publication(self):
|
||||
seen = []
|
||||
def publish(source, target):
|
||||
seen.append((Path(source).read_text(), stat.S_IMODE(os.stat(source).st_mode)))
|
||||
self.assertFalse(self.path.exists())
|
||||
os.replace(source, target)
|
||||
rig.atomic_write_secret(self.path, "unit-secret", replace=publish)
|
||||
self.assertEqual(seen, [("unit-secret", 0o600)])
|
||||
self.assertEqual(self.path.read_text(), "unit-secret")
|
||||
self.assertEqual(stat.S_IMODE(self.path.stat().st_mode), 0o600)
|
||||
|
||||
def test_failed_publication_keeps_old_secret_and_removes_temporary_file(self):
|
||||
self.path.write_text("old-secret")
|
||||
def interrupted(*args):
|
||||
raise OSError("interrupted")
|
||||
with self.assertRaises(OSError):
|
||||
rig.atomic_write_secret(self.path, "new-secret", replace=interrupted)
|
||||
self.assertEqual(self.path.read_text(), "old-secret")
|
||||
self.assertEqual(list(self.path.parent.iterdir()), [self.path])
|
||||
|
||||
def test_symlink_target_is_rejected_without_touching_destination(self):
|
||||
target = self.path.parent / "outside"
|
||||
target.write_text("untouched")
|
||||
self.path.symlink_to(target)
|
||||
with self.assertRaises(rig.RigError):
|
||||
rig.atomic_write_secret(self.path, "new-secret")
|
||||
self.assertEqual(target.read_text(), "untouched")
|
||||
|
||||
|
||||
class DeploymentPollingTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.calls = []
|
||||
self.now = 0.0
|
||||
self.responses = []
|
||||
self.base = "http://127.0.0.1:52111"
|
||||
self.deployment_id = "45b839a2-dc92-4f63-ad50-14eb9209e5a1"
|
||||
self.location = f"/api/deployments/{self.deployment_id}"
|
||||
|
||||
def request(self, method, url, *, headers, json_body, timeout):
|
||||
self.calls.append((method, url, headers, json_body, timeout))
|
||||
self.assertGreater(timeout, 0)
|
||||
return self.responses.pop(0)
|
||||
|
||||
def sleep(self, seconds):
|
||||
self.now += seconds
|
||||
|
||||
def status(self, state="Sealed", nodes=None):
|
||||
return {"deploymentId": self.deployment_id, "revisionHash": "unit-revision", "status": state,
|
||||
"failureReason": None, "nodes": nodes if nodes is not None else [
|
||||
{"nodeId": node, "status": "Applied", "appliedAtUtc": "2026-11-16T00:00:00Z", "failureReason": None}
|
||||
for node in ("source-1", "source-2")]}
|
||||
|
||||
def invoke(self, **kwargs):
|
||||
return rig.deploy_and_wait(self.base, "unit-deploy-key", {"source-1", "source-2"},
|
||||
request=self.request, clock=lambda: self.now, sleep=self.sleep,
|
||||
timeout=3, poll_interval=1, **kwargs)
|
||||
|
||||
def accepted(self):
|
||||
return (202, {"Location": self.location}, {"outcome": "Accepted", "deploymentId": self.deployment_id,
|
||||
"revisionHash": "unit-revision"})
|
||||
|
||||
def test_posts_created_by_only_once_then_polls_location_and_all_nodes(self):
|
||||
self.responses = [self.accepted(), (200, {}, self.status("AwaitingApplyAcks")),
|
||||
(200, {}, self.status())]
|
||||
result = self.invoke()
|
||||
self.assertEqual(result["revisionHash"], "unit-revision")
|
||||
self.assertEqual([call[0] for call in self.calls], ["POST", "GET", "GET"])
|
||||
self.assertEqual(self.calls[0][1], self.base + "/api/deployments")
|
||||
self.assertEqual(self.calls[0][3], {"createdBy": "grpc-data-local-gate"})
|
||||
self.assertEqual(self.calls[1][1], self.base + self.location)
|
||||
self.assertTrue(all(call[2]["X-Api-Key"] == "unit-deploy-key" for call in self.calls))
|
||||
|
||||
def test_bodyless_trigger_supported_without_artifact_upload(self):
|
||||
self.responses = [self.accepted(), (200, {}, self.status())]
|
||||
self.invoke(created_by=None)
|
||||
self.assertIsNone(self.calls[0][3])
|
||||
|
||||
def test_no_changes_still_polls_existing_deployment_for_apply_evidence(self):
|
||||
self.responses = [(200, {}, {"outcome": "NoChanges", "deploymentId": self.deployment_id,
|
||||
"revisionHash": "unit-revision"}), (200, {}, self.status())]
|
||||
self.invoke()
|
||||
self.assertEqual([call[0] for call in self.calls], ["POST", "GET"])
|
||||
|
||||
def test_no_changes_without_deployment_and_inflight_are_explicit_failures(self):
|
||||
for response in ((200, {}, {"outcome": "NoChanges", "deploymentId": None, "revisionHash": "unit-revision"}),
|
||||
(409, {}, {"outcome": "AnotherDeploymentInFlight"})):
|
||||
self.responses = [response]
|
||||
self.calls.clear()
|
||||
with self.subTest(response=response), self.assertRaises(rig.RigError):
|
||||
self.invoke()
|
||||
self.assertEqual(len(self.calls), 1)
|
||||
|
||||
def test_missing_unexpected_duplicate_failed_and_degraded_nodes_fail(self):
|
||||
base_nodes = self.status()["nodes"]
|
||||
variants = [base_nodes[:1], base_nodes + [dict(base_nodes[0], nodeId="unexpected")],
|
||||
base_nodes + [deepcopy(base_nodes[0])],
|
||||
[dict(base_nodes[0], status="Failed"), base_nodes[1]],
|
||||
[dict(base_nodes[0], failureReason="Applied degraded: unavailable"), base_nodes[1]],
|
||||
[dict(base_nodes[0], appliedAtUtc=None), base_nodes[1]]]
|
||||
for nodes in variants:
|
||||
self.responses = [self.accepted(), (200, {}, self.status(nodes=nodes))]
|
||||
with self.subTest(nodes=nodes), self.assertRaises(rig.RigError):
|
||||
self.invoke()
|
||||
|
||||
def test_deployment_revision_identity_terminal_state_and_remote_location_fail(self):
|
||||
for key, value in (("revisionHash", "wrong"), ("deploymentId", "another"),
|
||||
("status", "PartiallyFailed"), ("status", "Mystery")):
|
||||
status_body = self.status()
|
||||
status_body[key] = value
|
||||
self.responses = [self.accepted(), (200, {}, status_body)]
|
||||
with self.subTest(key=key), self.assertRaises(rig.RigError):
|
||||
self.invoke()
|
||||
response = self.accepted()
|
||||
self.responses = [(response[0], {"Location": "https://shared-host/api/deployments/other"}, response[2])]
|
||||
self.calls.clear()
|
||||
with self.assertRaises(rig.RigError):
|
||||
self.invoke()
|
||||
self.assertEqual(len(self.calls), 1)
|
||||
|
||||
def test_polling_deadline_is_bounded_and_never_reposts(self):
|
||||
self.responses = [self.accepted()] + [(200, {}, self.status("AwaitingApplyAcks"))] * 10
|
||||
with self.assertRaisesRegex(rig.RigError, "timeout|deadline"):
|
||||
self.invoke()
|
||||
self.assertLessEqual(self.now, 3)
|
||||
self.assertEqual(sum(call[0] == "POST" for call in self.calls), 1)
|
||||
|
||||
def test_unwired_production_actions_fail_clearly_without_side_effects(self):
|
||||
for action in ("up", "seed"):
|
||||
with self.subTest(action=action), patch("subprocess.Popen") as popen:
|
||||
with self.assertRaisesRegex(rig.RigError, "prerequisite|not configured|not wired"):
|
||||
rig.require_production_prerequisites(action, {})
|
||||
popen.assert_not_called()
|
||||
Reference in New Issue
Block a user