430 lines
21 KiB
Python
430 lines
21 KiB
Python
"""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())
|