agent-review agent review: pass
Remove fixed-host and HTTPS-only deployment requirements so the dashboard works at the container IP on HTTP port 5187. Validate browser mutations against the actual request host and retain access keys and CSRF protection. Ignore legacy public-origin settings and make Proxmox setup hostname-free. Update D14 and regression coverage for version 1.2.3. Refs #25
618 lines
38 KiB
Python
618 lines
38 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_install_requires_no_hostname(self):
|
|
args = host.parser().parse_args(["install", "--role", "server", "--ctid", "201", "--storage", "local-lvm"])
|
|
host.validate(args)
|
|
self.assertIsNone(args.domain)
|
|
|
|
def test_worker_can_use_a_direct_http_ip_address(self):
|
|
self.assertEqual("http://10.0.30.150:5187", host.server_url("http://10.0.30.150:5187/"))
|
|
|
|
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_http_origin_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", "ftp://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_host_refuses_update_before_any_proxmox_command(self):
|
|
with patch.object(host, "run", side_effect=AssertionError("No host update")), contextlib.redirect_stderr(io.StringIO()):
|
|
with self.assertRaises(SystemExit):
|
|
host.main(["update", "--ctid", "201"])
|
|
|
|
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", "tools/lxc_update.py"):
|
|
(root / name).parent.mkdir(parents=True, exist_ok=True)
|
|
(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", "tools/lxc_update.py"):
|
|
(root / name).parent.mkdir(parents=True, exist_ok=True)
|
|
(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_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_dashboard_urls_use_container_ips_and_bracket_ipv6(self):
|
|
with patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 0, "10.0.30.150 2001:db8::5 fe80::1 127.0.0.1")):
|
|
self.assertEqual(["http://10.0.30.150:5187", "http://[2001:db8::5]:5187"], guest.dashboard_urls())
|
|
|
|
def test_missing_address_command_does_not_fail_an_update(self):
|
|
with patch.object(guest, "run", side_effect=FileNotFoundError):
|
|
self.assertEqual(["http://<container-ip>:5187"], guest.dashboard_urls())
|
|
|
|
def test_health_check_uses_no_configured_hostname(self):
|
|
with patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 0)), patch.object(guest.time, "sleep"), \
|
|
patch.object(guest.urllib.request, "urlopen") as opener:
|
|
opener.return_value.__enter__.return_value.status = 200
|
|
self.assertTrue(guest.healthy(["finaltoken-server.service"], {"role": "server"}))
|
|
self.assertEqual("http://127.0.0.1:5187/", opener.call_args.args[0].full_url)
|
|
self.assertFalse(opener.call_args.args[0].has_header("Host"))
|
|
|
|
def test_server_packages_do_not_install_a_reverse_proxy(self):
|
|
with patch.object(guest, "run") as runner, patch.object(Path, "exists", return_value=True):
|
|
guest.packages("server", [])
|
|
commands = [list(map(str, call.args[0])) for call in runner.call_args_list]
|
|
self.assertFalse(any("caddy" in command for command in commands))
|
|
|
|
def test_fresh_server_exposes_backend_without_proxy_configuration(self):
|
|
with tempfile.TemporaryDirectory() as tmp, contextlib.ExitStack() as stack:
|
|
root = Path(tmp)
|
|
for name, relative in (("ETC", "etc"), ("SERVER_HOME", "server"), ("SYSTEMD", "units")):
|
|
stack.enter_context(patch.object(guest, name, root / relative))
|
|
users = stack.enter_context(patch.object(guest, "user"))
|
|
runner = stack.enter_context(patch.object(guest, "run"))
|
|
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))
|
|
guest.configure({"role": "server", "providers": [], "emails": {}, "ctid": 201,
|
|
"machineId": "lxc_201", "timezone": "UTC"})
|
|
environment = (guest.ETC / "server.env").read_text()
|
|
self.assertTrue("ASPNETCORE_URLS=http://0.0.0.0:5187" in environment)
|
|
self.assertNotIn("FINALTOKEN_PUBLIC_ORIGIN", environment)
|
|
self.assertFalse((guest.ETC / "Caddyfile").exists())
|
|
self.assertFalse((guest.SYSTEMD / "finaltoken-proxy.service").exists())
|
|
self.assertEqual(["finaltoken-server"], [call.args[0] for call in users.call_args_list])
|
|
self.assertFalse(any("caddy.service" in call.args[0] for call in runner.call_args_list))
|
|
|
|
def test_only_application_services_are_managed(self):
|
|
self.assertEqual(["finaltoken-server.service"], guest.units("server"))
|
|
|
|
def test_legacy_proxy_migration_preserves_keys_and_stops_only_owned_proxy(self):
|
|
for newline in (b"\n", b"\r\n"):
|
|
with self.subTest(newline=newline), tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
(root / "units").mkdir()
|
|
(root / "units/finaltoken-proxy.service").write_text("owned fixture")
|
|
original = newline.join([b"FINALTOKEN_DASHBOARD_KEY=synthetic-fixture-only", b"ASPNETCORE_URLS=http://127.0.0.1:5187", b"FINALTOKEN_PUBLIC_ORIGIN=https://usage.example.test", b""])
|
|
(root / "server.env").write_bytes(original)
|
|
(root / "server.json").write_bytes(b"operator config")
|
|
calls = []
|
|
def fake(command, **kwargs):
|
|
calls.append(command)
|
|
return subprocess.CompletedProcess(command, 0)
|
|
with patch.object(guest, "ETC", root), patch.object(guest, "SYSTEMD", root / "units"), \
|
|
patch.object(guest, "run", side_effect=fake), patch.object(guest, "healthy", return_value=True):
|
|
updated = guest.migrate_external_proxy({"role": "server", "domain": "usage.example.test"})
|
|
self.assertEqual("external", updated["network"])
|
|
self.assertTrue((root / "server.env").read_bytes() == original.replace(b"127.0.0.1:5187", b"0.0.0.0:5187"))
|
|
self.assertTrue((root / "server.env.pre-external-proxy").read_bytes() == original)
|
|
self.assertEqual(b"operator config", (root / "server.json").read_bytes())
|
|
self.assertIn(["systemctl", "disable", "--now", "finaltoken-proxy.service"], calls)
|
|
self.assertFalse(any("caddy.service" in command or "purge" in command or "remove" in command for command in calls))
|
|
|
|
def test_failed_proxy_migration_restores_listener_and_running_services(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
(root / "units").mkdir()
|
|
(root / "units/finaltoken-proxy.service").write_text("owned")
|
|
original = "ASPNETCORE_URLS=http://127.0.0.1:5187\n"
|
|
(root / "server.env").write_bytes(original.encode())
|
|
with patch.object(guest, "ETC", root), patch.object(guest, "SYSTEMD", root / "units"), \
|
|
patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 0)) as runner, \
|
|
patch.object(guest, "healthy", return_value=False), self.assertRaises(ValueError):
|
|
guest.migrate_external_proxy({"role": "server"})
|
|
self.assertEqual(original.encode(), (root / "server.env").read_bytes())
|
|
commands = [call.args[0] for call in runner.call_args_list]
|
|
self.assertIn(["systemctl", "restart", "finaltoken-proxy.service"], commands)
|
|
self.assertNotIn(["systemctl", "disable", "--now", "finaltoken-proxy.service"], commands)
|
|
|
|
def test_custom_listener_is_not_overwritten_by_migration(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
original = b"ASPNETCORE_URLS=http://192.0.2.10:6000\n"
|
|
(root / "server.env").write_bytes(original)
|
|
with patch.object(guest, "ETC", root), patch.object(guest, "run") as runner, self.assertRaises(ValueError):
|
|
guest.migrate_external_proxy({"role": "server"})
|
|
runner.assert_not_called()
|
|
self.assertEqual(original, (root / "server.env").read_bytes())
|
|
|
|
def test_proxy_stop_failure_rolls_back_listener_and_proxy_state(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
(root / "units").mkdir()
|
|
(root / "units/finaltoken-proxy.service").write_text("owned")
|
|
original = b"ASPNETCORE_URLS=http://127.0.0.1:5187\n"
|
|
(root / "server.env").write_bytes(original)
|
|
calls = []
|
|
def fake(command, **kwargs):
|
|
calls.append(command)
|
|
if command[1:3] == ["disable", "--now"]:
|
|
raise subprocess.CalledProcessError(1, command)
|
|
return subprocess.CompletedProcess(command, 0)
|
|
with patch.object(guest, "ETC", root), patch.object(guest, "SYSTEMD", root / "units"), \
|
|
patch.object(guest, "run", side_effect=fake), patch.object(guest, "healthy", return_value=True), \
|
|
self.assertRaises(subprocess.CalledProcessError):
|
|
guest.migrate_external_proxy({"role": "server"})
|
|
self.assertEqual(original, (root / "server.env").read_bytes())
|
|
self.assertIn(["systemctl", "enable", "finaltoken-proxy.service"], calls)
|
|
self.assertIn(["systemctl", "restart", "finaltoken-proxy.service"], calls)
|
|
|
|
def test_migration_keeps_intentionally_stopped_backend_stopped(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
(root / "server.env").write_bytes(b"ASPNETCORE_URLS=http://127.0.0.1:5187\n")
|
|
with patch.object(guest, "ETC", root), patch.object(guest, "SYSTEMD", root / "units"), \
|
|
patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 3)) as runner, \
|
|
patch.object(guest, "healthy") as healthy:
|
|
guest.migrate_external_proxy({"role": "server"})
|
|
healthy.assert_not_called()
|
|
self.assertFalse(any("restart" in call.args[0] or "start" in call.args[0] for call in runner.call_args_list))
|
|
|
|
def test_worker_migration_does_not_access_server_configuration(self):
|
|
with patch.object(Path, "read_bytes", side_effect=AssertionError("Worker has no server environment")):
|
|
self.assertEqual("external", guest.migrate_external_proxy({"role": "worker"})["network"])
|
|
|
|
def test_updater_registration_does_not_overwrite_an_operator_file(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = Path(tmp) / "finaltoken-update"
|
|
path.write_bytes(b"operator file")
|
|
with patch.object(guest, "UPDATER", path), self.assertRaises(ValueError):
|
|
guest.install_updater()
|
|
self.assertEqual(b"operator file", path.read_bytes())
|
|
|
|
def test_updater_is_discoverable_without_sbin_in_shell_path(self):
|
|
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")
|
|
self.assertIsNotNone(bash, "Bash is required for container command lookup verification")
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
app = root / "app"
|
|
target = app / "current/finaltoken-update"
|
|
target.parent.mkdir(parents=True)
|
|
target.write_bytes(b"#!/bin/sh\nprintf 'synthetic updater executed\\n'\n")
|
|
target.chmod(0o755)
|
|
registered = root / guest.UPDATER.as_posix().lstrip("/")
|
|
searched = root / "usr/local/bin"
|
|
searched.mkdir(parents=True)
|
|
with contextlib.ExitStack() as stack:
|
|
stack.enter_context(patch.object(guest, "APP", app))
|
|
stack.enter_context(patch.object(guest, "UPDATER", registered))
|
|
if os.name == "nt":
|
|
# Windows may deny symlink creation; only substitute that OS operation.
|
|
# The real Bash lookup/execution still uses the actual installed path.
|
|
stack.enter_context(patch.object(Path, "symlink_to", lambda path, destination: shutil.copy2(destination, path)))
|
|
guest.install_updater()
|
|
env = dict(os.environ, PATH=str(searched))
|
|
env.pop("BASH_ENV", None)
|
|
result = subprocess.run([bash, "--noprofile", "--norc", "-c",
|
|
"command -v finaltoken-update && finaltoken-update"], env=env,
|
|
text=True, capture_output=True, timeout=10)
|
|
self.assertEqual(0, result.returncode, result.stderr)
|
|
self.assertIn("synthetic updater executed", result.stdout)
|
|
|
|
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", "network": "external", "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, "install_updater"), patch.object(guest, "dashboard_urls", return_value=["http://10.0.30.150:5187"]), \
|
|
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))
|
|
item = tarfile.TarInfo("tools/lxc_update.py")
|
|
item.size = 1
|
|
stream.addfile(item, io.BytesIO(b"#"))
|
|
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_build_user_cannot_replace_the_root_updater(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root = Path(tmp)
|
|
trusted = b"#!/usr/bin/env python3\n# trusted archive updater\n"
|
|
malicious = b"#!/usr/bin/env python3\n# build-user replacement\n"
|
|
archive = root / "source.tgz"
|
|
with tarfile.open(archive, "w:gz") as stream:
|
|
for name, content in (("LICENSE", b"fixture"), ("tools/lxc_update.py", trusted)):
|
|
item = tarfile.TarInfo(name)
|
|
item.size = len(content)
|
|
stream.addfile(item, io.BytesIO(content))
|
|
home = root / "build"
|
|
home.mkdir()
|
|
def compromised_publish(name, home, command, **kwargs):
|
|
source = Path(kwargs["cwd"])
|
|
(source / "tools/lxc_update.py").write_bytes(malicious)
|
|
output = Path(command[command.index("-o") + 1])
|
|
output.mkdir(parents=True)
|
|
(output / "finaltoken-worker").write_bytes(b"\x7fELF" + b"\0" * 14 + b"\x3e\x00")
|
|
(output.parent / "finaltoken-update").write_bytes(malicious)
|
|
with patch.object(guest, "APP", root / "app"), patch.object(guest, "BUILD", home), \
|
|
patch.object(guest, "user", return_value=types.SimpleNamespace(pw_uid=1000, pw_gid=1000)), \
|
|
patch.object(guest.os, "chown", create=True), patch.object(guest, "as_user", side_effect=compromised_publish):
|
|
release = guest.build(archive, {"role": "worker", "sourceSha256": "0" * 64})
|
|
self.assertEqual(trusted, (release / "finaltoken-update").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"), ("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.assertFalse((guest.ETC / "Caddyfile").exists())
|
|
|
|
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()
|