import copy from contextlib import ExitStack, redirect_stdout, redirect_stderr import io import importlib.machinery import importlib.util import json from pathlib import Path import tarfile import tempfile import unittest from unittest import mock import build_artifact SOURCE = Path(__file__).resolve().parent loader = importlib.machinery.SourceFileLoader("gitea_ci_runner_test", str(SOURCE.parent / "deploy-runner/nodedc-deploy")) spec = importlib.util.spec_from_loader(loader.name, loader) RUNNER = importlib.util.module_from_spec(spec) loader.exec_module(RUNNER) def container_info(): return { "Config": {"Image": RUNNER.GITEA_CI_IMAGE, "Labels": { "com.docker.compose.project": "nodedc-gitea-ci", "com.docker.compose.service": "build-runner", }}, "State": {"Running": True}, "HostConfig": { "PortBindings": {}, "NetworkMode": "nodedc-gitea-ci_default", "ReadonlyRootfs": True, "Memory": 512 * 1024 ** 2, "NanoCpus": 500000000, "PidsLimit": 128, "CapDrop": ["ALL"], "SecurityOpt": ["no-new-privileges:true"], }, "NetworkSettings": {"Ports": {}}, "Mounts": [{"Destination": dest, "Source": source, "RW": rw, "Type": "bind"} for dest, source, rw in [ ("/config/runner.yaml", str(RUNNER.GITEA_CI_ROOT / "runner.yaml"), False), ("/data", str(RUNNER.GITEA_CI_ROOT / "data"), True), ("/run/secrets/registration-token", str(RUNNER.GITEA_CI_ROOT / "secrets/registration-token"), False), ("/var/run/docker.sock", "/var/run/docker.sock", False), ]], } class BootstrapTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name).resolve() self.patch = "gitea-ci-bootstrap-v1-test-001" self.artifact = self.root / "bootstrap.tgz" self.artifact.write_bytes(build_artifact.bundle(self.patch)) self.extracted = self.root / "extracted" self.extracted.mkdir() def load(self): return RUNNER.load_artifact(self.artifact, self.extracted) def test_deterministic_data_bundle_accepted_by_canonical_runner(self): self.assertEqual(self.artifact.read_bytes(), build_artifact.bundle(self.patch)) manifest, entries, _ = self.load() self.assertEqual(manifest["component"], "gitea-ci") self.assertEqual(tuple(entries), RUNNER.GITEA_CI_ENTRIES) self.assertEqual(RUNNER.component_services("gitea-ci", entries), ("build-runner",)) self.assertEqual(RUNNER.component_builds("gitea-ci", entries), ()) self.assertTrue(RUNNER.component_compose_no_deps("gitea-ci", entries)) with tarfile.open(self.artifact) as archive: self.assertEqual(len(archive.getmembers()), 5) self.assertTrue(all(m.isfile() and m.mode == 0o644 for m in archive)) def test_changed_ports_or_privileges_in_source_are_rejected(self): _, entries, payload = self.load() compose = payload / RUNNER.GITEA_CI_ENTRIES[0] compose.write_text(compose.read_text() + ' ports: ["9999:9999"]\n') with self.assertRaisesRegex(RUNNER.DeployError, "immutable configuration"): RUNNER.validate_gitea_ci_payload(payload, entries, self.patch) def test_partial_update_and_production_activation_are_rejected(self): _, entries, payload = self.load() with self.assertRaisesRegex(RUNNER.DeployError, "entry set"): RUNNER.validate_gitea_ci_payload(payload, entries[:1], self.patch) descriptor_path = payload / RUNNER.GITEA_CI_ENTRIES[2] descriptor = json.loads(descriptor_path.read_text()) descriptor["productionDeployEnabled"] = True descriptor_path.write_text(json.dumps(descriptor)) with self.assertRaisesRegex(RUNNER.DeployError, "descriptor mismatch"): RUNNER.validate_gitea_ci_payload(payload, entries, self.patch) def test_credentials_hooks_and_extra_services_are_not_payload_paths(self): for path in ("secrets/token", "data/.runner", "install.sh", "other.yml", "controller.py"): with self.subTest(path=path), self.assertRaises(RUNNER.DeployError): RUNNER.allowed_payload_path("gitea-ci", path) def test_runtime_accepts_exact_isolated_daemon(self): RUNNER.accept_gitea_ci_container(container_info()) def test_runtime_rejects_port_privilege_unbounded_memory_or_wrong_service(self): for field, value in ( ("PortBindings", {"8080/tcp": [{"HostPort": "8080"}]}), ("PublishAllPorts", True), ("NetworkMode", "host"), ("Privileged", True), ("Memory", 0), ("NanoCpus", 0), ("PidsLimit", 0), ("CapAdd", ["SYS_ADMIN"]), ("CapDrop", []), ("SecurityOpt", []), ): info = container_info() info["HostConfig"][field] = value with self.subTest(field=field), self.assertRaises(RUNNER.DeployError): RUNNER.accept_gitea_ci_container(info) def test_runtime_rejects_production_volume_mount(self): info = container_info() info["Mounts"].append({"Destination": "/production", "Source": "/volume1/docker/nodedc-device-plane", "RW": True, "Type": "bind"}) with self.assertRaisesRegex(RUNNER.DeployError, "mount boundary"): RUNNER.accept_gitea_ci_container(info) def test_enrollment_must_be_private_and_is_not_logged_in_error(self): pending = self.root / "enrollment.json" pending.write_text(json.dumps({"repository": "SILVER/NODEDC_DEVICE_CORE", "token": "sensitive" * 6})) with mock.patch.object(RUNNER, "GITEA_CI_ENROLLMENT", pending): pending.chmod(0o644) with self.assertRaisesRegex(RUNNER.DeployError, "private regular"): RUNNER.read_gitea_ci_enrollment() pending.chmod(0o600) self.assertEqual(RUNNER.read_gitea_ci_enrollment(), "sensitive" * 6) pending.write_text('{"token":"sensitive", malformed') with self.assertRaises(RUNNER.DeployError) as error: RUNNER.read_gitea_ci_enrollment() self.assertNotIn("sensitive", str(error.exception)) def test_symlink_enrollment_rejected(self): actual = self.root / "actual" actual.write_text("secret") link = self.root / "link" link.symlink_to(actual) with mock.patch.object(RUNNER, "GITEA_CI_ENROLLMENT", link): with self.assertRaises(RUNNER.DeployError): RUNNER.read_gitea_ci_enrollment() def test_preflight_rejects_reusing_bootstrap_for_an_installed_release(self): (self.root / RUNNER.GITEA_CI_ENTRIES[0]).write_text("installed") with mock.patch.object(RUNNER, "GITEA_CI_ROOT", self.root): with self.assertRaisesRegex(RUNNER.DeployError, "versioned upgrade"): RUNNER.preflight_gitea_ci() def test_inventory_preserves_only_non_ci_container_identities(self): old = {"Image": "old", "State": {"Running": True, "StartedAt": "before"}, "Config": {"Labels": {}}} own = copy.deepcopy(old) own["Config"]["Labels"]["com.docker.compose.project"] = "nodedc-gitea-ci" with mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=["old", "own"]), mock.patch.object(RUNNER, "inspect_container", side_effect=[old, own]): self.assertEqual(RUNNER.gitea_ci_inventory(), {"old": {"image": "old", "startedAt": "before", "running": True}}) def test_rollback_removes_only_ci_service_and_restores_only_source(self): with mock.patch.object(RUNNER, "stop_and_remove_compose_services") as stop, mock.patch.object(RUNNER, "restore_overlay_source") as restore, mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=[]): RUNNER.rollback_gitea_ci(self.root, self.root / "backup", RUNNER.GITEA_CI_ENTRIES, "stamp", True) stop.assert_called_once_with("gitea-ci", ("build-runner",)) restore.assert_called_once_with(self.root, self.root / "backup", RUNNER.GITEA_CI_ENTRIES, "stamp") def apply_in_synthetic_host(self, fail_health=False, version="v1"): expected_entries = RUNNER.GITEA_CI_ENTRIES if version in ("v2", "v3", "v4"): expected_entries = getattr(RUNNER, "GITEA_CI_" + version.upper() + "_ENTRIES") self.artifact.write_bytes(build_artifact.bundle("gitea-ci-bootstrap-" + version + "-test-001")) host = self.root / "host" host.mkdir() names = {name: host / name.lower() for name in ( "INBOX", "APPLIED_DIR", "FAILED_DIR", "BACKUPS_DIR", "STATE_DIR", "TMP_DIR", "RUNTIME_DIR", )} for directory in names.values(): directory.mkdir() names.update({ "STATE_FILE": names["STATE_DIR"] / "applied.jsonl", "FAILED_STATE_FILE": names["STATE_DIR"] / "failed.jsonl", "LOCK_DIR": names["STATE_DIR"] / "deploy.lock", "DOCKER": Path("/usr/bin/true"), }) app = host / "gitea-ci" registry = {**RUNNER.COMPONENTS["gitea-ci"], "payload_root": app, "compose_root": app, "compose_files": (app / "docker-compose.gitea-ci.yml",)} candidate = names["INBOX"] / "candidate.tgz" candidate.write_bytes(self.artifact.read_bytes()) def start_runtime(*args): self.assertEqual(args, ("gitea-ci", list(expected_entries), ("build-runner",))) (app / "data").mkdir() (app / "data" / "registration-marker").write_text("preserve-on-rollback") with ExitStack() as stack: for name, value in names.items(): stack.enter_context(mock.patch.object(RUNNER, name, value)) stack.enter_context(mock.patch.dict(RUNNER.COMPONENTS, {"gitea-ci": registry})) stack.enter_context(mock.patch.object(RUNNER, "require_root")) stack.enter_context(mock.patch.object(RUNNER.os, "chown")) stack.enter_context(mock.patch.object(RUNNER, "preflight_gitea_ci", return_value={})) stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_inventory", return_value={})) stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=[])) stack.enter_context(mock.patch.object(RUNNER, "run_component_runtime", side_effect=start_runtime)) stop = stack.enter_context(mock.patch.object(RUNNER, "stop_and_remove_compose_services")) stack.enter_context(mock.patch.object(RUNNER, "accept_gitea_ci", side_effect=RUNNER.DeployError("synthetic health failure") if fail_health else None)) output = stack.enter_context(redirect_stdout(io.StringIO())) stack.enter_context(redirect_stderr(io.StringIO())) if fail_health: with self.assertRaisesRegex(RUNNER.DeployError, "synthetic health failure"): RUNNER.apply_artifact(candidate) stop.assert_called_once_with("gitea-ci", ("build-runner",)) else: RUNNER.apply_artifact(candidate) stop.assert_not_called() return names, app, candidate, output.getvalue() def test_apply_records_commit_independent_artifact_receipt_only_after_acceptance(self): paths, app, candidate, output = self.apply_in_synthetic_host() self.assertFalse(candidate.exists()) row = json.loads(paths["STATE_FILE"].read_text()) self.assertEqual(row["status"], "ok") self.assertEqual(row["component"], "gitea-ci") self.assertTrue((paths["APPLIED_DIR"] / candidate.name).is_file()) self.assertTrue((paths["BACKUPS_DIR"] / row["backup_id"] / "ci-runtime-before.json").is_file()) self.assertIn("deploy-ok", output) self.assertTrue((app / "runner.yaml").is_file()) def test_failed_health_restores_source_preserves_registration_and_archives_failure(self): paths, app, candidate, output = self.apply_in_synthetic_host(fail_health=True) self.assertFalse(paths["STATE_FILE"].exists()) row = json.loads(paths["FAILED_STATE_FILE"].read_text()) self.assertEqual(row["rollback_status"], "ok:gitea-ci-bootstrap") self.assertTrue((paths["FAILED_DIR"] / row["artifact"]).is_file()) self.assertFalse((app / "runner.yaml").exists()) self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback") self.assertNotIn("deploy-ok", output) def test_v2_apply_records_distinct_descriptor_and_receipt(self): paths, app, candidate, output = self.apply_in_synthetic_host(version="v2") self.assertTrue((app / "deployment/bootstrap-v2.json").is_file()) self.assertFalse((app / "deployment/bootstrap-v1.json").exists()) self.assertEqual(json.loads(paths["STATE_FILE"].read_text())["status"], "ok") self.assertIn("deploy-ok patch=gitea-ci-bootstrap-v2-test-001", output) def test_v2_failed_health_preserves_identity_and_rolls_back_source(self): paths, app, candidate, output = self.apply_in_synthetic_host(fail_health=True, version="v2") self.assertFalse((app / "deployment/bootstrap-v2.json").exists()) self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback") self.assertEqual(json.loads(paths["FAILED_STATE_FILE"].read_text())["rollback_status"], "ok:gitea-ci-bootstrap") def test_v3_apply_and_receipt(self): paths, app, candidate, output = self.apply_in_synthetic_host(version="v3") self.assertTrue((app / "deployment/bootstrap-v3.json").is_file()) self.assertEqual(json.loads(paths["STATE_FILE"].read_text())["status"], "ok") self.assertIn("deploy-ok patch=gitea-ci-bootstrap-v3-test-001", output) def test_v3_rollback_preserves_identity(self): paths, app, candidate, output = self.apply_in_synthetic_host(fail_health=True, version="v3") self.assertFalse((app / "deployment/bootstrap-v3.json").exists()) self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback") self.assertEqual(json.loads(paths["FAILED_STATE_FILE"].read_text())["rollback_status"], "ok:gitea-ci-bootstrap") def test_v4_apply_and_receipt(self): paths, app, candidate, output = self.apply_in_synthetic_host(version="v4") self.assertTrue((app / "deployment/bootstrap-v4.json").is_file()) self.assertEqual(json.loads(paths["STATE_FILE"].read_text())["status"], "ok") self.assertIn("deploy-ok patch=gitea-ci-bootstrap-v4-test-001", output) def test_v4_rollback_preserves_identity(self): paths, app, candidate, output = self.apply_in_synthetic_host(fail_health=True, version="v4") self.assertFalse((app / "deployment/bootstrap-v4.json").exists()) self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback") self.assertEqual(json.loads(paths["FAILED_STATE_FILE"].read_text())["rollback_status"], "ok:gitea-ci-bootstrap") if __name__ == "__main__": unittest.main()