1491 lines
83 KiB
Python
1491 lines
83 KiB
Python
"""Standalone local Docker fixture, with pure safety and polling boundaries."""
|
|
import argparse
|
|
import copy
|
|
from contextlib import contextmanager
|
|
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."""
|
|
|
|
|
|
def bundle_commit_matches(expected, observed):
|
|
"""Require both production stores to acknowledge the exact published scope/version."""
|
|
if not isinstance(expected, dict) or not isinstance(observed, dict):
|
|
return False
|
|
if type(expected.get("scopeVersion")) is not int or expected["scopeVersion"] <= 0:
|
|
return False
|
|
if not all(type(observed.get(key)) is int and observed[key] == expected["scopeVersion"]
|
|
for key in ("credentialScopeVersion", "trustScopeVersion")):
|
|
return False
|
|
if expected.get("kind") == "scope-only":
|
|
return all(observed.get(key) is None
|
|
for key in ("credentialVersion", "trustVersion", "credentialDeleted", "trustRetired"))
|
|
if expected.get("kind", "entry") != "entry" or any(type(expected.get(key)) is not int or expected[key] <= 0
|
|
for key in ("credentialVersion", "trustVersion")):
|
|
return False
|
|
pairs = (("credentialScopeVersion", "scopeVersion"), ("trustScopeVersion", "scopeVersion"),
|
|
("credentialVersion", "credentialVersion"), ("trustVersion", "trustVersion"))
|
|
return (all(type(observed.get(actual)) is int and observed[actual] == expected[wanted]
|
|
for actual, wanted in pairs)
|
|
and all(type(expected.get(flag, False)) is bool and observed.get(flag) is expected.get(flag, False)
|
|
for flag in ("credentialDeleted", "trustRetired")))
|
|
|
|
|
|
def deployment_bundle_expectations(scope, published, *, selected=None):
|
|
"""Wait only for enabled scope entries actually published to required consumers."""
|
|
required = scope.get("required_node_ids")
|
|
connections = scope.get("connections")
|
|
if not isinstance(required, list) or not isinstance(connections, list) or not isinstance(published, list):
|
|
raise RigError("published deployment bundle inventory is missing")
|
|
consumers = NODES[2:] if selected is None else selected
|
|
wanted = {(node, item["connection_id"]) for item in connections for node in consumers
|
|
if node + ":4053" in required and node + ":4053" in item["consumer_node_ids"]}
|
|
scope_only_nodes = {node for node in consumers if node + ":4053" in required and not any(pair[0] == node for pair in wanted)}
|
|
wanted.update((node, "fixture-scope-only") for node in scope_only_nodes)
|
|
selected = []
|
|
seen = set()
|
|
for entry in published:
|
|
pair = (entry.get("node"), entry.get("connectionId"))
|
|
if pair not in wanted:
|
|
continue
|
|
if (pair in seen or (entry.get("kind") == "scope-only") != (pair[0] in scope_only_nodes)
|
|
or entry.get("scopeVersion") != scope.get("scope_version") or not bundle_commit_matches(entry, {
|
|
"credentialScopeVersion": entry.get("scopeVersion"), "trustScopeVersion": entry.get("scopeVersion"),
|
|
"credentialVersion": entry.get("credentialVersion"), "trustVersion": entry.get("trustVersion"),
|
|
"credentialDeleted": entry.get("credentialDeleted", False), "trustRetired": entry.get("trustRetired", False)})):
|
|
raise RigError("published deployment bundle inventory is invalid")
|
|
seen.add(pair)
|
|
selected.append(dict(entry))
|
|
if seen != wanted:
|
|
raise RigError("required deployment bundle entry was not published")
|
|
return selected
|
|
|
|
|
|
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)
|
|
akka_seed = (parsed.scheme == "akka.tcp" and parsed.username == "otopcua" and parsed.password is None
|
|
and parsed.path == "" and not parsed.query and not parsed.fragment
|
|
and re.fullmatch(r"(?:Cluster__SeedNodes__|Cluster:SeedNodes:)\d+|SeedNodes", key) is not None)
|
|
if (parsed.username is not None or parsed.password is not None) and not akka_seed:
|
|
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", on_accepted=None):
|
|
"""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")
|
|
if on_accepted is not None:
|
|
required = on_accepted(deployment_id, revision)
|
|
if required is not None:
|
|
if (not isinstance(required, (set, frozenset, list, tuple)) or not required
|
|
or any(not isinstance(node, str) for node in required) or not set(required) <= expected_nodes):
|
|
raise RigError("deployment required-node inventory is outside the owned topology")
|
|
expected_nodes = set(required)
|
|
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)}")
|
|
|
|
|
|
# Runtime composition. Every subprocess is argv-only, bounded and captures output;
|
|
# failed child diagnostics are deliberately withheld because Docker can echo env.
|
|
ROOT = Path(__file__).resolve().parents[3]
|
|
HERE = Path(__file__).resolve().parent
|
|
NODES = tuple(f"{pair}-{n}" for pair in ("control", "source", "consumer") for n in (1, 2))
|
|
# `questdb` exists only on a `--history-backend questdb` run (compose.history.questdb.yml), `opcplc` only on a `--conditions`
|
|
# run (compose.conditions.yml); listing them is the DNS allowlist.
|
|
SERVICES = ("sql", "migrator", "device", "seeder", "questdb", "opcplc", *NODES)
|
|
HISTORY_BACKENDS = ("sqlserver", "questdb")
|
|
|
|
|
|
def run_command(argv, *, timeout=120, environment=None):
|
|
from processes import ProcessError, run_process
|
|
import threading
|
|
if not isinstance(argv, list) or not argv or any(not isinstance(arg, str) or "\0" in arg for arg in argv):
|
|
raise RigError("invalid subprocess argv")
|
|
progress = None
|
|
observer = None
|
|
run_id = (environment or {}).get("GRPC_DATA_RUN_ID")
|
|
if run_id and _RUN_PATTERN.fullmatch(run_id):
|
|
log_dir = ROOT / "artifacts" / "grpc-data" / "runs" / run_id / "diagnostics"
|
|
log_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
if log_dir.is_symlink(): raise RigError("diagnostics directory cannot be linked")
|
|
fd = os.open(log_dir / (uuid.uuid4().hex + ".progress.log"), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
progress = os.fdopen(fd, "w")
|
|
lock = threading.Lock()
|
|
def observer(stream, chunk):
|
|
with lock:
|
|
progress.write(chunk); progress.flush()
|
|
try:
|
|
result = run_process(argv, cwd=ROOT, environment=environment, timeout=timeout,
|
|
max_output_bytes=16 * 1024 * 1024, observer=observer)
|
|
except (OSError, ProcessError):
|
|
raise RigError("local tool failed or exceeded its deadline; credentials withheld") from None
|
|
finally:
|
|
if progress is not None: progress.close()
|
|
if result.returncode or result.cancelled or result.timed_out or result.truncated:
|
|
run_id = (environment or {}).get("GRPC_DATA_RUN_ID")
|
|
if run_id and _RUN_PATTERN.fullmatch(run_id):
|
|
log_dir = ROOT / "artifacts" / "grpc-data" / "runs" / run_id / "diagnostics"
|
|
log_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
if log_dir.is_symlink(): raise RigError("diagnostics directory cannot be linked")
|
|
name = uuid.uuid4().hex
|
|
atomic_write_secret(log_dir / (name + ".stdout.log"), result.stdout or "(empty)\n")
|
|
atomic_write_secret(log_dir / (name + ".stderr.log"), result.stderr or "(empty)\n")
|
|
raise RigError("local tool returned failure; inspect restricted run diagnostics locally")
|
|
return result.stdout
|
|
|
|
|
|
def _image_input(name):
|
|
"""Whether repository-relative `name` is an image build input (the filter both tree hashes share)."""
|
|
suffix = Path(name).suffix
|
|
return not name.startswith(("docs/", "tests/", ".playwright-mcp/")) and (
|
|
suffix in {".cs", ".csproj", ".props", ".targets", ".slnx", ".resx", ".razor", ".css", ".js", ".proto"}
|
|
or name in {"global.json", "NuGet.Config", "nuget.config", "Directory.Build.rsp", ".dockerignore", "scripts/validation/grpc-data/Dockerfile"}
|
|
or name.startswith("src/") and suffix == ".json")
|
|
|
|
|
|
def _tree_hash(root, names):
|
|
import hashlib
|
|
digest = hashlib.sha256()
|
|
for name in sorted(set(filter(None, names))):
|
|
path = root / name
|
|
if not _image_input(name):
|
|
continue
|
|
if path.is_file() and not path.is_symlink():
|
|
digest.update(name.encode() + b"\0")
|
|
digest.update(hashlib.sha256(path.read_bytes()).digest())
|
|
return digest.hexdigest()
|
|
|
|
|
|
def source_tree_hash():
|
|
"""Hash image build inputs, including pending/new code, excluding review evidence.
|
|
|
|
Harness Python and test sources have their own evidence and do not enter the
|
|
Host/seeder/probe binaries. Notes can change without invalidating an image.
|
|
"""
|
|
paths = run_command(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"]).split("\0")
|
|
return _tree_hash(ROOT, paths)
|
|
|
|
|
|
# lmxopcua#921: a pinned pre-H2 SOURCE pair (plan §4.3 mixed versions, row "new consumer → v1 origin"). A pinned revision must
|
|
# CONTAIN X0 (a pre-X0 node rejects the whole data-connection snapshot once any newer bit is authored, so it is not the v1 origin
|
|
# the row describes) and must NOT contain H2 (whose merge adds the origin HistoryRead RPC and the `history` feature).
|
|
X0_MERGE = "a15912539f8a48804c31e74b2558994a50a338e6"
|
|
H2_MERGE = "ef938b435bbad2862bcd4b8e1f39e0b1ef2089b2"
|
|
PINNED_DATA_PROTO = "src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto"
|
|
# The only rig file added to a pinned tree: the self-contained data-listener wire tap (ASP.NET Core only, compiles at any revision).
|
|
PINNED_OVERLAY_FILES = ("scripts/validation/grpc-data/node-probe/WireTap.cs",)
|
|
|
|
|
|
def resolve_pinned_source_revision(revision, *, git=None):
|
|
"""The full SHA of `revision` once it is proven a post-X0, pre-H2 commit; RigError otherwise."""
|
|
git = git or (lambda *arguments: run_command(["git", *arguments]))
|
|
if not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{7,40}", revision):
|
|
raise RigError("a pinned SOURCE revision must be a hexadecimal commit id")
|
|
full = git("rev-parse", "--verify", "--quiet", revision + "^{commit}").strip()
|
|
if not re.fullmatch(r"[0-9a-f]{40}", full):
|
|
raise RigError("the pinned SOURCE revision does not name a commit")
|
|
if git("merge-base", X0_MERGE, full).strip() != X0_MERGE:
|
|
raise RigError("the pinned SOURCE revision predates X0 (tolerant readers); it would reject the whole snapshot")
|
|
if git("merge-base", H2_MERGE, full).strip() == H2_MERGE:
|
|
raise RigError("the pinned SOURCE revision contains H2; it is not a v1 (pre-history) origin")
|
|
if re.search(r"^\s*rpc\s+HistoryRead\b", git("show", f"{full}:{PINNED_DATA_PROTO}"), re.M):
|
|
raise RigError("the pinned SOURCE revision's data contract already has HistoryRead")
|
|
return full
|
|
|
|
|
|
def export_pinned_source(revision, directory):
|
|
"""Extract `revision`'s committed tree into a new restricted `directory` and add the rig's wire tap."""
|
|
import shutil
|
|
import subprocess
|
|
if directory.exists():
|
|
raise RigError("pinned SOURCE export directory already exists")
|
|
directory.mkdir(mode=0o700)
|
|
archive = subprocess.Popen(["git", "archive", "--format=tar", revision], cwd=ROOT, stdout=subprocess.PIPE)
|
|
try:
|
|
extract = subprocess.run(["tar", "-x", "-C", str(directory)], stdin=archive.stdout, timeout=600, check=False)
|
|
finally:
|
|
archive.stdout.close()
|
|
if archive.wait(timeout=600) != 0 or extract.returncode != 0:
|
|
raise RigError("could not export the pinned SOURCE revision")
|
|
for name in PINNED_OVERLAY_FILES:
|
|
target = directory / name
|
|
if target.exists():
|
|
raise RigError("the pinned SOURCE tree already has a rig overlay file")
|
|
shutil.copyfile(ROOT / name, target)
|
|
return pinned_tree_hash(directory)
|
|
|
|
|
|
def pinned_tree_hash(directory):
|
|
"""The image-input hash of an exported pinned tree (same filter as `source_tree_hash`)."""
|
|
names = [str(path.relative_to(directory)) for path in directory.rglob("*") if path.is_file() and not path.is_symlink()]
|
|
return _tree_hash(directory, [name.replace(os.sep, "/") for name in names])
|
|
|
|
|
|
def device_tree_hash():
|
|
"""Identify the fixture protocol/ledger implementation independently of Hosts."""
|
|
import hashlib
|
|
digest = hashlib.sha256()
|
|
for name in ("Dockerfile", "server.py"):
|
|
path = HERE / "device" / name
|
|
if path.is_symlink() or not path.is_file(): raise RigError("device fixture input is unavailable")
|
|
digest.update(name.encode() + b"\0" + path.read_bytes())
|
|
return digest.hexdigest()
|
|
|
|
|
|
def docker_context():
|
|
name = run_command(["docker", "context", "show"]).strip()
|
|
rows = json.loads(run_command(["docker", "context", "inspect", name]))
|
|
if not isinstance(rows, list) or len(rows) != 1:
|
|
raise RigError("Docker context inspection was ambiguous")
|
|
validate_docker_context(rows[0], environment=dict(os.environ))
|
|
return rows[0]
|
|
|
|
|
|
def http_request(method, url, *, headers, json_body=None, timeout=10):
|
|
import urllib.request
|
|
import urllib.error
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self, req, fp, code, msg, hdrs, newurl):
|
|
return None
|
|
data = None if json_body is None else json.dumps(json_body).encode()
|
|
request = urllib.request.Request(url, data=data, headers={**headers, **({"Content-Type": "application/json"} if data else {})}, method=method)
|
|
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
|
|
try:
|
|
response = opener.open(request, timeout=min(timeout, 15))
|
|
except urllib.error.HTTPError as error:
|
|
response = error
|
|
with response:
|
|
raw = response.read(1024 * 1024 + 1)
|
|
if len(raw) > 1024 * 1024:
|
|
raise RigError("HTTP response exceeded limit")
|
|
try:
|
|
body = json.loads(raw) if raw else None
|
|
except (ValueError, UnicodeError):
|
|
body = None
|
|
return response.status, dict(response.headers), body
|
|
|
|
|
|
def wait_until(predicate, *, timeout, description, interval=1):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
if predicate():
|
|
return
|
|
except (OSError, ValueError, RigError):
|
|
pass
|
|
time.sleep(min(interval, max(0, deadline - time.monotonic())))
|
|
raise RigError(f"deadline waiting for {description}")
|
|
|
|
|
|
def observe_active_endpoint(node_urls, *, request, timeout, require_ready=False, clock=None):
|
|
"""Observe the whole pair; one failed endpoint cannot hide its partner."""
|
|
_duration(timeout, "active endpoint observation timeout")
|
|
if not isinstance(node_urls, dict) or len(node_urls) != 2:
|
|
raise RigError("an explicit two-node active endpoint inventory is required")
|
|
clock = clock or time.monotonic
|
|
deadline = clock() + timeout
|
|
active = []
|
|
for node, origin in node_urls.items():
|
|
remaining = deadline - clock()
|
|
if remaining <= 0:
|
|
return None # An incomplete pair observation cannot select a node.
|
|
try:
|
|
status, _, _ = request("GET", origin.rstrip("/") + "/health/active", headers={}, timeout=min(5, remaining))
|
|
except OSError:
|
|
continue
|
|
if status == 200:
|
|
active.append(node)
|
|
if len(active) > 1:
|
|
raise RigError("pair has more than one observed active node")
|
|
if not active or clock() >= deadline:
|
|
return None
|
|
selected = active[0]
|
|
if require_ready:
|
|
remaining = deadline - clock()
|
|
if remaining <= 0:
|
|
return None
|
|
try:
|
|
status, _, _ = request("GET", node_urls[selected].rstrip("/") + "/health/ready", headers={}, timeout=min(5, remaining))
|
|
except OSError:
|
|
return None
|
|
if status != 200 or clock() >= deadline:
|
|
return None
|
|
return selected
|
|
|
|
|
|
def wait_active_endpoint(node_urls, *, request, timeout, require_ready=False, clock=None, sleep=None):
|
|
"""Bound startup/election polling without retrying any deployment mutation."""
|
|
_duration(timeout, "active endpoint selection timeout")
|
|
clock, sleep = clock or time.monotonic, sleep or time.sleep
|
|
deadline = clock() + timeout
|
|
while True:
|
|
remaining = deadline - clock()
|
|
if remaining <= 0:
|
|
raise RigError("deadline waiting for one ready active endpoint")
|
|
selected = observe_active_endpoint(node_urls, request=request, timeout=min(15, remaining),
|
|
require_ready=require_ready, clock=clock)
|
|
if selected is not None:
|
|
return selected
|
|
remaining = deadline - clock()
|
|
if remaining <= 0:
|
|
raise RigError("deadline waiting for one ready active endpoint")
|
|
sleep(min(1, remaining))
|
|
|
|
|
|
class LocalRig:
|
|
def __init__(self, run_id, *, base=None):
|
|
if not _RUN_PATTERN.fullmatch(run_id or ""):
|
|
raise RigError("a safe explicit --run-id is required")
|
|
self.run_id = run_id
|
|
self.folder = (Path(base) if base else ROOT / "artifacts" / "grpc-data" / "runs") / run_id
|
|
self.path = self.folder / "manifest.json"
|
|
self.project = "grpc-data-" + run_id
|
|
self.environment = dict(os.environ)
|
|
self.environment["COMPOSE_PROJECT_NAME"] = self.project
|
|
self.context = docker_context()
|
|
self.docker = ["docker", "--context", self.context["Name"]]
|
|
if self.folder.exists():
|
|
if self.folder.is_symlink() or self.folder.stat().st_mode & 0o077:
|
|
raise RigError("run directory must be restricted and cannot be a symlink")
|
|
env_path = self.folder / "environment.json"
|
|
if env_path.exists():
|
|
self.environment.update(json.loads(env_path.read_text()))
|
|
|
|
def compose_files(self):
|
|
"""The run's Compose files: the v1 fixture, plus the H2 history overlay when the run opted in."""
|
|
files = ["--file", str(HERE / "compose.yml")]
|
|
if self.environment.get("GRPC_DATA_HISTORY") == "1":
|
|
files.extend(["--file", str(HERE / "compose.history.yml")])
|
|
if self.environment.get("GRPC_DATA_HISTORY_BACKEND") == "questdb":
|
|
files.extend(["--file", str(HERE / "compose.history.questdb.yml")])
|
|
if self.environment.get("GRPC_DATA_CONDITIONS") == "1":
|
|
files.extend(["--file", str(HERE / "compose.conditions.yml")])
|
|
if self.environment.get("GRPC_DATA_SOURCE_PINNED") == "1":
|
|
files.extend(["--file", str(HERE / "compose.source-pinned.yml")])
|
|
return files
|
|
|
|
def compose(self, *args, timeout=120):
|
|
return run_command([*self.docker, "compose", "--project-name", self.project, *self.compose_files(), *args], timeout=timeout, environment=self.environment)
|
|
|
|
@contextmanager
|
|
def hub_partitions(self, count):
|
|
"""Restart only the owned SOURCE pair with an explicit hub partition count.
|
|
|
|
Port allocation changes when Compose recreates a container, so every
|
|
transition refreshes the canonical manifest before readiness polling.
|
|
"""
|
|
if type(count) is not int or not 1 <= count <= 256:
|
|
raise RigError("hub partition count must be between 1 and 256")
|
|
with self._configuration_experiment("hub-partitions", ("source-1", "source-2"),
|
|
{"DataConnections__Hub__PartitionCount": str(count)}):
|
|
yield
|
|
|
|
@contextmanager
|
|
def compact_batches(self, enabled):
|
|
"""Exercise the production caller's negotiated encoding preference."""
|
|
if type(enabled) is not bool:
|
|
raise RigError("compact encoding preference must be boolean")
|
|
with self._configuration_experiment("compact-batches", ("consumer-1", "consumer-2"),
|
|
{"DataConnections__UseCompactBatches": str(enabled).lower()}):
|
|
yield
|
|
|
|
@contextmanager
|
|
def _configuration_experiment(self, name, nodes, environment, *, before_restore=None):
|
|
override = self.folder / (name + ".json")
|
|
if override.exists():
|
|
raise RigError("a configuration experiment is already present")
|
|
def transition(extra):
|
|
# Inspect exact project resources before changing its owned services.
|
|
self.inspect_resources()
|
|
run_command([*self.docker, "compose", "--project-name", self.project,
|
|
*self.compose_files(), *extra, "up", "--detach", "--no-deps", *nodes],
|
|
timeout=300, environment=self.environment)
|
|
manifest = self.refresh_endpoints(nodes)
|
|
self.capture(manifest)
|
|
wait_until(lambda: self.health(manifest), timeout=180, description="configuration experiment pair readiness")
|
|
atomic_write_secret(override, json.dumps({"services": {node: {"environment": environment} for node in nodes}}))
|
|
try:
|
|
transition(["--file", str(override)])
|
|
yield
|
|
finally:
|
|
try:
|
|
if before_restore is not None:
|
|
before_restore()
|
|
transition([])
|
|
finally:
|
|
override.unlink(missing_ok=True)
|
|
|
|
def save(self, manifest):
|
|
atomic_write_secret(self.path, json.dumps(manifest, indent=2, sort_keys=True) + "\n")
|
|
|
|
def load(self):
|
|
if not self.path.is_file() or self.path.is_symlink():
|
|
raise RigError("restricted run manifest is missing")
|
|
manifest = json.loads(self.path.read_text())
|
|
validate_manifest(manifest, expected_run_id=self.run_id)
|
|
if manifest.get("docker_context") != self.context["Name"]:
|
|
raise RigError("selected Docker context differs from the recorded run")
|
|
return manifest
|
|
|
|
def verify_candidate(self):
|
|
"""Match every running Host binary stamp to the actual compiled inputs."""
|
|
manifest = self.load()
|
|
expected = source_tree_hash()
|
|
if manifest.get("source_tree_hash") != expected:
|
|
raise RigError("running manifest does not match current image build inputs")
|
|
pinned = manifest.get("source_pinned")
|
|
if pinned is not None:
|
|
# lmxopcua#921: the SOURCE pair runs the pinned revision; its export must still hash to what was built.
|
|
if (not isinstance(pinned, dict) or pinned_tree_hash(self.folder / "pinned-source") != pinned.get("tree_hash")
|
|
or pinned.get("revision") != self.environment.get("GRPC_DATA_SOURCE_PINNED_REVISION")):
|
|
raise RigError("pinned SOURCE export does not match the recorded pinned build")
|
|
for node in NODES:
|
|
raw = self.compose("exec", "--no-TTY", node, "cat", "/app/grpc-data-source.json", timeout=15)
|
|
stamp = json.loads(raw)
|
|
want = ((pinned["tree_hash"], pinned["revision"]) if pinned is not None and node.startswith("source-")
|
|
else (expected, manifest.get("source_revision")))
|
|
if stamp.get("tree_hash") != want[0] or stamp.get("revision") != want[1]:
|
|
raise RigError("running Host build stamp does not match the candidate")
|
|
device_hash = device_tree_hash()
|
|
if manifest.get("device_source_hash") != device_hash:
|
|
raise RigError("device manifest does not match current fixture inputs")
|
|
observed = self.compose("exec", "--no-TTY", "device", "cat", "/fixture/source-hash", timeout=15).strip()
|
|
if observed != device_hash:
|
|
raise RigError("running device fixture does not match current protocol/ledger inputs")
|
|
return expected
|
|
|
|
def inspect_resources(self):
|
|
resources = []
|
|
for kind, listing in (("container", ["container", "ls", "-a", "-q"]), ("network", ["network", "ls", "-q"]), ("volume", ["volume", "ls", "-q"]), ("image", ["image", "ls", "-q"])):
|
|
ids = run_command([*self.docker, *listing, "--filter", f"label={RUN_LABEL}={self.run_id}", "--filter", f"label={PROJECT_LABEL}={self.project}"]).split()
|
|
for identity in dict.fromkeys(ids):
|
|
row = json.loads(run_command([*self.docker, kind, "inspect", identity]))[0]
|
|
labels = row.get("Config", {}).get("Labels") if kind in {"container", "image"} else row.get("Labels")
|
|
if not isinstance(labels, dict) or labels.get(RUN_LABEL) != self.run_id or labels.get(PROJECT_LABEL) != self.project:
|
|
raise RigError("observed Docker object ownership mismatch")
|
|
resources.append({"kind": kind, "id": row.get("Id", row.get("Name")), "labels": labels})
|
|
return resources
|
|
|
|
def capture(self, manifest):
|
|
manifest["resources"] = self.inspect_resources()
|
|
self.save(manifest)
|
|
|
|
def allocate_manifest(self):
|
|
endpoints = {}
|
|
for node in (*NODES, "sql", "device"):
|
|
ids = self.compose("ps", "--all", "--quiet", node).split()
|
|
if len(ids) != 1:
|
|
raise RigError("fixture must contain exactly one container per service")
|
|
row = json.loads(run_command([*self.docker, "container", "inspect", ids[0]]))[0]
|
|
for container_port, bindings in row["NetworkSettings"]["Ports"].items():
|
|
if not bindings:
|
|
continue
|
|
port = int(container_port.split("/")[0])
|
|
if len(bindings) != 1 or bindings[0]["HostIp"] != "127.0.0.1":
|
|
raise RigError("Docker published a fixture port outside loopback")
|
|
suffix = {9000: "admin", 4840: "opcua", 4057: "data", 1433: "sql", 5020: "modbus", 8080: "control"}[port]
|
|
scheme = {4840: "opc.tcp", 4057: "https", 1433: "tcp", 5020: "tcp"}.get(port, "http")
|
|
host_port = int(bindings[0]["HostPort"])
|
|
path = "/OtOpcUa" if port == 4840 else ""
|
|
endpoints[f"{node}.{suffix}"] = {"scheme": scheme, "host": "127.0.0.1", "host_port": host_port,
|
|
"container_host": node, "container_port": port, "url": f"{scheme}://127.0.0.1:{host_port}{path}"}
|
|
return {"schema_version": 1, "run_id": self.run_id, "project": self.project,
|
|
"labels": {RUN_LABEL: self.run_id, PROJECT_LABEL: self.project}, "services": list(SERVICES),
|
|
"docker_context": self.context["Name"], "endpoints": endpoints, "resources": [],
|
|
"nodes": {node: {"cluster_id": node.split("-")[0].upper(), "node_id": node + ":4053", "application_uri": "urn:OtOpcUa:grpc-data:" + node} for node in NODES},
|
|
"tls": {"ca_file": str(self.folder / "security" / "ca.pem")}, "state": "started"}
|
|
|
|
def refresh_endpoints(self, nodes):
|
|
"""Refresh only restarted owned services, preserving intentionally stopped peers."""
|
|
if (not isinstance(nodes, (tuple, list)) or not nodes or any(not isinstance(node, str) or node not in NODES for node in nodes)
|
|
or len(nodes) != len(set(nodes))):
|
|
raise RigError("endpoint refresh requires unique owned node services")
|
|
manifest = copy.deepcopy(self.load())
|
|
for node in nodes:
|
|
ids = self.compose("ps", "--all", "--quiet", node).split()
|
|
if len(ids) != 1:
|
|
raise RigError("endpoint refresh requires exactly one owned service container")
|
|
try:
|
|
rows = json.loads(run_command([*self.docker, "container", "inspect", ids[0]]))
|
|
if not isinstance(rows, list) or len(rows) != 1:
|
|
raise ValueError()
|
|
row = rows[0]
|
|
labels = row.get("Config", {}).get("Labels", {})
|
|
if (not isinstance(labels, dict) or labels.get(RUN_LABEL) != self.run_id
|
|
or labels.get(PROJECT_LABEL) != self.project or labels.get("com.docker.compose.service") != node
|
|
or row.get("State", {}).get("Running") is not True):
|
|
raise ValueError()
|
|
ports = row["NetworkSettings"]["Ports"]
|
|
expected = {"4840/tcp": ("opcua", "opc.tcp"), "9000/tcp": ("admin", "http")}
|
|
if not node.startswith("control-"):
|
|
expected["4057/tcp"] = ("data", "https")
|
|
if not isinstance(ports, dict) or any(bindings and port not in expected for port, bindings in ports.items()):
|
|
raise ValueError()
|
|
for port, (suffix, scheme) in expected.items():
|
|
bindings = ports.get(port)
|
|
if (not isinstance(bindings, list) or len(bindings) != 1
|
|
or bindings[0].get("HostIp") != "127.0.0.1"):
|
|
raise ValueError()
|
|
allocated = int(bindings[0]["HostPort"])
|
|
if not _port(allocated):
|
|
raise ValueError()
|
|
container_port = int(port.split("/")[0])
|
|
path = "/OtOpcUa" if suffix == "opcua" else ""
|
|
manifest["endpoints"][node + "." + suffix] = {"scheme": scheme, "host": "127.0.0.1",
|
|
"host_port": allocated, "container_host": node, "container_port": container_port,
|
|
"url": f"{scheme}://127.0.0.1:{allocated}{path}"}
|
|
except (ValueError, TypeError, KeyError, AttributeError):
|
|
raise RigError("endpoint refresh requires an owned running container with complete loopback bindings") from None
|
|
validate_manifest(manifest, expected_run_id=self.run_id)
|
|
self.save(manifest)
|
|
return manifest
|
|
|
|
def up(self, timeout=600, history=False, history_backend="sqlserver", conditions=False, source_revision=None):
|
|
import secrets
|
|
import credentials
|
|
if self.folder.exists():
|
|
raise RigError("run already exists; use status or owned down before reusing its id")
|
|
self.folder.mkdir(parents=True, mode=0o700)
|
|
os.chmod(self.folder, 0o700)
|
|
atomic_write_secret(self.folder / "setup.json", json.dumps({"run_id": self.run_id, "docker_context": self.context["Name"], "project": self.project}))
|
|
revision = run_command(["git", "rev-parse", "HEAD"]).strip()
|
|
tree_hash = source_tree_hash()
|
|
settings = {"GRPC_DATA_UID": str(os.getuid()) if hasattr(os, "getuid") else "0", "GRPC_DATA_GID": str(os.getgid()) if hasattr(os, "getgid") else "0", "GRPC_DATA_RUN_ID": self.run_id, "GRPC_DATA_PROJECT": self.project, "SOURCE_REVISION": revision, "SOURCE_TREE_HASH": tree_hash, "DEVICE_TREE_HASH": device_tree_hash(),
|
|
"GRPC_DATA_IMAGE": f"otopcua-grpc-data:{self.run_id}", "GRPC_DATA_MIGRATOR_IMAGE": f"otopcua-grpc-migrator:{self.run_id}",
|
|
"GRPC_DATA_DEVICE_IMAGE": f"otopcua-grpc-device:{self.run_id}", "GRPC_DATA_SEED_IMAGE": f"otopcua-grpc-seed:{self.run_id}",
|
|
"GRPC_DATA_CERT_DIR": str(self.folder / "security" / "tls"), "GRPC_DATA_CREDENTIAL_DIR": str(self.folder / "security" / "credentials"),
|
|
"GRPC_DATA_OUTPUT_DIR": str(self.folder / "seed"), "GRPC_DATA_PROBE_DIR": str(self.folder / "probe")}
|
|
for name in ("APIKEY_PEPPER", "JWT_KEY", "DEPLOY_KEY", "CONFIG_KEY", "TELEMETRY_KEY", "MESH_PSK_CONTROL", "MESH_PSK_SOURCE", "MESH_PSK_CONSUMER", "SYNC_KEY_SOURCE", "SYNC_KEY_CONSUMER"):
|
|
settings["GRPC_DATA_" + name] = secrets.token_hex(32)
|
|
settings["GRPC_DATA_SQL_PASSWORD"] = "Gd!" + secrets.token_hex(24)
|
|
import base64
|
|
settings["GRPC_DATA_SECRETS_KEK"] = base64.b64encode(secrets.token_bytes(32)).decode()
|
|
if history:
|
|
if history_backend not in HISTORY_BACKENDS:
|
|
raise RigError("unknown history backend")
|
|
settings["GRPC_DATA_HISTORY"] = "1"
|
|
settings["GRPC_DATA_HISTORY_BACKEND"] = history_backend
|
|
if conditions:
|
|
settings["GRPC_DATA_CONDITIONS"] = "1"
|
|
pinned = None
|
|
if source_revision is not None:
|
|
# lmxopcua#921: the SOURCE pair is built from a pinned post-X0, pre-H2 revision (the "v1 origin"); CONTROL and
|
|
# CONSUMER stay on this checkout. Only the wire tap is added to the pinned tree.
|
|
full = resolve_pinned_source_revision(source_revision)
|
|
pinned = {"revision": full, "tree_hash": export_pinned_source(full, self.folder / "pinned-source"),
|
|
"x0_merge": X0_MERGE, "h2_merge_absent": H2_MERGE, "overlay_files": list(PINNED_OVERLAY_FILES)}
|
|
settings.update({"GRPC_DATA_SOURCE_PINNED": "1", "GRPC_DATA_SOURCE_PINNED_REVISION": full,
|
|
"GRPC_DATA_SOURCE_PINNED_TREE_HASH": pinned["tree_hash"], "GRPC_DATA_SOURCE_PINNED_CONTEXT": str(self.folder / "pinned-source"),
|
|
"GRPC_DATA_SOURCE_IMAGE": f"otopcua-grpc-data-source-pinned:{self.run_id}"})
|
|
atomic_write_secret(self.folder / "environment.json", json.dumps(settings))
|
|
self.environment.update(settings)
|
|
credentials.provision_tls(self.folder / "security", NODES[2:])
|
|
(self.folder / "security" / "credentials").mkdir(mode=0o700)
|
|
for node in NODES[2:]:
|
|
(self.folder / "security" / "credentials" / node).mkdir(parents=True, mode=0o700)
|
|
(self.folder / "seed").mkdir(mode=0o700)
|
|
(self.folder / "probe").mkdir(mode=0o700)
|
|
for node in NODES:
|
|
(self.folder / "probe" / node).mkdir(parents=True, mode=0o700)
|
|
# Save a restricted setup journal before the first mutation, so interrupted
|
|
# builds can still be collected by exact observed object IDs on `down`.
|
|
atomic_write_secret(self.folder / "setup.json", json.dumps({"run_id": self.run_id, "docker_context": self.context["Name"], "project": self.project}))
|
|
resolved = json.loads(self.compose("config", "--format", "json"))
|
|
validate_fixture_endpoints(resolved, local_services=SERVICES)
|
|
try:
|
|
self.compose("build", "--pull", "migrator", "device", "control-1", "seeder", *(["source-1"] if pinned else []),
|
|
timeout=2400 if pinned else 1800) # a pinned run builds a second Host image
|
|
self.compose("up", "--detach", "sql", "device", "migrator", *NODES, timeout=timeout)
|
|
manifest = self.allocate_manifest()
|
|
manifest["source_revision"] = revision
|
|
manifest["source_tree_hash"] = tree_hash
|
|
manifest["device_source_hash"] = settings["DEVICE_TREE_HASH"]
|
|
if pinned is not None:
|
|
manifest["source_pinned"] = pinned
|
|
self.capture(manifest)
|
|
wait_until(lambda: self.health(manifest, require_catalog=False), timeout=timeout, description="six node health and independent pair roles")
|
|
manifest["state"] = "up"
|
|
self.capture(manifest)
|
|
return manifest
|
|
except BaseException:
|
|
# Capture whatever exists; no broad compose down/prune is permitted.
|
|
atomic_write_secret(self.folder / "interrupted-resources.json", json.dumps(self.inspect_resources()))
|
|
raise
|
|
|
|
def health(self, manifest, *, require_catalog=False, timeout=None):
|
|
deadline = None if timeout is None else time.monotonic() + timeout
|
|
def request_timeout():
|
|
remaining = 5 if deadline is None else deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
raise RigError("fixture readiness deadline timeout")
|
|
return min(5, remaining)
|
|
active = {}
|
|
for node in NODES:
|
|
origin = manifest["endpoints"][node + ".admin"]["url"]
|
|
status, _, _ = http_request("GET", origin + "/health/ready", headers={}, timeout=request_timeout())
|
|
if status != 200:
|
|
return False
|
|
status, _, _ = http_request("GET", origin + "/health/active", headers={}, timeout=request_timeout())
|
|
active[node] = status == 200
|
|
if any(sum(active[node] for node in NODES if node.startswith(pair + "-")) != 1 for pair in ("control", "source", "consumer")):
|
|
return False
|
|
if require_catalog:
|
|
# Namespace resolution reads through real OPC UA sessions on all six
|
|
# hosts, validates each URI, and requires Good fixture leaf values.
|
|
remaining = 120 if deadline is None else deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
raise RigError("fixture catalog readiness deadline timeout")
|
|
self.seed_helper("resolve", timeout=min(120, remaining))
|
|
if deadline is not None and time.monotonic() >= deadline:
|
|
raise RigError("fixture readiness exceeded its deadline")
|
|
return True
|
|
|
|
def seed_helper(self, action, *arguments, timeout=120):
|
|
self.compose("run", "--rm", "--no-deps", "seeder", action, *arguments, timeout=timeout)
|
|
|
|
def seed(self):
|
|
manifest = self.load()
|
|
self.seed_helper("seed")
|
|
fixture = json.loads((self.folder / "seed" / "fixture.json").read_text())
|
|
validate_fixture_endpoints(fixture.get("endpoints", {}), local_services=SERVICES)
|
|
manifest["fixture"] = fixture
|
|
manifest["node_probe_dirs"] = {node: str(self.folder / "probe" / node) for node in NODES}
|
|
manifest["credentials"] = {"cli_key_file": str(self.folder / "seed" / "cli.key"),
|
|
"data_key_files": {"source": str(self.folder / "seed" / "source.key")}}
|
|
if self.environment.get("GRPC_DATA_HISTORY") == "1":
|
|
manifest["credentials"]["data_key_files"]["source_nohistory"] = str(self.folder / "seed" / "source-nohistory.key")
|
|
if self.environment.get("GRPC_DATA_CONDITIONS") == "1":
|
|
# A4: the UNS-only origin principal (A04) and the CONSUMER CLI principal without a mapping grant (A05).
|
|
manifest["credentials"]["data_key_files"]["source_unsonly"] = str(self.folder / "seed" / "source-unsonly.key")
|
|
manifest["credentials"]["data_key_files"]["cli_nogrant"] = str(self.folder / "seed" / "cli-nogrant.key")
|
|
manifest["credentials"]["data_key_files"]["cli_alt"] = str(self.folder / "seed" / "cli-alt.key")
|
|
manifest["state"] = "seeded"
|
|
self.capture(manifest)
|
|
return manifest
|
|
|
|
def provision_deployment(self, deployment_id, revision, *, timeout=120):
|
|
import credentials
|
|
self.seed_helper("scope", deployment_id, revision, timeout=timeout)
|
|
scope = json.loads((self.folder / "seed" / "scope.json").read_text())
|
|
published = self.publish_scope(scope)
|
|
scope["bundle_expectations"] = deployment_bundle_expectations(scope, published)
|
|
return scope
|
|
|
|
def bundle_version(self, node):
|
|
directory = self.folder / "security" / "credentials" / node
|
|
bundle = directory / "bundle.json"
|
|
generation = directory / "generation.txt"
|
|
return max(json.loads(bundle.read_text())["Version"] if bundle.exists() else 0,
|
|
int(generation.read_text()) if generation.exists() else 0) + 1
|
|
|
|
def publish_scope(self, scope, *, selected=None, deleted=False):
|
|
import base64
|
|
import credentials
|
|
key = (self.folder / "seed" / "source.key").read_text().strip()
|
|
state_path = self.folder / "trust-state.json"
|
|
ca_files = json.loads(state_path.read_text())["roots"] if state_path.exists() else [str(self.folder / "security" / "ca.pem")]
|
|
roots = [base64.b64encode(credentials._openssl("x509", "-in", path, "-outform", "DER")).decode("ascii") for path in ca_files]
|
|
nodes = {}
|
|
for node in selected if selected is not None else NODES[2:]:
|
|
entries = [{"ConnectionId": item["connection_id"], "SecretReference": item["secret_reference"], "Value": None if deleted else key, "Deleted": deleted}
|
|
for item in scope["connections"] if node + ":4053" in item["consumer_node_ids"]]
|
|
version = self.bundle_version(node)
|
|
nodes[node] = {"owner": node.split("-")[0].upper(), "scope_version": scope["scope_version"], "entries": entries,
|
|
"bundle_version": version, "trust_version": version, "trust_roots": roots}
|
|
directory = self.folder / "security" / "credentials" / node
|
|
for name in ("bundle", "trust"):
|
|
current = directory / (name + ".json")
|
|
if current.exists():
|
|
atomic_write_secret(directory / (name + "-previous.json"), current.read_text())
|
|
credentials.write_bundles(self.folder / "security", nodes)
|
|
for node, spec in nodes.items():
|
|
atomic_write_secret(self.folder / "security" / "credentials" / node / "generation.txt", str(spec["bundle_version"]))
|
|
entries = [{"node": node, "connectionId": entry["ConnectionId"], "scopeVersion": spec["scope_version"],
|
|
"kind": "entry",
|
|
"credentialVersion": spec["bundle_version"], "trustVersion": spec["trust_version"],
|
|
"credentialDeleted": entry["Deleted"], "trustRetired": False}
|
|
for node, spec in nodes.items() for entry in spec["entries"]]
|
|
return entries + [{"node": node, "connectionId": "fixture-scope-only", "kind": "scope-only",
|
|
"scopeVersion": spec["scope_version"], "credentialVersion": None, "trustVersion": None,
|
|
"credentialDeleted": None, "trustRetired": None} for node, spec in nodes.items() if not spec["entries"]]
|
|
|
|
def wait_bundle_commits(self, expectations, *, timeout):
|
|
"""Observe exact numeric acknowledgements through each caller's production DI stores."""
|
|
_duration(timeout, "bundle commit readiness timeout")
|
|
if not isinstance(expectations, list):
|
|
raise RigError("published bundle expectations are missing")
|
|
deadline = time.monotonic() + timeout
|
|
records = []
|
|
safe_fields = ("credentialScopeVersion", "credentialVersion", "trustScopeVersion", "trustVersion",
|
|
"credentialDeleted", "trustRetired")
|
|
diagnostics = self.folder / "seed" / "bundle-commit-readiness.json"
|
|
atomic_write_secret(diagnostics, json.dumps({"required_entries": len(expectations), "entries": records}))
|
|
for expected in expectations:
|
|
node = expected["node"]
|
|
folder = self.folder / "probe" / node
|
|
if node not in NODES[2:] or folder.is_symlink() or not folder.is_dir():
|
|
raise RigError("bundle acknowledgement requires an owned data-node probe directory")
|
|
record = {"node": node, "connectionId": expected["connectionId"],
|
|
"expected": {key: expected[key] for key in ("scopeVersion", "credentialVersion", "trustVersion",
|
|
"credentialDeleted", "trustRetired")},
|
|
"observed": None, "matched": False}
|
|
record["expected"]["kind"] = expected.get("kind", "entry")
|
|
records.append(record)
|
|
atomic_write_secret(diagnostics, json.dumps({"required_entries": len(expectations), "entries": records}))
|
|
while True:
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
raise RigError("deadline waiting for exact credential and trust bundle acknowledgements")
|
|
identity = "bundle-" + uuid.uuid4().hex
|
|
request = folder / (identity + ".request.json")
|
|
response = folder / (identity + ".result.json")
|
|
atomic_write_secret(request, json.dumps({"id": identity, "operation": "bundle-commit",
|
|
"connectionId": expected["connectionId"], "timeoutSeconds": max(1, min(5, int(remaining)))}))
|
|
try:
|
|
while not response.exists():
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
raise RigError("deadline waiting for bundle acknowledgement probe")
|
|
time.sleep(min(.1, remaining))
|
|
if time.monotonic() > deadline:
|
|
raise RigError("deadline waiting for bundle acknowledgement probe")
|
|
if response.is_symlink() or not response.is_file() or response.stat().st_size > 16384:
|
|
raise RigError("bundle acknowledgement probe output is invalid")
|
|
result = json.loads(response.read_text())
|
|
if (result.get("id") != identity or result.get("operation") != "bundle-commit"
|
|
or result.get("passed") is not True or type(result.get("assertions")) is not int
|
|
or result["assertions"] <= 0 or not isinstance(result.get("observations"), dict)):
|
|
raise RigError("bundle acknowledgement probe identity or result is invalid")
|
|
observed = {key: result["observations"].get(key) for key in safe_fields}
|
|
if any(value is not None and type(value) is not (bool if key in {"credentialDeleted", "trustRetired"} else int)
|
|
for key, value in observed.items()):
|
|
raise RigError("bundle acknowledgement fields must be nullable numeric versions or state flags")
|
|
record["observed"] = observed
|
|
record["matched"] = bundle_commit_matches(record["expected"], record["observed"])
|
|
atomic_write_secret(diagnostics, json.dumps({"required_entries": len(expectations), "entries": records}))
|
|
if record["matched"]:
|
|
break
|
|
finally:
|
|
request.unlink(missing_ok=True)
|
|
time.sleep(min(.1, max(0, deadline - time.monotonic())))
|
|
return records
|
|
|
|
def credential_action(self, action, node=None):
|
|
"""Publish through the actual node bundle loader, never fake an auth result."""
|
|
if node is not None and node not in NODES[2:]:
|
|
raise RigError("credential action requires an owned data node")
|
|
selected = [node] if node is not None else [name for name in NODES if name.startswith("consumer-")]
|
|
if action == "reload_stale_bundle":
|
|
for name in selected:
|
|
directory = self.folder / "security" / "credentials" / name
|
|
for kind in ("bundle", "trust"):
|
|
previous = directory / (kind + "-previous.json")
|
|
if not previous.is_file():
|
|
raise RigError("no previous bundle is available for stale replay")
|
|
atomic_write_secret(directory / (kind + ".json"), previous.read_text())
|
|
elif action in {"remove_consumer_secret", "provision_consumer_secret"}:
|
|
scope = json.loads((self.folder / "seed" / "scope.json").read_text())
|
|
published = self.publish_scope(scope, selected=selected, deleted=action == "remove_consumer_secret")
|
|
self.wait_bundle_commits(deployment_bundle_expectations(scope, published, selected=selected), timeout=120)
|
|
else:
|
|
raise RigError("unknown credential fixture action")
|
|
return {"action": action, "nodes": selected}
|
|
|
|
def trust_action(self, action):
|
|
"""Stage trust, replace owned server certs, then retire the original CA."""
|
|
import credentials
|
|
security = self.folder / "security"
|
|
next_security = self.folder / "security-next"
|
|
state_path = self.folder / "trust-state.json"
|
|
if action == "stage_new":
|
|
if next_security.exists():
|
|
raise RigError("a CA rotation is already staged")
|
|
credentials.provision_tls(next_security, NODES[2:])
|
|
for node in NODES[2:]:
|
|
for kind in ("pem", "key"):
|
|
directory = security / "tls" / node
|
|
atomic_write_secret(directory / ("server-original." + kind), (directory / ("server." + kind)).read_text())
|
|
original = security / "ca-original.pem"
|
|
atomic_write_secret(original, (security / "ca.pem").read_text())
|
|
atomic_write_secret(state_path, json.dumps({"phase": "staged", "roots": [str(original), str(next_security / "ca.pem")]}))
|
|
atomic_write_secret(security / "ca.pem", original.read_text() + (next_security / "ca.pem").read_text())
|
|
else:
|
|
if not state_path.exists():
|
|
raise RigError("CA rotation has not been staged")
|
|
state = json.loads(state_path.read_text())
|
|
if action == "rotate_server":
|
|
if state["phase"] != "staged":
|
|
raise RigError("server certificates can rotate only after trust staging")
|
|
for node in NODES[2:]:
|
|
for name in ("server.pem", "server.key"):
|
|
atomic_write_secret(security / "tls" / node / name, (next_security / "tls" / node / name).read_text())
|
|
self.compose("restart", *NODES[2:], timeout=120)
|
|
self.refresh_endpoints(NODES[2:])
|
|
state["phase"] = "rotated"
|
|
elif action == "retire_old":
|
|
if state["phase"] != "rotated":
|
|
raise RigError("old CA can retire only after server certificate rotation")
|
|
state = {"phase": "retired", "roots": [str(next_security / "ca.pem")]}
|
|
atomic_write_secret(security / "ca.pem", (next_security / "ca.pem").read_text())
|
|
else:
|
|
raise RigError("unknown trust fixture action")
|
|
atomic_write_secret(state_path, json.dumps(state))
|
|
scope = json.loads((self.folder / "seed" / "scope.json").read_text())
|
|
published = self.publish_scope(scope)
|
|
self.wait_bundle_commits(deployment_bundle_expectations(scope, published), timeout=120)
|
|
manifest = self.load()
|
|
manifest["tls"]["rotation"] = json.loads(state_path.read_text())["phase"]
|
|
manifest["tls"]["ca_file"] = str(security / "ca.pem")
|
|
self.save(manifest)
|
|
return {"action": action, "phase": manifest["tls"]["rotation"]}
|
|
|
|
def restore_security(self):
|
|
"""Restore the original local CA/certificates while keeping bundle generations monotonic."""
|
|
import shutil
|
|
security = self.folder / "security"
|
|
state_path = self.folder / "trust-state.json"
|
|
if not state_path.exists():
|
|
return {"restored": False}
|
|
original = security / "ca-original.pem"
|
|
if not original.is_file():
|
|
raise RigError("original local CA material is unavailable")
|
|
for node in NODES[2:]:
|
|
for kind in ("pem", "key"):
|
|
directory = security / "tls" / node
|
|
atomic_write_secret(directory / ("server." + kind), (directory / ("server-original." + kind)).read_text())
|
|
atomic_write_secret(security / "ca.pem", original.read_text())
|
|
atomic_write_secret(state_path, json.dumps({"phase": "restored", "roots": [str(original)]}))
|
|
self.compose("restart", *NODES[2:], timeout=120)
|
|
self.refresh_endpoints(NODES[2:])
|
|
scope = json.loads((self.folder / "seed" / "scope.json").read_text())
|
|
published = self.publish_scope(scope)
|
|
self.wait_bundle_commits(deployment_bundle_expectations(scope, published), timeout=120)
|
|
next_security = self.folder / "security-next"
|
|
if next_security.is_symlink():
|
|
raise RigError("staged security directory cannot be a symlink")
|
|
if next_security.exists():
|
|
shutil.rmtree(next_security)
|
|
state_path.unlink()
|
|
manifest = self.load()
|
|
manifest["tls"]["rotation"] = "restored"
|
|
manifest["tls"]["ca_file"] = str(security / "ca.pem")
|
|
self.save(manifest)
|
|
return {"restored": True}
|
|
|
|
@contextmanager
|
|
def retired_server_identity(self, node):
|
|
"""Present an old-CA server identity after actual consumers retired it."""
|
|
if node not in ("source-1", "source-2"):
|
|
raise RigError("retired identity experiment requires an owned SOURCE node")
|
|
state_path = self.folder / "trust-state.json"
|
|
if not state_path.is_file() or json.loads(state_path.read_text()).get("phase") != "retired":
|
|
raise RigError("old CA must be retired before the identity experiment")
|
|
directory = self.folder / "security" / "tls" / node
|
|
original = {}
|
|
for kind in ("pem", "key"):
|
|
old = directory / ("server-original." + kind)
|
|
if old.is_symlink() or not old.is_file():
|
|
raise RigError("restricted server identities are unavailable")
|
|
original[kind] = old.read_text()
|
|
with self._server_identity_material(node, original):
|
|
yield
|
|
|
|
@contextmanager
|
|
def rejected_server_identity(self, node, reason):
|
|
"""Serve a real invalid identity to the production caller trust policy."""
|
|
if node not in ("source-1", "source-2") or reason not in ("wrong-ca", "wrong-san"):
|
|
raise RigError("invalid owned TLS rejection experiment")
|
|
if reason == "wrong-ca":
|
|
import credentials
|
|
isolated = self.folder / "security-rejected"
|
|
if isolated.is_symlink(): raise RigError("rejected identity directory cannot be linked")
|
|
if not isolated.exists(): credentials.provision_tls(isolated, ("source-1", "source-2"))
|
|
directory = isolated / "tls" / node
|
|
else:
|
|
partner = "source-2" if node == "source-1" else "source-1"
|
|
directory = self.folder / "security" / "tls" / partner
|
|
material = {}
|
|
for kind in ("pem", "key"):
|
|
path = directory / ("server." + kind)
|
|
if path.is_symlink() or not path.is_file(): raise RigError("owned TLS test identity is unavailable")
|
|
material[kind] = path.read_text()
|
|
if reason == "wrong-san":
|
|
# The Host correctly checks its own certificate against AllowedHosts
|
|
# at startup. Admit the partner identity on that server only, while
|
|
# the actual caller remains pinned to this node's original URI.
|
|
live = self.folder / "security" / "tls" / node
|
|
saved = {kind: (live / ("server." + kind)).read_text() for kind in ("pem", "key")}
|
|
def restore():
|
|
for kind, content in saved.items():
|
|
atomic_write_secret(live / ("server." + kind), content)
|
|
try:
|
|
for kind, content in material.items():
|
|
atomic_write_secret(live / ("server." + kind), content)
|
|
with self._configuration_experiment("wrong-san-" + node, (node,),
|
|
{"DataConnections__AllowedHosts__0": partner}, before_restore=restore):
|
|
yield
|
|
finally:
|
|
restore()
|
|
return
|
|
with self._server_identity_material(node, material):
|
|
yield
|
|
|
|
def verify_test_tls_listener(self, node, reason):
|
|
"""Validate the presented test certificate independently of consumer trust.
|
|
|
|
This control proves that the same owned TLS listener is reachable while
|
|
the production consumer must reject its configured identity. It sends no
|
|
HTTP request and grants no trust material to that consumer.
|
|
"""
|
|
import hashlib
|
|
import socket
|
|
import ssl
|
|
if node not in ("source-1", "source-2") or reason not in ("wrong-ca", "wrong-san", "retired-ca"):
|
|
raise RigError("invalid owned TLS listener control")
|
|
security = self.folder / "security"
|
|
ca = (self.folder / "security-rejected" / "ca.pem") if reason == "wrong-ca" else (
|
|
security / "ca-original.pem" if reason == "retired-ca" else security / "ca.pem")
|
|
server_name = ("source-2" if node == "source-1" else "source-1") if reason == "wrong-san" else node
|
|
endpoint = self.load()["endpoints"][node + ".data"]
|
|
context = ssl.create_default_context(cafile=str(ca))
|
|
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
with socket.create_connection((endpoint["host"], endpoint["host_port"]), timeout=5) as transport:
|
|
with context.wrap_socket(transport, server_hostname=server_name) as channel:
|
|
actual = channel.getpeercert(binary_form=True)
|
|
expected = ssl.PEM_cert_to_DER_cert((security / "tls" / node / "server.pem").read_text())
|
|
if actual != expected: raise RigError("TLS control observed another server identity")
|
|
return {"server_name": server_name, "certificate_sha256": hashlib.sha256(actual).hexdigest(),
|
|
"tls_version": channel.version(), "listener_reachable": True}
|
|
|
|
@contextmanager
|
|
def _server_identity_material(self, node, material):
|
|
directory = self.folder / "security" / "tls" / node
|
|
current = {}
|
|
for kind in ("pem", "key"):
|
|
path = directory / ("server." + kind)
|
|
if path.is_symlink() or not path.is_file(): raise RigError("restricted server identity is unavailable")
|
|
current[kind] = path.read_text()
|
|
def apply(material):
|
|
self.inspect_resources()
|
|
for kind, content in material.items():
|
|
atomic_write_secret(directory / ("server." + kind), content)
|
|
self.compose("restart", node, timeout=90)
|
|
manifest = self.refresh_endpoints((node,))
|
|
wait_until(lambda: self.health(manifest), timeout=180, description="server identity experiment readiness")
|
|
try:
|
|
apply(material)
|
|
yield
|
|
finally:
|
|
apply(current)
|
|
|
|
def deploy(self, timeout=180, *, require_catalog=True):
|
|
_duration(timeout, "deployment operation timeout")
|
|
deadline = time.monotonic() + timeout
|
|
def remaining():
|
|
value = deadline - time.monotonic()
|
|
if value <= 0:
|
|
raise RigError("deployment operation deadline timeout")
|
|
return value
|
|
manifest = self.load()
|
|
if "fixture" not in manifest:
|
|
raise RigError("seed must complete before deploy")
|
|
primary = wait_active_endpoint({node: manifest["endpoints"][node + ".admin"]["url"] for node in NODES[:2]},
|
|
request=http_request, timeout=remaining(), require_ready=True)
|
|
scope = {}
|
|
def accepted(identity, revision):
|
|
scope.update(self.provision_deployment(identity, revision, timeout=remaining()))
|
|
# This inventory comes from the sealer's immutable artifact, not the
|
|
# status rows we are about to validate. Maintenance deliberately
|
|
# removes a node from expected apply acknowledgements.
|
|
required = scope.get("required_node_ids")
|
|
if not isinstance(required, list) or not required:
|
|
raise RigError("sealed artifact has no required-node inventory")
|
|
return required
|
|
outcome = deploy_and_wait(manifest["endpoints"][primary + ".admin"]["url"], self.environment["GRPC_DATA_DEPLOY_KEY"],
|
|
{node + ":4053" for node in NODES}, request=http_request, timeout=remaining(), on_accepted=accepted)
|
|
manifest["deployment"] = {"id": outcome["deploymentId"], "revision_hash": outcome["revisionHash"], "scope_version": scope["scope_version"], "nodes": outcome["nodes"], "required_node_ids": scope["required_node_ids"]}
|
|
manifest["deployment"]["bundle_commits"] = self.wait_bundle_commits(scope["bundle_expectations"], timeout=remaining())
|
|
if require_catalog:
|
|
wait_until(lambda: self.health(manifest, require_catalog=True, timeout=remaining()), timeout=remaining(), description="deployed catalog and OPC UA namespace identity")
|
|
manifest["resolved_nodes"] = json.loads((self.folder / "seed" / "resolved.json").read_text())
|
|
remaining()
|
|
manifest["state"] = "ready"
|
|
self.capture(manifest)
|
|
return manifest
|
|
|
|
def status(self):
|
|
manifest = self.load()
|
|
try:
|
|
manifest["healthy"] = self.health(manifest, require_catalog=manifest.get("state") == "ready")
|
|
except (OSError, ValueError, RigError):
|
|
manifest["healthy"] = False
|
|
self.capture(manifest)
|
|
return manifest
|
|
|
|
def down(self):
|
|
if self.path.exists():
|
|
manifest = self.load()
|
|
# Refresh exact-ID inventory of the same run; labels are checked twice.
|
|
manifest["resources"] = self.inspect_resources()
|
|
else:
|
|
setup = json.loads((self.folder / "setup.json").read_text())
|
|
if setup != {"run_id": self.run_id, "docker_context": self.context["Name"], "project": self.project}:
|
|
raise RigError("interrupted setup journal ownership mismatch")
|
|
# cleanup_owned also validates endpoint/node schema; this placeholder
|
|
# is safety-only and cannot be reported as running or ready.
|
|
manifest = {"schema_version": 1, "run_id": self.run_id, "project": self.project, "labels": {RUN_LABEL: self.run_id, PROJECT_LABEL: self.project},
|
|
"services": list(SERVICES), "endpoints": {"journal": {"scheme": "tcp", "host": "127.0.0.1", "host_port": 1, "container_host": "sql", "container_port": 1433}},
|
|
"nodes": {"source-1": {"cluster_id": "SOURCE", "application_uri": "urn:OtOpcUa:grpc-data:source-1"}}, "resources": self.inspect_resources()}
|
|
order = {"container": 0, "network": 1, "volume": 2, "image": 3}
|
|
manifest["resources"].sort(key=lambda row: order[row["kind"]])
|
|
def remove(kind, identity):
|
|
run_command([*self.docker, kind, "rm", *(["--force"] if kind == "container" else []), identity])
|
|
cleanup_owned(manifest, self.inspect_resources(), remove=remove)
|
|
manifest["state"] = "down"
|
|
manifest["resources"] = []
|
|
self.save(manifest)
|
|
return manifest
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description="Standalone owned local gRPC data integration rig")
|
|
parser.add_argument("action", choices=("preflight", "up", "seed", "deploy", "status", "down"))
|
|
parser.add_argument("--run-id")
|
|
parser.add_argument("--timeout", type=float, default=None)
|
|
parser.add_argument("--source-revision", default=None,
|
|
help="up only (#921): build the SOURCE pair from this pinned post-X0, pre-H2 commit (a v1 origin), e.g. 0c86edc1")
|
|
parser.add_argument("--conditions", action="store_true", help="up only: add the A2a conditions overlay (AlarmSubscribe exports + one scripted alarm)")
|
|
parser.add_argument("--history", action="store_true", help="up only: add the H2 history overlay (SOURCE historian + history seed profile)")
|
|
parser.add_argument("--history-backend", choices=HISTORY_BACKENDS, default=None,
|
|
help="up --history only: the SOURCE historian backend (sqlserver = the run's SQL container, default; questdb = a run-owned QuestDB)")
|
|
arguments = parser.parse_args(argv)
|
|
try:
|
|
if arguments.action == "preflight":
|
|
context = docker_context()
|
|
environment = dict(os.environ)
|
|
for name in re.findall(r"\$\{([A-Z][A-Z0-9_]*)", (HERE / "compose.yml").read_text()):
|
|
environment[name] = "preflight"
|
|
environment.update({"GRPC_DATA_PROJECT": "grpc-data-preflight", "GRPC_DATA_RUN_ID": "preflight",
|
|
"GRPC_DATA_UID": "0", "GRPC_DATA_GID": "0", "GRPC_DATA_CERT_DIR": "/tmp/grpc-data-preflight/tls",
|
|
"GRPC_DATA_CREDENTIAL_DIR": "/tmp/grpc-data-preflight/credentials", "GRPC_DATA_OUTPUT_DIR": "/tmp/grpc-data-preflight/output",
|
|
"GRPC_DATA_PROBE_DIR": "/tmp/grpc-data-preflight/probe"})
|
|
resolved = json.loads(run_command(["docker", "--context", context["Name"], "compose", "--file", str(HERE / "compose.yml"), "config", "--format", "json"], environment=environment))
|
|
validate_fixture_endpoints(resolved, local_services=SERVICES)
|
|
print(json.dumps({"local_docker": True, "resolved_fixture_local": True, "context": context["Name"]}))
|
|
return 0
|
|
rig = LocalRig(arguments.run_id)
|
|
action = getattr(rig, arguments.action)
|
|
options = {"timeout": arguments.timeout} if arguments.timeout is not None and arguments.action in {"up", "deploy"} else {}
|
|
if arguments.history:
|
|
if arguments.action != "up":
|
|
raise RigError("--history applies to up only; the run remembers it")
|
|
options["history"] = True
|
|
if arguments.history_backend is not None:
|
|
options["history_backend"] = arguments.history_backend
|
|
elif arguments.history_backend is not None:
|
|
raise RigError("--history-backend needs up --history")
|
|
if arguments.conditions:
|
|
if arguments.action != "up":
|
|
raise RigError("--conditions applies to up only; the run remembers it")
|
|
options["conditions"] = True
|
|
if arguments.source_revision is not None:
|
|
if arguments.action != "up":
|
|
raise RigError("--source-revision applies to up only; the run remembers it")
|
|
options["source_revision"] = arguments.source_revision
|
|
result = action(**options)
|
|
print(json.dumps({"run_id": result["run_id"], "state": result.get("state"), "manifest": str(rig.path), "healthy": result.get("healthy")}))
|
|
return 0
|
|
except (RigError, ValueError, OSError, KeyError) as error:
|
|
# Only our own fixed RigError messages are public. Parser/system errors
|
|
# can include paths or env supplied secrets, so withhold their contents.
|
|
message = str(error) if isinstance(error, RigError) else "fixture operation failed; inspect restricted run files"
|
|
print("grpc-data rig: " + message, file=__import__("sys").stderr)
|
|
return 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|