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
This commit is contained in:
+113
-163
@@ -1,188 +1,138 @@
|
||||
"""Real local Git/Bash updater checks. No network, Proxmox, package or service changes."""
|
||||
"""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
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "proxmox-update.sh"
|
||||
GIT = shutil.which("git")
|
||||
WINDOWS_BASH = Path(GIT).resolve().parents[1] / "bin/bash.exe" if GIT else Path("missing")
|
||||
BASH = str(WINDOWS_BASH) if os.name == "nt" and WINDOWS_BASH.is_file() else shutil.which("bash")
|
||||
|
||||
|
||||
class UpdaterTests(unittest.TestCase):
|
||||
class ContainerUpdateTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
if not GIT or not BASH:
|
||||
self.fail("Git and Bash are required for the updater integration checks")
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="finaltoken-update-")
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="finaltoken-ct-update-test-")
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.seed, self.remote, self.clone = (self.root / n for n in ("seed", "remote.git", "clone"))
|
||||
self.output = self.root / "invocation"
|
||||
self.env = dict(os.environ, GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_SYSTEM=os.devnull,
|
||||
GIT_CONFIG_NOSYSTEM="1", GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="Never",
|
||||
FT_TEST_RESULT=self.output.as_posix())
|
||||
self.git(self.root, "init", "--bare", "--initial-branch=master", str(self.remote))
|
||||
self.git(self.root, "init", "--initial-branch=master", str(self.seed))
|
||||
(self.seed / "tools").mkdir()
|
||||
(self.seed / "tools/proxmox-update.sh").write_bytes(SCRIPT.read_bytes())
|
||||
(self.seed / ".gitignore").write_text("ignored-state/\n")
|
||||
self.installer("v1")
|
||||
self.commit(self.seed, "Initial fixture")
|
||||
self.git(self.seed, "remote", "add", "origin", str(self.remote))
|
||||
self.git(self.seed, "push", "-u", "origin", "master")
|
||||
self.git(self.root, "clone", str(self.remote), str(self.clone))
|
||||
# Git Bash has no flock. Exercise its refusal path with this command seam;
|
||||
# Linux advisory locking itself is deliberately not claimed by these tests.
|
||||
self.bin = self.root / "bin"
|
||||
self.bin.mkdir()
|
||||
(self.bin / "flock").write_text('#!/usr/bin/env bash\nexit "${FT_TEST_LOCK_EXIT:-0}"\n')
|
||||
(self.bin / "flock").chmod(0o755)
|
||||
self.env["PATH"] = str(self.bin) + os.pathsep + self.env["PATH"]
|
||||
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, directory, *arguments):
|
||||
return subprocess.run([GIT, "-c", "user.name=Fixture", "-c", "[email protected]",
|
||||
"-c", "commit.gpgsign=false", "-c", "core.hooksPath=", "-C", str(directory),
|
||||
*arguments], env=self.env, text=True, capture_output=True, check=True)
|
||||
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 commit(self, directory, message):
|
||||
self.git(directory, "add", ".")
|
||||
self.git(directory, "commit", "-m", message)
|
||||
|
||||
def installer(self, version):
|
||||
(self.seed / "tools/proxmox.sh").write_text(
|
||||
'#!/usr/bin/env bash\nset -euo pipefail\n'
|
||||
f'printf "%s\\n" "{version}" "$@" > "$FT_TEST_RESULT"\n'
|
||||
'exit "${FT_TEST_EXIT:-0}"\n')
|
||||
|
||||
def publish(self):
|
||||
self.installer("v2")
|
||||
self.commit(self.seed, "Update fixture installer")
|
||||
self.git(self.seed, "push")
|
||||
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):
|
||||
# The caller's cwd deliberately differs from the checkout location.
|
||||
return subprocess.run([BASH, str(self.clone / "tools/proxmox-update.sh"), *arguments],
|
||||
cwd=self.root, env=self.env, text=True, capture_output=True)
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
return updater.main(list(arguments))
|
||||
|
||||
def test_refresh_executes_new_installer_and_passes_exact_ctid_and_source(self):
|
||||
self.publish()
|
||||
result = self.update("201")
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
lines = self.output.read_text().splitlines()
|
||||
self.assertEqual(["v2", "update", "--ctid", "201", "--source"], lines[:-1])
|
||||
# Git Bash reports /c/... while native Windows Python uses C:/....
|
||||
self.assertTrue(lines[-1].replace("\\", "/").endswith("/clone"))
|
||||
self.assertEqual(self.git(self.seed, "rev-parse", "HEAD").stdout,
|
||||
self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
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_no_new_commit_still_runs_installer_to_resume_failed_deployment(self):
|
||||
result = self.update("201")
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertEqual("v1", self.output.read_text().splitlines()[0])
|
||||
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_dry_run_never_fetches_or_changes_checkout(self):
|
||||
before = self.git(self.clone, "rev-parse", "HEAD").stdout
|
||||
self.publish()
|
||||
result = self.update("201", "--dry-run")
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertIn("--dry-run", self.output.read_text().splitlines())
|
||||
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
self.assertFalse((self.clone / ".git/FETCH_HEAD").exists())
|
||||
self.assertFalse((self.clone / ".git/finaltoken-proxmox-update.lock").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_dirty_tracked_staged_or_untracked_source_is_retained_and_not_deployed(self):
|
||||
for state in ("tracked", "staged", "untracked"):
|
||||
with self.subTest(state=state):
|
||||
path = self.clone / ("local.txt" if state == "untracked" else ".gitignore")
|
||||
original = path.read_bytes() if path.exists() else None
|
||||
path.write_text("operator local change\n")
|
||||
if state == "staged":
|
||||
self.git(self.clone, "add", str(path))
|
||||
result = self.update("201")
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertIn("clean", result.stderr)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual("operator local change\n", path.read_text())
|
||||
self.git(self.clone, "reset", "--", str(path))
|
||||
if original is None:
|
||||
path.unlink()
|
||||
else:
|
||||
path.write_bytes(original)
|
||||
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_diverged_or_ahead_branch_is_not_deployed_or_reset(self):
|
||||
(self.clone / "operator.txt").write_text("local commit fixture")
|
||||
self.commit(self.clone, "Local-only fixture")
|
||||
before = self.git(self.clone, "rev-parse", "HEAD").stdout
|
||||
for diverged in (False, True):
|
||||
with self.subTest(diverged=diverged):
|
||||
if diverged:
|
||||
self.publish()
|
||||
result = self.update("201")
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
self.assertEqual("local commit fixture", (self.clone / "operator.txt").read_text())
|
||||
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_no_upstream_or_detached_head_never_deploys(self):
|
||||
self.git(self.clone, "branch", "--unset-upstream")
|
||||
self.assertNotEqual(0, self.update("201").returncode)
|
||||
self.git(self.clone, "checkout", "--detach")
|
||||
self.assertNotEqual(0, self.update("201").returncode)
|
||||
self.assertFalse(self.output.exists())
|
||||
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_fetch_failure_leaves_checkout_and_does_not_deploy_or_echo_remote(self):
|
||||
self.git(self.clone, "remote", "set-url", "origin", str(self.root / "private-origin-not-available"))
|
||||
before = self.git(self.clone, "rev-parse", "HEAD").stdout
|
||||
result = self.update("201")
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertNotIn("private-origin-not-available", result.stdout + result.stderr)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
|
||||
def test_busy_checkout_never_pulls_or_deploys(self):
|
||||
self.env["FT_TEST_LOCK_EXIT"] = "1"
|
||||
self.publish()
|
||||
before = self.git(self.clone, "rev-parse", "HEAD").stdout
|
||||
self.assertNotEqual(0, self.update("201").returncode)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
|
||||
def test_installer_failure_propagates_and_keeps_ignored_local_state(self):
|
||||
state = self.clone / "ignored-state/history.json"
|
||||
state.parent.mkdir()
|
||||
state.write_text("synthetic local history")
|
||||
self.env["FT_TEST_EXIT"] = "17"
|
||||
result = self.update("201")
|
||||
self.assertEqual(17, result.returncode, result.stdout + result.stderr)
|
||||
self.assertEqual("synthetic local history", state.read_text())
|
||||
|
||||
def test_upstream_cannot_overwrite_ignored_operator_state(self):
|
||||
relative = "ignored-state/history.json"
|
||||
local = self.clone / relative
|
||||
local.parent.mkdir()
|
||||
local.write_text("synthetic retained operator history")
|
||||
upstream = self.seed / relative
|
||||
upstream.parent.mkdir()
|
||||
upstream.write_text("upstream fixture must not overwrite operator data")
|
||||
self.git(self.seed, "add", "--force", relative)
|
||||
self.publish()
|
||||
before = self.git(self.clone, "rev-parse", "HEAD").stdout
|
||||
result = self.update("201")
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
self.assertEqual("synthetic retained operator history", local.read_text())
|
||||
|
||||
def test_invalid_arguments_are_rejected_before_fetch(self):
|
||||
for arguments in ((), ("99",), ("201", "--source", "/tmp/other"), ("201;touch /tmp/no",), ("201", "--unknown")):
|
||||
with self.subTest(arguments=arguments):
|
||||
self.assertNotEqual(0, self.update(*arguments).returncode)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertFalse((self.clone / ".git/FETCH_HEAD").exists())
|
||||
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__":
|
||||
|
||||
Reference in New Issue
Block a user