Files
FinalToken/tools/proxmox/test_installer.py
T
Florian Schmidt b23b7289c7
agent-review agent review: fail
tools: add Proxmox installation and one-command updates
Create unprivileged server or worker LXCs and build native binaries inside the container. Refresh a clean published checkout before updates, preserve configuration and history, and roll back failed binary activation without resetting local source work.

Refs #19
2026-11-15 10:59:41 +01:00

391 lines
22 KiB
Python

"""Deterministic host/guest installer tests. No pct, apt, dotnet publish or service mutation."""
import contextlib
import hashlib
import importlib.util
import io
import json
import os
from pathlib import Path, PurePosixPath
import subprocess
import sys
import tarfile
import tempfile
import types
import unittest
from unittest.mock import patch, Mock
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import host
# pwd is a Linux-only module; filesystem/command tests also run on the Windows development host.
with patch.dict(sys.modules, {"pwd": types.SimpleNamespace(getpwnam=lambda _: types.SimpleNamespace(pw_gid=1000))} if os.name == "nt" else {}):
spec = importlib.util.spec_from_file_location("guest", HERE / "guest.py")
guest = importlib.util.module_from_spec(spec)
spec.loader.exec_module(guest)
def install_args(*extra):
args = host.parser().parse_args(["install", "--ctid", "201", "--storage", "local-lvm", "--domain", "usage.example.test", "--email", "[email protected]", *extra])
host.validate(args)
return args
class HostTests(unittest.TestCase):
def test_server_only_requires_no_provider_login_or_email(self):
args = host.parser().parse_args(["install", "--role", "server", "--ctid", "201",
"--storage", "local-lvm", "--domain", "usage.example.test"])
host.validate(args)
self.assertEqual("server", args.role)
self.assertIsNone(args.email)
def test_default_creates_unprivileged_client_and_dashboard(self):
args = install_args()
command = host.create_command(args, 201, "debian-13-standard_13.1-1_amd64.tar.zst")
self.assertEqual("both", args.role)
self.assertEqual("1", command[command.index("--unprivileged") + 1])
self.assertEqual("local-lvm:20", command[command.index("--rootfs") + 1])
self.assertIn("ip=dhcp", command[command.index("--net0") + 1])
self.assertNotIn("--features", command)
def test_static_network_and_vlan_are_separate_validated_values(self):
args = install_args("--ip", "192.0.2.20/24", "--gateway", "192.0.2.1", "--vlan", "10")
command = host.create_command(args, 201, "template")
self.assertIn("gw=192.0.2.1,tag=10", command[command.index("--net0") + 1])
def test_rejects_injection_and_unsafe_configuration(self):
for flags in (("--domain", "x.test;touch /tmp/no"), ("--machine-id", "x-201"),
("--bridge", "vmbr0,ip=evil"), ("--ip", "192.0.2.2/24"), ("--vlan", "4095"),
("--template", "../../template.tar.zst"), ("--memory", "512"), ("--providers", "claude,unknown")):
with self.subTest(flags=flags), self.assertRaises(ValueError):
install_args(*flags)
def test_worker_only_requires_https_and_enrollment_file(self):
with tempfile.TemporaryDirectory() as tmp:
key = Path(tmp) / "enrollment"
key.write_text("a" * 64)
args = install_args("--role", "worker", "--server-url", "https://usage.example.test", "--worker-key-file", str(key))
self.assertEqual("worker", args.role)
with self.assertRaises(ValueError):
install_args("--role", "worker", "--server-url", "http://usage.example.test", "--worker-key-file", str(key))
key.write_text("short")
with self.assertRaises(ValueError):
install_args("--role", "worker", "--server-url", "https://usage.example.test", "--worker-key-file", str(key))
def test_dry_run_never_invokes_proxmox_or_reads_service_keys(self):
with patch.object(host, "run", side_effect=AssertionError("must not execute")), contextlib.redirect_stdout(io.StringIO()) as output:
self.assertEqual(0, host.main(["install", "--ctid", "201", "--storage", "local-lvm", "--domain", "usage.example.test", "--email", "[email protected]", "--dry-run"]))
self.assertIn("Plan:", output.getvalue())
def test_pct_exec_explicitly_drops_host_environment(self):
with patch.object(host.subprocess, "run") as runner:
host.run(["pct", "exec", 201, "--", "true"])
self.assertEqual(["pct", "exec", "201", "--keep-env", "0", "--", "true"], runner.call_args.args[0])
def test_update_cannot_silently_change_identity(self):
args = host.parser().parse_args(["update", "--ctid", "201", "--email", "[email protected]"])
with self.assertRaises(ValueError):
host.validate(args)
def test_snapshot_includes_uncommitted_source_but_excludes_outputs_and_hidden_files(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "repo"
for project in host.PROJECTS:
path = root / "src" / project
path.mkdir(parents=True)
(path / "New.cs").write_text("// uncommitted implementation")
(path / ".env").write_text("never bundle")
(path / "bin").mkdir()
(path / "bin/out").write_text("not source")
(path / "server.json").write_text('{"synthetic":"local runtime config"}')
(path / "operator.env").write_text("SYNTHETIC_LOCAL_CONFIGURATION=placeholder")
(path / "private.key").write_text("synthetic local key fixture")
for name in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE"):
(root / name).write_text("fixture")
archive = Path(tmp) / "source.tgz"
digest = host.snapshot(root, archive)
self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), digest)
with tarfile.open(archive) as stream:
names = stream.getnames()
self.assertIn("src/FinalToken.Web/New.cs", names)
self.assertIn("LICENSE", names)
self.assertFalse(any(".env" in n or "/bin/" in n for n in names))
self.assertFalse(any(n.endswith(("server.json", "operator.env", "private.key")) for n in names))
def test_existing_ct_is_never_overwritten(self):
with patch.object(host, "run", return_value=subprocess.CompletedProcess([], 0, "status: running")) as runner:
with self.assertRaises(ValueError):
host.deploy(install_args(), Path("unused"), "0" * 64)
self.assertEqual(1, runner.call_count)
def test_snapshot_refuses_a_symlinked_project_before_traversing_it(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "repo"
project = root / "src/FinalToken.Core"
project.mkdir(parents=True)
(project / "outside.txt").write_text("must not read")
for name in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE"):
(root / name).write_text("fixture")
original = Path.is_symlink
with patch.object(Path, "is_symlink", lambda path: path == project or original(path)), self.assertRaises(ValueError):
host.snapshot(root, Path(tmp) / "source.tgz")
def test_foreign_or_stopped_ct_is_not_updated(self):
args = host.parser().parse_args(["update", "--ctid", "201"])
host.validate(args)
for status in ("status: stopped", "status: running"):
calls = []
def fake(command, **kwargs):
calls.append(command)
return subprocess.CompletedProcess(command, 0, status if command[1] == "status" else '{"installer":"foreign"}')
with patch.object(host, "run", side_effect=fake), self.assertRaises(ValueError):
host.deploy(args, Path("unused"), "0" * 64)
self.assertFalse(any("apt-get" in c or "start" in c or "create" in c for c in calls))
def test_update_uploads_new_source_without_install_identity_or_ct_creation(self):
args = host.parser().parse_args(["update", "--ctid", "201"])
host.validate(args)
calls, manifests = [], []
def fake(command, **kwargs):
command = list(map(str, command))
calls.append(command)
text = "status: running" if command[:2] == ["pct", "status"] else ""
if command[-1] == "/etc/finaltoken/install.json":
text = json.dumps({"installer": "finaltoken-proxmox-v1", "ctid": 201, "role": "server"})
if command[:2] == ["pct", "push"] and command[3].endswith("manifest.json"):
manifests.append(json.loads(Path(command[3]).read_text()))
return subprocess.CompletedProcess(command, 0, text)
with tempfile.TemporaryDirectory() as tmp, patch.object(host, "run", side_effect=fake), contextlib.redirect_stdout(io.StringIO()):
archive = Path(tmp) / "source.tgz"
archive.write_bytes(b"updated source fixture")
host.deploy(args, archive, "a" * 64)
self.assertEqual([{"installer": "finaltoken-proxmox-v1", "ctid": 201, "action": "update", "sourceSha256": "a" * 64}], manifests)
self.assertFalse(any("create" in c or "start" in c or "destroy" in c for c in calls))
self.assertTrue(any("python3" in c and "--manifest" in c for c in calls))
def test_install_orders_create_start_push_and_guest_without_shell_or_destroy(self):
calls = []
def fake(command, **kwargs):
command = list(map(str, command))
calls.append(command)
text, code = "", 0
if command[:2] == ["pct", "status"]:
code = 1
elif command[:2] == ["pveam", "available"]:
text = "system debian-13-standard_13.1-1_amd64.tar.zst\nsystem debian-13-standard_13.2-1_amd64.tar.zst"
elif command[:2] == ["pvesm", "path"]:
code = 1
return subprocess.CompletedProcess(command, code, text)
with tempfile.TemporaryDirectory() as tmp:
archive = Path(tmp) / "source.tgz"
archive.write_bytes(b"fixture")
with patch.object(host, "run", side_effect=fake), contextlib.redirect_stdout(io.StringIO()):
host.deploy(install_args(), archive, "0" * 64)
verbs = [c[1] for c in calls if c[0] == "pct"]
self.assertLess(verbs.index("create"), verbs.index("start"))
self.assertLess(verbs.index("start"), verbs.index("push"))
self.assertNotIn("destroy", verbs)
self.assertTrue(any("local:vztmpl/debian-13-standard_13.2-1_amd64.tar.zst" in c for c in calls))
self.assertFalse(any("sh" in c or "bash" in c for c in calls))
def test_guest_failure_cleans_uploads_and_never_destroys_container(self):
calls = []
def fake(command, **kwargs):
command = list(map(str, command))
calls.append(command)
if "python3" in command and "--manifest" in command:
raise subprocess.CalledProcessError(1, command)
code = 1 if command[:2] in (["pct", "status"], ["pvesm", "path"]) else 0
return subprocess.CompletedProcess(command, code, "")
args = install_args("--template", "debian-13-standard_13.1-1_amd64.tar.zst")
with tempfile.TemporaryDirectory() as tmp:
archive = Path(tmp) / "source.tgz"
archive.write_bytes(b"fixture")
with patch.object(host, "run", side_effect=fake), self.assertRaises(subprocess.CalledProcessError):
host.deploy(args, archive, "0" * 64)
self.assertIn("rm", calls[-1])
self.assertNotIn("destroy", [c[1] for c in calls])
class GuestTests(unittest.TestCase):
def test_server_update_uses_persisted_identity_and_preserves_config_and_history(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
etc = root / "etc"
etc.mkdir()
archive = root / "source.tgz"
archive.write_bytes(b"updated server fixture")
digest = hashlib.sha256(archive.read_bytes()).hexdigest()
identity = {"installer": guest.INSTALLER, "ctid": 201, "installed": True,
"role": "server", "providers": [], "domain": "usage.example.test",
"sourceSha256": "0" * 64, "release": "previous"}
(etc / "install.json").write_text(json.dumps(identity))
config, history = etc / "server.json", root / "history.json"
config.write_text('{"operator":"custom"}')
history.write_text("synthetic retained history")
manifest = {"installer": guest.INSTALLER, "ctid": 201, "action": "update", "sourceSha256": digest}
original_read = Path.read_text
def read(path, *a, **kw):
return 'ID=debian\nVERSION_ID="13"\n' if path.as_posix() == "/etc/os-release" else original_read(path, *a, **kw)
with patch.object(guest, "ETC", etc), patch.object(guest.os, "geteuid", return_value=0, create=True), \
patch.object(guest.os, "uname", return_value=types.SimpleNamespace(machine="x86_64"), create=True), \
patch.object(Path, "read_text", read), patch.object(guest, "packages") as packages, \
patch.object(guest, "configure") as configure, patch.object(guest, "official_clis") as clis, \
patch.object(guest, "build", return_value=root / "release-v2") as build, \
patch.object(guest, "activate") as activate, contextlib.redirect_stdout(io.StringIO()):
guest.provision(manifest, archive)
packages.assert_called_once_with("server", [])
configure.assert_not_called()
clis.assert_not_called()
activate.assert_called_once_with(root / "release-v2", build.call_args.args[1], False)
updated = json.loads((etc / "install.json").read_text())
self.assertEqual("server", updated["role"])
self.assertEqual("usage.example.test", updated["domain"])
self.assertEqual(digest, updated["sourceSha256"])
self.assertEqual(str(root / "release-v2"), updated["release"])
self.assertEqual('{"operator":"custom"}', config.read_text())
self.assertEqual("synthetic retained history", history.read_text())
def test_native_release_preserves_source_license(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
archive = root / "source.tgz"
license_text = b"Synthetic MIT notice\n"
with tarfile.open(archive, "w:gz") as stream:
item = tarfile.TarInfo("LICENSE")
item.size = len(license_text)
stream.addfile(item, io.BytesIO(license_text))
home = root / "build"
home.mkdir()
def fake_publish(name, home, command, **kwargs):
target = Path(command[command.index("-o") + 1])
target.mkdir(parents=True)
header = b"\x7fELF" + b"\0" * 14 + b"\x3e\x00"
(target / "finaltoken-worker").write_bytes(header)
with patch.object(guest, "APP", root / "app"), patch.object(guest, "BUILD", home), \
patch.object(guest, "user", return_value=types.SimpleNamespace(pw_uid=0, pw_gid=0)), \
patch.object(guest.os, "chown", create=True), patch.object(guest, "as_user", side_effect=fake_publish):
release = guest.build(archive, {"role": "worker", "sourceSha256": "0" * 64})
self.assertEqual(license_text, (release / "LICENSE").read_bytes())
def test_atomic_configuration_is_never_replaced_on_update(self):
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "config.json"
guest.atomic(target, "original", once=True)
self.assertFalse(guest.atomic(target, "replacement", once=True))
self.assertEqual("original", target.read_text())
guest.atomic(target, "explicit replacement")
self.assertEqual("explicit replacement", target.read_text())
self.assertEqual([target], list(target.parent.iterdir()))
def test_archive_rejects_traversal_links_and_devices(self):
for name, kind in (("../escape", tarfile.REGTYPE), ("/absolute", tarfile.REGTYPE), ("link", tarfile.SYMTYPE), ("device", tarfile.CHRTYPE)):
with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
archive = Path(tmp) / "source.tgz"
with tarfile.open(archive, "w:gz") as stream:
item = tarfile.TarInfo(name)
item.type = kind
stream.addfile(item)
with self.assertRaises(ValueError):
guest.unpack(archive, Path(tmp) / "extract")
self.assertFalse((Path(tmp) / "escape").exists())
def test_config_generates_bound_profiles_and_preserves_keys_and_settings(self):
with tempfile.TemporaryDirectory() as tmp, contextlib.ExitStack() as stack:
root = Path(tmp)
for name, relative in (("ETC", "etc"), ("WORKER_HOME", "worker"), ("SERVER_HOME", "server"), ("PROXY_HOME", "proxy"), ("SYSTEMD", "units")):
stack.enter_context(patch.object(guest, name, root / relative))
stack.enter_context(patch.object(guest, "run"))
stack.enter_context(patch.object(guest, "user"))
stack.enter_context(patch.object(guest.pwd, "getpwnam", return_value=types.SimpleNamespace(pw_gid=1000)))
stack.enter_context(patch.object(guest.os, "chown", create=True))
meta = {"role": "both", "providers": ["claude", "codex"], "ctid": 201, "machineId": "lxc_201", "timezone": "UTC",
"domain": "usage.example.test", "tls": "internal", "emails": {"claude": "[email protected]", "codex": "[email protected]"}}
guest.configure(meta)
config = json.loads((guest.ETC / "server.json").read_text())
self.assertEqual("finaltoken", config["machines"][0]["osUser"])
self.assertEqual("lxc_201", config["machines"][0]["id"])
worker = json.loads((guest.ETC / "worker.json").read_text())
self.assertEqual("http://127.0.0.1:5187", worker["serverUrl"])
self.assertEqual(2, len(worker["profiles"]))
keys = (guest.ETC / "transport-keys.json").read_bytes()
(guest.ETC / "worker.json").write_text('{"operator":"custom"}')
guest.configure(meta)
self.assertEqual(keys, (guest.ETC / "transport-keys.json").read_bytes())
self.assertEqual({"operator": "custom"}, json.loads((guest.ETC / "worker.json").read_text()))
self.assertIn("tls internal", (guest.ETC / "Caddyfile").read_text())
def test_units_use_profile_owner_and_kill_child_processes(self):
worker = guest.service_unit("worker")
self.assertIn("User=finaltoken\n", worker)
self.assertIn("KillMode=control-group", worker)
self.assertIn("NoNewPrivileges=true", worker)
self.assertIn("User=finaltoken-server", guest.service_unit("server"))
self.assertNotIn("MemoryDenyWriteExecute", worker) # Node-based CLIs can need JIT.
def test_worker_commands_do_not_inherit_root_environment(self):
with patch.object(guest, "run") as runner:
guest.as_user("finaltoken", PurePosixPath("/worker"), ["claude", "--version"])
command = runner.call_args.args[0]
self.assertIn("-i", command)
self.assertIn("HOME=/worker", command)
self.assertNotIn("shell", runner.call_args.kwargs)
def test_failed_activation_restores_previous_release_without_touching_data(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
old = root / "releases/old"
old.mkdir(parents=True)
new = root / "releases/new"
new.mkdir()
history = root / "history.json"
history.write_text("unchanged")
fake_current = Mock()
fake_current.is_symlink.return_value = True
fake_current.resolve.return_value = old
fake_app = Mock()
fake_app.__truediv__ = Mock(return_value=fake_current)
with patch.object(guest, "APP", fake_app), patch.object(guest, "switch") as switch, \
patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 0)), patch.object(guest, "healthy", return_value=False), \
contextlib.redirect_stderr(io.StringIO()), self.assertRaises(ValueError):
guest.activate(new, {"role": "both"}, False)
self.assertEqual([new, old], [c.args[0] for c in switch.call_args_list])
self.assertEqual("unchanged", history.read_text())
def test_update_does_not_start_intentionally_stopped_services(self):
current = Mock()
current.is_symlink.return_value = False
app = Mock()
app.__truediv__ = Mock(return_value=current)
with patch.object(guest, "APP", app), patch.object(guest, "switch"), patch.object(guest, "healthy") as health, \
patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 3)) as runner:
guest.activate(Path("unused"), {"role": "worker"}, False)
health.assert_not_called()
self.assertFalse(any("restart" in call.args[0] or "enable" in call.args[0] for call in runner.call_args_list))
def test_enrollment_key_survives_partial_install_before_packages_fail(self):
with tempfile.TemporaryDirectory() as tmp:
directory = Path(tmp)
archive = directory / "source.tgz"
archive.write_bytes(b"fixture")
meta = {"installer": guest.INSTALLER, "action": "install", "ctid": 201,
"sourceSha256": hashlib.sha256(b"fixture").hexdigest(), "workerKey": "a" * 64}
original_read = Path.read_text
def read(path, *a, **kw):
return 'ID=debian\nVERSION_ID="13"\n' if path.as_posix() == "/etc/os-release" else original_read(path, *a, **kw)
with patch.object(guest, "ETC", directory / "etc"), patch.object(guest.os, "geteuid", return_value=0, create=True), \
patch.object(guest.os, "uname", return_value=types.SimpleNamespace(machine="x86_64"), create=True), \
patch.object(Path, "read_text", read), patch.object(guest, "packages", side_effect=ValueError("network failure")):
meta.update(role="worker", providers=["codex"])
with self.assertRaises(ValueError):
guest.provision(meta, archive)
marker = json.loads((directory / "etc/install.json").read_text())
keys = json.loads((directory / "etc/transport-keys.json").read_text())
self.assertFalse(marker["installed"])
self.assertNotIn("workerKey", marker)
self.assertEqual("a" * 64, keys["worker"])
if __name__ == "__main__":
unittest.main()