"""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())