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