Files
FinalToken/tools/proxmox/test_update.py
T
Florian Schmidt 7b70c7a0fa
agent-review agent review: fail
tools: update inside LXC and use the existing proxy
Keep the Proxmox host responsible only for container creation. Serve the private backend on port 5187 behind the operator's HTTPS proxy and install a self-updating in-container command. Preserve existing identity and history while migrating the old installer-owned proxy with listener rollback.

Refs #21
2026-11-15 12:49:53 +01:00

140 lines
7.0 KiB
Python

"""In-container updater tests: real local Git; no Proxmox, package or service mutations."""
import contextlib
import io
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))
import lxc_update as updater
class ContainerUpdateTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="finaltoken-ct-update-test-")
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.source, self.etc, self.result = self.root / "repo", self.root / "etc", self.root / "result.json"
self.source.mkdir(); self.etc.mkdir()
self.env = dict(os.environ, GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1")
self.git("init", "--initial-branch=master")
for name in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE", "tools/lxc_update.py"):
path = self.source / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("synthetic source fixture\n")
for project in ("FinalToken.Core", "FinalToken.Fleet", "FinalToken.Web", "FinalToken.Worker"):
path = self.source / "src" / project
path.mkdir(parents=True)
(path / (project + ".csproj")).write_text("<Project/>\n")
(self.source / "tools/proxmox").mkdir()
shutil.copy2(HERE / "source_bundle.py", self.source / "tools/proxmox/source_bundle.py")
shutil.copy2(HERE.parent / "source_policy.py", self.source / "tools/source_policy.py")
self.publish("v1")
self.marker = {"installer": "finaltoken-proxmox-v1", "ctid": 201, "role": "server"}
(self.etc / "install.json").write_text(json.dumps(self.marker))
(self.etc / "history.json").write_bytes(b"synthetic retained history")
self.commands = []
real_run = updater.run
def run(command, **kwargs):
self.commands.append(list(map(str, command)))
if command[0] in ("apt-get", "env"):
return subprocess.CompletedProcess(command, 0)
self.assertEqual("git", command[0], "Updater must not invoke Proxmox host commands")
return real_run(command, **kwargs)
self.stack = contextlib.ExitStack()
self.addCleanup(self.stack.close)
self.stack.enter_context(patch.object(updater, "ETC", self.etc))
self.stack.enter_context(patch.object(updater, "REPOSITORY", str(self.source)))
self.stack.enter_context(patch.object(updater.sys, "platform", "linux"))
self.stack.enter_context(patch.object(updater.os, "geteuid", return_value=0, create=True))
self.stack.enter_context(patch.object(updater, "update_lock", side_effect=contextlib.nullcontext))
self.stack.enter_context(patch.object(updater, "run", side_effect=run))
def git(self, *arguments):
return subprocess.run(["git", "-c", "user.name=Fixture", "-c", "[email protected]",
"-c", "commit.gpgsign=false", "-C", str(self.source), *arguments], env=self.env,
text=True, capture_output=True, check=True)
def publish(self, version, failure=False):
code = "import hashlib, json, tarfile\nfrom pathlib import Path\n"
code += "def provision(manifest, archive):\n"
code += " assert hashlib.sha256(archive.read_bytes()).hexdigest() == manifest['sourceSha256']\n"
if failure:
code += " raise ValueError('synthetic build failure')\n"
else:
code += " with tarfile.open(archive) as stream: names = stream.getnames()\n"
code += f" Path({str(self.result)!r}).write_text(json.dumps(dict(version={version!r}, manifest=manifest, files=names)))\n"
(self.source / "tools/proxmox/guest.py").write_text(code)
self.git("add", ".")
self.git("commit", "-m", "Synthetic " + version)
def update(self, *arguments):
with contextlib.redirect_stdout(io.StringIO()):
return updater.main(list(arguments))
def test_updates_here_using_fresh_source_and_current_container_identity(self):
self.assertEqual(0, self.update())
self.assertEqual("v1", json.loads(self.result.read_text())["version"])
self.publish("v2")
self.assertEqual(0, self.update())
result = json.loads(self.result.read_text())
self.assertEqual("v2", result["version"])
self.assertEqual(201, result["manifest"]["ctid"])
self.assertEqual("update", result["manifest"]["action"])
self.assertIn("tools/lxc_update.py", result["files"])
self.assertEqual(b"synthetic retained history", (self.etc / "history.json").read_bytes())
self.assertEqual(self.marker, json.loads((self.etc / "install.json").read_text()))
def test_dry_run_does_not_fetch_install_packages_or_acquire_lock(self):
with patch.object(updater, "update_lock") as lock:
self.assertEqual(0, self.update("--dry-run"))
lock.assert_not_called()
self.assertEqual([], self.commands)
self.assertFalse(self.result.exists())
def test_non_root_foreign_or_missing_container_never_starts_update(self):
with patch.object(updater.os, "geteuid", return_value=1000), self.assertRaises(ValueError):
self.update()
(self.etc / "install.json").write_text('{"installer":"foreign"}')
with self.assertRaises(ValueError):
self.update()
(self.etc / "install.json").unlink()
with self.assertRaises(ValueError):
self.update()
self.assertEqual([], self.commands)
def test_busy_update_does_not_fetch(self):
with patch.object(updater, "update_lock", side_effect=BlockingIOError), self.assertRaises(BlockingIOError):
self.update()
self.assertEqual([], self.commands)
def test_download_failure_keeps_container_state(self):
with patch.object(updater, "REPOSITORY", str(self.root / "missing")), self.assertRaises(subprocess.CalledProcessError):
self.update()
self.assertFalse(self.result.exists())
self.assertEqual(b"synthetic retained history", (self.etc / "history.json").read_bytes())
def test_build_failure_is_not_reported_as_success_and_preserves_state(self):
self.publish("failed", failure=True)
with self.assertRaises(ValueError):
self.update()
self.assertFalse(self.result.exists())
self.assertEqual(self.marker, json.loads((self.etc / "install.json").read_text()))
def test_git_bootstrap_installs_only_inside_the_validated_container(self):
with patch.object(updater.shutil, "which", return_value=None):
self.assertEqual(0, self.update())
self.assertEqual(["apt-get", "update"], self.commands[0])
self.assertEqual(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "git", "ca-certificates"], self.commands[1])
if __name__ == "__main__":
unittest.main()