282 lines
15 KiB
Python
282 lines
15 KiB
Python
"""Safety units only: no Docker, HTTP, DNS, socket, or production fixture calls."""
|
|
from copy import deepcopy
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
import rig
|
|
|
|
|
|
RUN = "unit-fixture-001"
|
|
LABELS = {"otopcua.grpc-data.run": RUN,
|
|
"com.docker.compose.project": f"grpc-data-{RUN}"}
|
|
|
|
|
|
def manifest():
|
|
return {
|
|
"schema_version": 1, "run_id": RUN, "project": f"grpc-data-{RUN}",
|
|
"labels": dict(LABELS),
|
|
"services": ["sql", "device", "control-1", "control-2", "source-1", "source-2",
|
|
"consumer-1", "consumer-2"],
|
|
"endpoints": {
|
|
"admin": {"scheme": "http", "host": "127.0.0.1", "host_port": 52111,
|
|
"container_host": "control-1", "container_port": 9000},
|
|
"source-1": {"scheme": "https", "host": "127.0.0.1", "host_port": 52112,
|
|
"container_host": "source-1", "container_port": 4057}},
|
|
"nodes": {"source-1": {"cluster_id": "SOURCE", "application_uri": "urn:unit:source-1"}},
|
|
"resources": [{"kind": "container", "id": "unit-container", "labels": dict(LABELS)}],
|
|
}
|
|
|
|
|
|
class LocalDockerSafetyTests(unittest.TestCase):
|
|
def test_accepts_only_local_unix_and_npipe_transports(self):
|
|
for endpoint in ("unix:///var/run/docker.sock", "unix:///Users/unit/.docker/run/docker.sock",
|
|
"npipe:////./pipe/docker_engine"):
|
|
with self.subTest(endpoint=endpoint):
|
|
rig.validate_local_docker(endpoint)
|
|
|
|
def test_rejects_remote_transports_even_on_loopback(self):
|
|
for endpoint in ("ssh://unit@localhost", "tcp://127.0.0.1:2375", "tcp://10.100.0.35:2376",
|
|
"http://localhost:2375", "unix://other-host/var/run/docker.sock", ""):
|
|
with self.subTest(endpoint=endpoint), self.assertRaises(rig.RigError):
|
|
rig.validate_local_docker(endpoint)
|
|
|
|
def test_context_resolution_cannot_hide_remote_endpoint(self):
|
|
with self.assertRaises(rig.RigError):
|
|
rig.validate_docker_context({"Name": "local-looking", "Endpoints": {
|
|
"docker": {"Host": "ssh://unit@shared-host"}}}, environment={})
|
|
|
|
def test_remote_environment_override_rejected_even_with_local_context(self):
|
|
context = {"Name": "desktop-linux", "Endpoints": {"docker": {"Host": "unix:///tmp/docker.sock"}}}
|
|
for environment in ({"DOCKER_HOST": "tcp://localhost:2375"},
|
|
{"DOCKER_CONTEXT": "other-context"}):
|
|
with self.subTest(environment=environment), self.assertRaises(rig.RigError):
|
|
rig.validate_docker_context(context, environment=environment)
|
|
|
|
def test_local_named_context_and_matching_override_allowed(self):
|
|
context = {"Name": "desktop-linux", "Endpoints": {"docker": {"Host": "unix:///tmp/docker.sock"}}}
|
|
rig.validate_docker_context(context, environment={"DOCKER_CONTEXT": "desktop-linux"})
|
|
|
|
def test_resolved_fixture_endpoints_allow_only_loopback_and_declared_services(self):
|
|
document = {"services": {"source-1": {"environment": {
|
|
"ConnectionStrings__ConfigDb": "Server=sql,1433;Database=fixture;Password=secret",
|
|
"Mesh__Endpoint": "http://control-1:4055", "Device__Host": "device",
|
|
"Security__Ldap__Server": "127.0.0.1"}}}}
|
|
rig.validate_fixture_endpoints(document, local_services=set(manifest()["services"]))
|
|
|
|
def test_shared_endpoints_rejected_in_urls_sql_and_plain_host_options(self):
|
|
for value in ({"url": "https://10.100.0.35:4057"},
|
|
{"ConnectionStrings__ConfigDb": "Server=shared-db,1433;Database=x"},
|
|
{"ConnectionStrings__FixturePg": "Host=10.100.0.35;Port=15432"},
|
|
{"Oracle": "Data Source=10.100.0.35:11521/FREEPDB1"},
|
|
{"Security__Ldap__Server": "shared-directory"},
|
|
{"Device__Host": "host.docker.internal"},
|
|
{"url": "http://[::ffff:10.100.0.35]:9000"},
|
|
{"url": "http://${SHARED_HOST}:9000"}):
|
|
with self.subTest(value=value), self.assertRaises(rig.RigError):
|
|
rig.validate_fixture_endpoints(value, local_services=set(manifest()["services"]))
|
|
|
|
|
|
class ManifestOwnershipTests(unittest.TestCase):
|
|
def test_valid_manifest_accepts_dynamic_nondefault_loopback_ports(self):
|
|
rig.validate_manifest(manifest(), expected_run_id=RUN)
|
|
|
|
def test_unknown_version_wrong_run_and_unsafe_project_rejected(self):
|
|
for key, value in (("schema_version", 2), ("run_id", "../other"), ("project", "docker-dev")):
|
|
candidate = manifest()
|
|
candidate[key] = value
|
|
with self.subTest(key=key), self.assertRaises(rig.RigError):
|
|
rig.validate_manifest(candidate, expected_run_id=RUN)
|
|
|
|
def test_public_shared_duplicate_invalid_and_boolean_ports_rejected(self):
|
|
for key, value in (("host", "0.0.0.0"), ("host", "10.100.0.35"), ("host_port", 52112),
|
|
("host_port", 0), ("host_port", True), ("container_port", 65536),
|
|
("container_host", "shared-host")):
|
|
candidate = manifest()
|
|
candidate["endpoints"]["admin"][key] = value
|
|
with self.subTest(key=key, value=value), self.assertRaises(rig.RigError):
|
|
rig.validate_manifest(candidate)
|
|
|
|
def test_missing_endpoint_node_identity_or_exact_ownership_fails(self):
|
|
for mutate in (lambda m: m.update(endpoints={}), lambda m: m["nodes"]["source-1"].pop("cluster_id"),
|
|
lambda m: m["labels"].pop("otopcua.grpc-data.run"),
|
|
lambda m: m["resources"][0]["labels"].update({"otopcua.grpc-data.run": "other"})):
|
|
candidate = manifest()
|
|
mutate(candidate)
|
|
with self.subTest(candidate=candidate), self.assertRaises(rig.RigError):
|
|
rig.validate_manifest(candidate)
|
|
|
|
def test_cleanup_removes_only_recorded_ids_with_matching_run_and_project(self):
|
|
candidate = manifest()
|
|
observed = deepcopy(candidate["resources"])
|
|
observed += [{"kind": "container", "id": "same-labels-unrecorded", "labels": dict(LABELS)},
|
|
{"kind": "volume", "id": "developer-data", "labels": {}},
|
|
{"kind": "container", "id": "another-run", "labels": {}}]
|
|
removed = []
|
|
rig.cleanup_owned(candidate, observed, remove=lambda kind, resource_id: removed.append((kind, resource_id)))
|
|
self.assertEqual(removed, [("container", "unit-container")])
|
|
|
|
def test_cleanup_checks_all_ownership_before_first_deletion(self):
|
|
candidate = manifest()
|
|
candidate["resources"].append({"kind": "volume", "id": "unit-volume", "labels": dict(LABELS)})
|
|
observed = deepcopy(candidate["resources"])
|
|
observed[1]["labels"]["com.docker.compose.project"] = "docker-dev"
|
|
removed = []
|
|
with self.assertRaises(rig.RigError):
|
|
rig.cleanup_owned(candidate, observed, remove=lambda *args: removed.append(args))
|
|
self.assertEqual(removed, [])
|
|
|
|
def test_missing_resource_is_idempotent_but_duplicate_observations_fail(self):
|
|
removed = []
|
|
rig.cleanup_owned(manifest(), [], remove=lambda *args: removed.append(args))
|
|
self.assertEqual(removed, [])
|
|
with self.assertRaises(rig.RigError):
|
|
rig.cleanup_owned(manifest(), manifest()["resources"] * 2,
|
|
remove=lambda *args: removed.append(args))
|
|
self.assertEqual(removed, [])
|
|
|
|
|
|
class RestrictedSecretTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.temp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.temp.cleanup)
|
|
self.path = Path(self.temp.name) / "credential.key"
|
|
|
|
def test_secret_is_restricted_before_atomic_publication(self):
|
|
seen = []
|
|
def publish(source, target):
|
|
seen.append((Path(source).read_text(), stat.S_IMODE(os.stat(source).st_mode)))
|
|
self.assertFalse(self.path.exists())
|
|
os.replace(source, target)
|
|
rig.atomic_write_secret(self.path, "unit-secret", replace=publish)
|
|
self.assertEqual(seen, [("unit-secret", 0o600)])
|
|
self.assertEqual(self.path.read_text(), "unit-secret")
|
|
self.assertEqual(stat.S_IMODE(self.path.stat().st_mode), 0o600)
|
|
|
|
def test_failed_publication_keeps_old_secret_and_removes_temporary_file(self):
|
|
self.path.write_text("old-secret")
|
|
def interrupted(*args):
|
|
raise OSError("interrupted")
|
|
with self.assertRaises(OSError):
|
|
rig.atomic_write_secret(self.path, "new-secret", replace=interrupted)
|
|
self.assertEqual(self.path.read_text(), "old-secret")
|
|
self.assertEqual(list(self.path.parent.iterdir()), [self.path])
|
|
|
|
def test_symlink_target_is_rejected_without_touching_destination(self):
|
|
target = self.path.parent / "outside"
|
|
target.write_text("untouched")
|
|
self.path.symlink_to(target)
|
|
with self.assertRaises(rig.RigError):
|
|
rig.atomic_write_secret(self.path, "new-secret")
|
|
self.assertEqual(target.read_text(), "untouched")
|
|
|
|
|
|
class DeploymentPollingTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.calls = []
|
|
self.now = 0.0
|
|
self.responses = []
|
|
self.base = "http://127.0.0.1:52111"
|
|
self.deployment_id = "45b839a2-dc92-4f63-ad50-14eb9209e5a1"
|
|
self.location = f"/api/deployments/{self.deployment_id}"
|
|
|
|
def request(self, method, url, *, headers, json_body, timeout):
|
|
self.calls.append((method, url, headers, json_body, timeout))
|
|
self.assertGreater(timeout, 0)
|
|
return self.responses.pop(0)
|
|
|
|
def sleep(self, seconds):
|
|
self.now += seconds
|
|
|
|
def status(self, state="Sealed", nodes=None):
|
|
return {"deploymentId": self.deployment_id, "revisionHash": "unit-revision", "status": state,
|
|
"failureReason": None, "nodes": nodes if nodes is not None else [
|
|
{"nodeId": node, "status": "Applied", "appliedAtUtc": "2026-11-16T00:00:00Z", "failureReason": None}
|
|
for node in ("source-1", "source-2")]}
|
|
|
|
def invoke(self, **kwargs):
|
|
return rig.deploy_and_wait(self.base, "unit-deploy-key", {"source-1", "source-2"},
|
|
request=self.request, clock=lambda: self.now, sleep=self.sleep,
|
|
timeout=3, poll_interval=1, **kwargs)
|
|
|
|
def accepted(self):
|
|
return (202, {"Location": self.location}, {"outcome": "Accepted", "deploymentId": self.deployment_id,
|
|
"revisionHash": "unit-revision"})
|
|
|
|
def test_posts_created_by_only_once_then_polls_location_and_all_nodes(self):
|
|
self.responses = [self.accepted(), (200, {}, self.status("AwaitingApplyAcks")),
|
|
(200, {}, self.status())]
|
|
result = self.invoke()
|
|
self.assertEqual(result["revisionHash"], "unit-revision")
|
|
self.assertEqual([call[0] for call in self.calls], ["POST", "GET", "GET"])
|
|
self.assertEqual(self.calls[0][1], self.base + "/api/deployments")
|
|
self.assertEqual(self.calls[0][3], {"createdBy": "grpc-data-local-gate"})
|
|
self.assertEqual(self.calls[1][1], self.base + self.location)
|
|
self.assertTrue(all(call[2]["X-Api-Key"] == "unit-deploy-key" for call in self.calls))
|
|
|
|
def test_bodyless_trigger_supported_without_artifact_upload(self):
|
|
self.responses = [self.accepted(), (200, {}, self.status())]
|
|
self.invoke(created_by=None)
|
|
self.assertIsNone(self.calls[0][3])
|
|
|
|
def test_no_changes_still_polls_existing_deployment_for_apply_evidence(self):
|
|
self.responses = [(200, {}, {"outcome": "NoChanges", "deploymentId": self.deployment_id,
|
|
"revisionHash": "unit-revision"}), (200, {}, self.status())]
|
|
self.invoke()
|
|
self.assertEqual([call[0] for call in self.calls], ["POST", "GET"])
|
|
|
|
def test_no_changes_without_deployment_and_inflight_are_explicit_failures(self):
|
|
for response in ((200, {}, {"outcome": "NoChanges", "deploymentId": None, "revisionHash": "unit-revision"}),
|
|
(409, {}, {"outcome": "AnotherDeploymentInFlight"})):
|
|
self.responses = [response]
|
|
self.calls.clear()
|
|
with self.subTest(response=response), self.assertRaises(rig.RigError):
|
|
self.invoke()
|
|
self.assertEqual(len(self.calls), 1)
|
|
|
|
def test_missing_unexpected_duplicate_failed_and_degraded_nodes_fail(self):
|
|
base_nodes = self.status()["nodes"]
|
|
variants = [base_nodes[:1], base_nodes + [dict(base_nodes[0], nodeId="unexpected")],
|
|
base_nodes + [deepcopy(base_nodes[0])],
|
|
[dict(base_nodes[0], status="Failed"), base_nodes[1]],
|
|
[dict(base_nodes[0], failureReason="Applied degraded: unavailable"), base_nodes[1]],
|
|
[dict(base_nodes[0], appliedAtUtc=None), base_nodes[1]]]
|
|
for nodes in variants:
|
|
self.responses = [self.accepted(), (200, {}, self.status(nodes=nodes))]
|
|
with self.subTest(nodes=nodes), self.assertRaises(rig.RigError):
|
|
self.invoke()
|
|
|
|
def test_deployment_revision_identity_terminal_state_and_remote_location_fail(self):
|
|
for key, value in (("revisionHash", "wrong"), ("deploymentId", "another"),
|
|
("status", "PartiallyFailed"), ("status", "Mystery")):
|
|
status_body = self.status()
|
|
status_body[key] = value
|
|
self.responses = [self.accepted(), (200, {}, status_body)]
|
|
with self.subTest(key=key), self.assertRaises(rig.RigError):
|
|
self.invoke()
|
|
response = self.accepted()
|
|
self.responses = [(response[0], {"Location": "https://shared-host/api/deployments/other"}, response[2])]
|
|
self.calls.clear()
|
|
with self.assertRaises(rig.RigError):
|
|
self.invoke()
|
|
self.assertEqual(len(self.calls), 1)
|
|
|
|
def test_polling_deadline_is_bounded_and_never_reposts(self):
|
|
self.responses = [self.accepted()] + [(200, {}, self.status("AwaitingApplyAcks"))] * 10
|
|
with self.assertRaisesRegex(rig.RigError, "timeout|deadline"):
|
|
self.invoke()
|
|
self.assertLessEqual(self.now, 3)
|
|
self.assertEqual(sum(call[0] == "POST" for call in self.calls), 1)
|
|
|
|
def test_unwired_production_actions_fail_clearly_without_side_effects(self):
|
|
for action in ("up", "seed"):
|
|
with self.subTest(action=action), patch("subprocess.Popen") as popen:
|
|
with self.assertRaisesRegex(rig.RigError, "prerequisite|not configured|not wired"):
|
|
rig.require_production_prerequisites(action, {})
|
|
popen.assert_not_called()
|