Use a global npm install within the service user's prefix so the configured .local/bin launcher exists. Exercise npm with an offline synthetic package and check the installed launcher without contacting a provider. Refs #19
443 lines
26 KiB
Python
443 lines
26 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 shutil
|
|
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_codex_npm_install_creates_the_configured_launcher(self):
|
|
node, npm = shutil.which("node"), shutil.which("npm")
|
|
if not node or not npm:
|
|
self.skipTest("Offline npm launcher integration requires Node.js and npm")
|
|
npm_path = Path(npm).resolve()
|
|
npm_cli = npm_path if npm_path.suffix == ".js" else npm_path.parent / "node_modules/npm/bin/npm-cli.js"
|
|
self.assertTrue(npm_cli.is_file(), "Cannot locate the installed npm CLI")
|
|
with tempfile.TemporaryDirectory(prefix="finaltoken-npm-fixture-") as tmp:
|
|
root = Path(tmp)
|
|
package = root / "codex-fixture.tgz"
|
|
with tarfile.open(package, "w:gz") as archive:
|
|
files = {"package/package.json": json.dumps({"name": "@finaltoken/offline-codex-fixture", "version": "1.0.0",
|
|
"bin": {"codex": "cli.js"}}), "package/cli.js": "#!/usr/bin/env node\nconsole.log('synthetic codex fixture');\n"}
|
|
for name, value in files.items():
|
|
content = value.encode("utf-8")
|
|
item = tarfile.TarInfo(name)
|
|
item.size, item.mode = len(content), 0o755
|
|
archive.addfile(item, io.BytesIO(content))
|
|
user_config, global_config = root / "user.npmrc", root / "global.npmrc"
|
|
user_config.write_text(""); global_config.write_text("")
|
|
env = {name: os.environ[name] for name in ("PATH", "SystemRoot", "TEMP", "TMP", "ComSpec", "PATHEXT") if name in os.environ}
|
|
env.update(NPM_CONFIG_USERCONFIG=str(user_config), NPM_CONFIG_GLOBALCONFIG=str(global_config))
|
|
home = root / "worker"
|
|
home.mkdir()
|
|
versions = []
|
|
def local_user(name, directory, command, **kwargs):
|
|
self.assertEqual("finaltoken", name)
|
|
self.assertEqual(home, directory)
|
|
if command[0] == "npm":
|
|
arguments = list(command[1:-1])
|
|
prefix_index = arguments.index("--prefix") + 1
|
|
prefix = Path(arguments[prefix_index])
|
|
# npm puts global launchers directly in the prefix on Windows;
|
|
# adapt that platform boundary to exercise the guest's Linux bin path.
|
|
if os.name == "nt":
|
|
arguments[prefix_index] = str(prefix / "bin")
|
|
return subprocess.run([node, str(npm_cli), *arguments, str(package), "--offline", "--ignore-scripts",
|
|
"--no-audit", "--no-fund", "--cache", str(root / "cache")], env=env, cwd=root,
|
|
text=True, capture_output=True, check=True, timeout=30)
|
|
launcher = home / ".local/bin/codex"
|
|
self.assertEqual([str(launcher), "--version"], command)
|
|
self.assertTrue(launcher.is_file(), "npm did not install the configured Codex launcher")
|
|
installed = home / (".local/bin/node_modules" if os.name == "nt" else ".local/lib/node_modules")
|
|
result = subprocess.run([node, str(installed / "@finaltoken/offline-codex-fixture/cli.js"), "--version"],
|
|
env=env, cwd=root, text=True, capture_output=True, check=True, timeout=10)
|
|
versions.append(result.stdout.strip())
|
|
with patch.object(guest, "WORKER_HOME", home), patch.object(guest, "as_user", side_effect=local_user):
|
|
guest.official_clis(["codex"])
|
|
guest.official_clis(["codex"]) # Existing launcher is used on subsequent runs.
|
|
self.assertEqual(["synthetic codex fixture"] * 2, versions)
|
|
|
|
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()
|