250 lines
16 KiB
Python
250 lines
16 KiB
Python
import copy
|
|
from contextlib import ExitStack, redirect_stdout
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
import subprocess
|
|
import tempfile
|
|
from types import SimpleNamespace
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
import build_actions_artifact
|
|
from test_bootstrap import RUNNER
|
|
|
|
|
|
class ActionsEnableTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.temp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.temp.cleanup)
|
|
self.root = Path(self.temp.name).resolve()
|
|
self.config = self.root / "instance/config/app.ini"
|
|
self.config.parent.mkdir(parents=True)
|
|
self.original = b"APP_NAME = Gitea\n[security]\nSECRET_KEY = fixture-keep-private\n[actions]\nENABLED = false\n[server]\nHTTP_PORT = 3000\n"
|
|
self.target = self.original.replace(b"ENABLED = false", b"ENABLED = true")
|
|
self.config.write_bytes(self.original)
|
|
self.config.chmod(0o640)
|
|
self.backup = self.root / "backup"
|
|
self.backup.mkdir()
|
|
self.metadata = self.config.stat()
|
|
self.stack = ExitStack()
|
|
self.addCleanup(self.stack.close)
|
|
for name, value in {"GITEA_ACTIONS_CONFIG": self.config,
|
|
"GITEA_ACTIONS_ROOT": self.root / "meta",
|
|
"RUNTIME_DIR": self.root / "runtime",
|
|
"GITEA_ACTIONS_BEFORE": hashlib.sha256(self.original).hexdigest(),
|
|
"GITEA_ACTIONS_AFTER": hashlib.sha256(self.target).hexdigest()}.items():
|
|
self.stack.enter_context(mock.patch.object(RUNNER, name, value))
|
|
self.info = {"Id": "verified-id", "Name": "/clean-gitea-20260820", "Image": "sha256:fixture",
|
|
"Config": {"Image": RUNNER.GITEA_ACTIONS_IMAGE,
|
|
"Cmd": ["web", "--config", "/etc/gitea/app.ini"],
|
|
"Env": ["HOME=/var/lib/gitea/git"],
|
|
"Labels": {"com.docker.compose.project": "clean-gitea", "com.docker.compose.service": "gitea"}},
|
|
"HostConfig": {"NetworkMode": "clean-gitea_clean_gitea", "PortBindings": {"3000/tcp": [{"HostIp": "172.22.0.222", "HostPort": "3000"}], "2222/tcp": [{"HostIp": "0.0.0.0", "HostPort": "4022"}]}},
|
|
"State": {"Running": True, "Health": {"Status": "healthy"}},
|
|
"Mounts": [{"Source": str(self.config), "Destination": "/etc/gitea/app.ini", "RW": False},
|
|
{"Source": str(self.config.parent.parent / "data"), "Destination": "/var/lib/gitea", "RW": True}],
|
|
"NetworkSettings": {"Networks": {"clean-gitea_clean_gitea": {"IPAddress": "172.22.27.2"}}}}
|
|
self.before = {"config": self.original, "metadata": self.metadata, "containerId": self.info["Id"],
|
|
"fingerprint": RUNNER.gitea_actions_fingerprint(self.info), "inventory": {"other": {"running": True}}}
|
|
|
|
def test_bundle_selects_one_service_and_only_data_descriptor(self):
|
|
patch = "gitea-actions-enable-v1-test-001"
|
|
artifact = self.root / "test.tgz"
|
|
artifact.write_bytes(build_actions_artifact.bundle(patch))
|
|
self.assertEqual(artifact.read_bytes(), build_actions_artifact.bundle(patch))
|
|
work = self.root / "work"
|
|
work.mkdir()
|
|
manifest, entries, payload = RUNNER.load_artifact(artifact, work)
|
|
self.assertEqual(manifest["component"], "gitea-actions-config")
|
|
self.assertEqual(entries, [RUNNER.GITEA_ACTIONS_ENTRY])
|
|
self.assertEqual(RUNNER.component_services(manifest["component"], entries), ("gitea",))
|
|
self.assertEqual(RUNNER.component_builds(manifest["component"], entries), ())
|
|
path = payload / entries[0]
|
|
value = json.loads(path.read_text())
|
|
value["service"] = "postgres"
|
|
path.write_text(json.dumps(value))
|
|
with self.assertRaisesRegex(RUNNER.DeployError, "descriptor mismatch"):
|
|
RUNNER.validate_gitea_actions_payload(payload, entries, patch)
|
|
for rel in ("app.ini", "secrets/token", "data/gitea.db", "compose.yaml"):
|
|
with self.subTest(rel=rel), self.assertRaises(RUNNER.DeployError):
|
|
RUNNER.allowed_payload_path(manifest["component"], rel)
|
|
|
|
def test_exact_boolean_change_and_unrelated_drift_rejection(self):
|
|
self.assertEqual(RUNNER.gitea_actions_transform(self.original), self.target)
|
|
with self.assertRaisesRegex(RUNNER.DeployError, "predecessor"):
|
|
RUNNER.gitea_actions_transform(self.original + b"# unrelated change\n")
|
|
with self.assertRaises(RUNNER.DeployError):
|
|
RUNNER.gitea_actions_transform(self.target)
|
|
|
|
def test_atomic_update_preserves_permissions_and_rejects_concurrent_edit(self):
|
|
RUNNER.gitea_actions_replace(RUNNER.GITEA_ACTIONS_BEFORE, self.target, self.metadata)
|
|
self.assertEqual(self.config.read_bytes(), self.target)
|
|
self.assertEqual(stat.S_IMODE(self.config.stat().st_mode), 0o640)
|
|
self.assertEqual(self.config.stat().st_uid, self.metadata.st_uid)
|
|
with self.assertRaisesRegex(RUNNER.DeployError, "changed before"):
|
|
RUNNER.gitea_actions_replace(RUNNER.GITEA_ACTIONS_BEFORE, self.target, self.metadata)
|
|
|
|
def test_runtime_rejects_wrong_identity_mounts_and_actions_env_override(self):
|
|
for field, value in (("Image", "other-image"), ("Cmd", ["other"]), ("Env", ["GITEA__actions__ENABLED=false"])):
|
|
info = copy.deepcopy(self.info)
|
|
info["Config"][field] = value
|
|
with mock.patch.object(RUNNER, "inspect_container", return_value=info):
|
|
with self.subTest(field=field), self.assertRaises(RUNNER.DeployError):
|
|
RUNNER.gitea_actions_container()
|
|
info = copy.deepcopy(self.info)
|
|
info["Mounts"][0]["RW"] = True
|
|
with mock.patch.object(RUNNER, "inspect_container", return_value=info):
|
|
with self.assertRaisesRegex(RUNNER.DeployError, "mounts"):
|
|
RUNNER.gitea_actions_container()
|
|
|
|
def test_config_links_are_rejected(self):
|
|
sibling = self.config.with_name('other.ini')
|
|
os.link(self.config, sibling)
|
|
with self.assertRaisesRegex(RUNNER.DeployError, "metadata"):
|
|
RUNNER.gitea_actions_read_config()
|
|
self.config.unlink()
|
|
self.config.symlink_to(sibling)
|
|
with self.assertRaises(OSError):
|
|
RUNNER.gitea_actions_read_config()
|
|
|
|
def test_preflight_binds_healthy_runtime_to_image_and_inactive_rpc(self):
|
|
sources = {"compose.yaml": "c21ef87833f87623f8352477d2b541d0a0f48769d8f9f79251d58033e90197ff",
|
|
"production.env": "9ebbf8638e035dddca25fd455b2ac4d4b6db306e1a6a4debd973b133fdeb5bb7"}
|
|
with mock.patch.object(RUNNER, "sha256_file", side_effect=lambda p:sources[p.name]), mock.patch.object(RUNNER, "inspect_container", return_value=self.info), mock.patch.object(RUNNER, "inspect_local_image", return_value=self.info["Image"]), mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}), (404,None)]), mock.patch.object(RUNNER, "gitea_ci_inventory", return_value={**self.before["inventory"],self.info["Id"]:{"running":True}}):
|
|
before = RUNNER.preflight_gitea_actions()
|
|
self.assertEqual(before["inventory"], self.before["inventory"])
|
|
self.assertEqual(before["config"], self.original)
|
|
self.assertEqual(before["fingerprint"], self.before["fingerprint"])
|
|
|
|
def test_preservation_acceptance_rejects_changed_container_configuration(self):
|
|
info = copy.deepcopy(self.info)
|
|
info["HostConfig"]["Memory"] = 123
|
|
with mock.patch.object(RUNNER, "gitea_actions_container", return_value=info), mock.patch.object(RUNNER.time, "monotonic", side_effect=[0,121]):
|
|
with self.assertRaisesRegex(RUNNER.DeployError, "runtime configuration drift"):
|
|
RUNNER.accept_gitea_actions(self.before)
|
|
|
|
def test_rpc_preflight_rejects_rest_only_instance(self):
|
|
with mock.patch.object(RUNNER, "gitea_actions_http", return_value=(404, None)):
|
|
with self.assertRaisesRegex(RUNNER.DeployError, "HTTP 404"):
|
|
RUNNER.require_gitea_actions_ping()
|
|
with mock.patch.object(RUNNER, "gitea_actions_http", return_value=(200, {"data": "Hello, nodedc-ci-probe!"})):
|
|
RUNNER.require_gitea_actions_ping()
|
|
with mock.patch.object(RUNNER, "GITEA_CI_ROOT", self.root / "empty-ci"), mock.patch.object(RUNNER, "gitea_ci_host_capabilities"), mock.patch.object(RUNNER, "require_gitea_actions_ping", side_effect=RUNNER.DeployError("HTTP 404")), mock.patch.object(RUNNER, "gitea_ci_container_ids") as containers:
|
|
with self.assertRaisesRegex(RUNNER.DeployError, "HTTP 404"):
|
|
RUNNER.preflight_gitea_ci(RUNNER.GITEA_CI_V4_ENTRIES)
|
|
containers.assert_not_called()
|
|
|
|
def test_apply_private_snapshot_and_failed_restart_can_restore_stopped_container(self):
|
|
with mock.patch.object(RUNNER.os, "chown"), mock.patch.object(RUNNER.os, "fchown"), mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info), mock.patch.object(RUNNER.subprocess, "run", side_effect=subprocess.CalledProcessError(1, ["docker", "restart"])):
|
|
with self.assertRaises(subprocess.CalledProcessError):
|
|
RUNNER.apply_gitea_actions(self.before, self.backup)
|
|
self.assertEqual(self.config.read_bytes(), self.target)
|
|
private = RUNNER.RUNTIME_DIR / "gitea-actions" / self.backup.name / "app.ini.before"
|
|
self.assertEqual(private.read_bytes(), self.original)
|
|
self.assertEqual(stat.S_IMODE(private.stat().st_mode), 0o600)
|
|
self.assertNotIn("fixture-keep-private", (self.backup / "gitea-actions-before.json").read_text())
|
|
stopped = copy.deepcopy(self.info)
|
|
stopped["State"]["Running"] = False
|
|
stopped["NetworkSettings"]["Networks"]["clean-gitea_clean_gitea"]["IPAddress"] = ""
|
|
with mock.patch.object(RUNNER, "inspect_container", return_value=stopped), mock.patch.object(RUNNER.subprocess, "run") as restart, mock.patch.object(RUNNER, "accept_gitea_actions") as accept, mock.patch.object(RUNNER, "restore_overlay_source"):
|
|
RUNNER.rollback_gitea_actions(self.root, self.backup, [RUNNER.GITEA_ACTIONS_ENTRY], "stamp", self.before, True)
|
|
restart.assert_called_once()
|
|
accept.assert_called_once_with(self.before, enabled=False)
|
|
self.assertEqual(self.config.read_bytes(), self.original)
|
|
|
|
def test_rollback_refuses_to_overwrite_unrelated_changes(self):
|
|
self.config.write_bytes(self.target + b"# concurrent change")
|
|
with mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info), mock.patch.object(RUNNER.subprocess, "run") as restart:
|
|
with self.assertRaisesRegex(RUNNER.DeployError, "unrelated config drift"):
|
|
RUNNER.rollback_gitea_actions(self.root, self.backup, [RUNNER.GITEA_ACTIONS_ENTRY], "stamp", self.before, True)
|
|
restart.assert_not_called()
|
|
|
|
def test_acceptance_proves_rpc_version_runtime_and_other_containers(self):
|
|
self.config.write_bytes(self.target)
|
|
with mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info), mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}), (200,{"data":"Hello, nodedc-ci-probe!"})]), mock.patch.object(RUNNER, "gitea_ci_inventory", return_value=self.before["inventory"]), redirect_stdout(io.StringIO()):
|
|
RUNNER.accept_gitea_actions(self.before)
|
|
|
|
def test_startup_diagnostics_never_save_raw_tokens_or_logs(self):
|
|
result = SimpleNamespace(stdout="runner registration token fixture-SECRET 404 not found", stderr="Authorization: another-secret")
|
|
with mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=["ci-container"]), mock.patch.object(RUNNER.subprocess, "run", return_value=result), redirect_stdout(io.StringIO()) as output:
|
|
RUNNER.capture_gitea_ci_diagnostics(self.backup)
|
|
data = (self.backup / "ci-startup-diagnostics.json").read_text()
|
|
for secret in ("fixture-SECRET", "another-secret", "Authorization"):
|
|
self.assertNotIn(secret, data + output.getvalue())
|
|
self.assertIn("actions-disabled-or-route", data)
|
|
|
|
def full_apply(self, fail_acceptance=False, version="v1"):
|
|
host = self.root / "host"
|
|
host.mkdir()
|
|
paths = {name: host / name.lower() for name in (
|
|
"INBOX", "APPLIED_DIR", "FAILED_DIR", "BACKUPS_DIR", "STATE_DIR", "TMP_DIR", "RUNTIME_DIR")}
|
|
for path in paths.values():
|
|
path.mkdir()
|
|
paths.update({"STATE_FILE": paths["STATE_DIR"] / "applied.jsonl",
|
|
"FAILED_STATE_FILE": paths["STATE_DIR"] / "failed.jsonl",
|
|
"LOCK_DIR": paths["STATE_DIR"] / "deploy.lock", "DOCKER": Path("/usr/bin/true")})
|
|
legacy = host / "legacy"
|
|
legacy.mkdir()
|
|
for name in ("compose.yaml", "production.env"):
|
|
(legacy / name).write_text("fixture")
|
|
root = host / "metadata"
|
|
registry = {**RUNNER.COMPONENTS["gitea-actions-config"], "payload_root": root,
|
|
"compose_root": legacy, "compose_files": (legacy / "compose.yaml",),
|
|
"compose_env_file": legacy / "production.env"}
|
|
artifact = paths["INBOX"] / "actions.tgz"
|
|
artifact.write_bytes(build_actions_artifact.bundle("gitea-actions-enable-" + version + "-full-test"))
|
|
if version == "v2":
|
|
(root / RUNNER.GITEA_ACTIONS_ENTRY).parent.mkdir(parents=True)
|
|
(root / RUNNER.GITEA_ACTIONS_ENTRY).write_bytes(b"preserved failed-attempt marker")
|
|
self.before.update({"fingerprint": RUNNER.gitea_actions_fingerprint_v2(self.info),
|
|
"fingerprintVersion": 2, "mutationStarted": False})
|
|
with ExitStack() as stack:
|
|
for name, value in paths.items():
|
|
stack.enter_context(mock.patch.object(RUNNER, name, value))
|
|
stack.enter_context(mock.patch.dict(RUNNER.COMPONENTS, {"gitea-actions-config": 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.os, "fchown"))
|
|
stack.enter_context(mock.patch.object(RUNNER, "preflight_gitea_actions", return_value=self.before))
|
|
stack.enter_context(mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info))
|
|
stack.enter_context(mock.patch.object(RUNNER.subprocess, "run"))
|
|
if fail_acceptance:
|
|
accept = stack.enter_context(mock.patch.object(RUNNER, "accept_gitea_actions", side_effect=[RUNNER.DeployError("synthetic RPC failure"), None]))
|
|
else:
|
|
stack.enter_context(mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}), (200,{"data":"Hello, nodedc-ci-probe!"})]))
|
|
stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_inventory", return_value=self.before["inventory"]))
|
|
with redirect_stdout(io.StringIO()):
|
|
if fail_acceptance:
|
|
with self.assertRaisesRegex(RUNNER.DeployError, "synthetic RPC"):
|
|
RUNNER.apply_artifact(artifact)
|
|
self.assertEqual(accept.call_count, 2)
|
|
else:
|
|
RUNNER.apply_artifact(artifact)
|
|
return paths, root
|
|
|
|
def test_full_apply_receipt_only_after_success_and_no_secrets_in_source_backup(self):
|
|
paths, root = self.full_apply()
|
|
row = json.loads(paths["STATE_FILE"].read_text())
|
|
self.assertEqual(row["status"], "ok")
|
|
self.assertEqual(self.config.read_bytes(), self.target)
|
|
self.assertTrue((root / RUNNER.GITEA_ACTIONS_ENTRY).is_file())
|
|
for file in (paths["BACKUPS_DIR"] / row["backup_id"]).iterdir():
|
|
if file.is_file():
|
|
self.assertNotIn(b"fixture-keep-private", file.read_bytes())
|
|
|
|
def test_full_failed_acceptance_restores_flag_and_descriptor_and_records_rollback(self):
|
|
paths, root = self.full_apply(fail_acceptance=True)
|
|
row = json.loads(paths["FAILED_STATE_FILE"].read_text())
|
|
self.assertEqual(row["rollback_status"], "ok:gitea-actions-config")
|
|
self.assertEqual(self.config.read_bytes(), self.original)
|
|
self.assertFalse((root / RUNNER.GITEA_ACTIONS_ENTRY).exists())
|
|
self.assertFalse(paths["STATE_FILE"].exists())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|