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:
@@ -1,2 +1,2 @@
|
||||
# Proxmox deployment tools
|
||||
Host creates only a new explicitly selected CT; update requires this installer's marker. Never destroy a CT, alter host package repositories, overwrite existing configuration, or read provider credentials. Builds run inside the CT as an isolated user. Transport keys are FinalToken service keys, not provider tokens. Keep commands as argv lists; never shell-interpolate deployment inputs. Test with `python -B tools/proxmox/test_installer.py`.
|
||||
Host creates only a new explicitly selected CT. Updates run inside the CT with finaltoken-update and require this installer's marker. Use the operator's existing reverse proxy; new installs expose private HTTP :5187 and never install a proxy. Legacy migration may change only the known listener and disable finaltoken-proxy.service; preserve keys/data and unrelated services. Never destroy a CT, alter host package repositories or read provider credentials. Builds run inside the CT as an isolated user. Keep commands as argv lists. Test with `python -B tools/proxmox/test_installer.py` and `python -B tools/proxmox/test_update.py`.
|
||||
|
||||
+60
-39
@@ -5,6 +5,7 @@ import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import pwd
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
@@ -21,7 +22,7 @@ APP = Path("/opt/finaltoken")
|
||||
BUILD = Path("/var/cache/finaltoken-build")
|
||||
SERVER_HOME = Path("/var/lib/finaltoken-server")
|
||||
WORKER_HOME = Path("/var/lib/finaltoken-worker")
|
||||
PROXY_HOME = Path("/var/lib/finaltoken-proxy")
|
||||
UPDATER = Path("/usr/local/sbin/finaltoken-update")
|
||||
SYSTEMD = Path("/etc/systemd/system")
|
||||
|
||||
|
||||
@@ -38,7 +39,7 @@ def atomic(path, data, mode=0o600, *, once=False):
|
||||
temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp")
|
||||
try:
|
||||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as stream:
|
||||
with os.fdopen(fd, "w", encoding="utf-8", newline="") as stream:
|
||||
stream.write(data)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
@@ -93,9 +94,7 @@ def as_user(name, home, command, cwd=None):
|
||||
|
||||
def packages(role, providers):
|
||||
run(["apt-get", "update"])
|
||||
wanted = ["ca-certificates", "curl", "clang", "zlib1g-dev", "libicu-dev", "libssl-dev", "tzdata"]
|
||||
if role != "worker":
|
||||
wanted.append("caddy")
|
||||
wanted = ["git", "ca-certificates", "curl", "clang", "zlib1g-dev", "libicu-dev", "libssl-dev", "tzdata"]
|
||||
if role != "server" and "codex" in providers:
|
||||
wanted.extend(["nodejs", "npm"])
|
||||
run(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", *wanted])
|
||||
@@ -160,39 +159,12 @@ WantedBy=multi-user.target
|
||||
"""
|
||||
|
||||
|
||||
def proxy_unit():
|
||||
return f"""[Unit]
|
||||
Description=FinalToken HTTPS proxy
|
||||
After=network-online.target finaltoken-server.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=exec
|
||||
User=finaltoken-proxy
|
||||
Group=finaltoken-proxy
|
||||
Environment=HOME={PROXY_HOME}
|
||||
Environment=XDG_DATA_HOME={PROXY_HOME}
|
||||
ExecStart=/usr/bin/caddy run --config {ETC}/Caddyfile --adapter caddyfile
|
||||
ExecReload=/usr/bin/caddy reload --config {ETC}/Caddyfile --adapter caddyfile
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
||||
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
|
||||
NoNewPrivileges=true
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
"""
|
||||
|
||||
|
||||
def configure(meta, enrollment_key=None):
|
||||
role, providers = meta["role"], meta["providers"]
|
||||
ETC.mkdir(parents=True, exist_ok=True)
|
||||
ETC.chmod(0o755)
|
||||
if role != "worker":
|
||||
user("finaltoken-server", SERVER_HOME)
|
||||
user("finaltoken-proxy", PROXY_HOME)
|
||||
if role != "server":
|
||||
user("finaltoken", WORKER_HOME)
|
||||
keys_path = ETC / "transport-keys.json"
|
||||
@@ -207,14 +179,10 @@ def configure(meta, enrollment_key=None):
|
||||
json_file(ETC / "server.json", {"accounts": accounts, "machines": machines}, once=True)
|
||||
atomic(ETC / "server.env", f"FINALTOKEN_SERVER_CONFIG={ETC}/server.json\nFINALTOKEN_SERVER_DATA={SERVER_HOME}/data\n"
|
||||
f"FINALTOKEN_DASHBOARD_KEY={keys['dashboard']}\nFINALTOKEN_PUBLIC_ORIGIN=https://{meta['domain']}\n"
|
||||
f"ASPNETCORE_URLS=http://127.0.0.1:5187\nFINALTOKEN_MACHINE_{meta['machineId']}={keys['worker']}\n", once=True)
|
||||
f"ASPNETCORE_URLS=http://0.0.0.0:5187\nFINALTOKEN_MACHINE_{meta['machineId']}={keys['worker']}\n", once=True)
|
||||
atomic(ETC / "dashboard-key", keys["dashboard"] + "\n", once=True)
|
||||
atomic(ETC / "worker-key", keys["worker"] + "\n", once=True)
|
||||
tls = " tls internal\n" if meta["tls"] == "internal" else ""
|
||||
atomic(ETC / "Caddyfile", f"{meta['domain']} {{\n{tls} reverse_proxy 127.0.0.1:5187\n}}\n", 0o644, once=True)
|
||||
atomic(SYSTEMD / "finaltoken-server.service", service_unit("server"), 0o644, once=True)
|
||||
atomic(SYSTEMD / "finaltoken-proxy.service", proxy_unit(), 0o644, once=True)
|
||||
run(["systemctl", "disable", "--now", "caddy.service"])
|
||||
if role != "server":
|
||||
profiles = [{"id": p, "provider": p.capitalize(), "expectedEmail": meta["emails"][p],
|
||||
"configDirectory": str(WORKER_HOME / (".claude" if p == "claude" else ".codex")),
|
||||
@@ -249,6 +217,7 @@ def build(archive, meta):
|
||||
if meta["role"] != "worker" and not (release / "web/wwwroot/index.html").is_file():
|
||||
shutil.copytree(source / "src/FinalToken.Web/wwwroot", release / "web/wwwroot", dirs_exist_ok=True)
|
||||
shutil.copy2(source / "LICENSE", release / "LICENSE")
|
||||
shutil.copy2(source / "tools/lxc_update.py", release / "finaltoken-update")
|
||||
destination = APP / "releases" / (meta["sourceSha256"][:16] + "-" + uuid.uuid4().hex[:8])
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
APP.chmod(0o755)
|
||||
@@ -267,6 +236,7 @@ def build(archive, meta):
|
||||
if header[:4] != b"\x7fELF" or header[18:20] != b"\x3e\x00":
|
||||
raise ValueError("Published executable is not a Linux x64 ELF binary")
|
||||
executable.chmod(0o755)
|
||||
(destination / "finaltoken-update").chmod(0o755)
|
||||
return destination
|
||||
finally:
|
||||
# Only this invocation's fresh build directory, never profiles, state or previous releases.
|
||||
@@ -285,7 +255,54 @@ def switch(release):
|
||||
|
||||
|
||||
def units(role):
|
||||
return (["finaltoken-server.service", "finaltoken-proxy.service"] if role != "worker" else []) + (["finaltoken-worker.service"] if role != "server" else [])
|
||||
return (["finaltoken-server.service"] if role != "worker" else []) + (["finaltoken-worker.service"] if role != "server" else [])
|
||||
|
||||
|
||||
def install_updater():
|
||||
target = APP / "current/finaltoken-update"
|
||||
if UPDATER.is_symlink() and UPDATER.readlink() == target:
|
||||
return
|
||||
if UPDATER.exists() or UPDATER.is_symlink():
|
||||
raise ValueError("Updater path already exists and is not owned by this installer")
|
||||
UPDATER.parent.mkdir(parents=True, exist_ok=True)
|
||||
UPDATER.symlink_to(target) # Atomic creation, without overwriting an operator file.
|
||||
|
||||
|
||||
def migrate_external_proxy(meta):
|
||||
"""The new in-container updater migrates the old installer-owned network layout."""
|
||||
updated = dict(meta, network="external")
|
||||
if meta["role"] == "worker":
|
||||
return updated
|
||||
path = ETC / "server.env"
|
||||
text = path.read_bytes().decode("utf-8")
|
||||
matches = re.findall(r"(?m)^ASPNETCORE_URLS=([^\r\n]*)", text)
|
||||
if len(matches) != 1 or matches[0] not in ("http://127.0.0.1:5187", "http://0.0.0.0:5187"):
|
||||
raise ValueError("Custom backend listener retained; configure it for your external proxy before migration")
|
||||
replacement = re.sub(r"(?m)^ASPNETCORE_URLS=[^\r\n]*", "ASPNETCORE_URLS=http://0.0.0.0:5187", text)
|
||||
server, proxy = "finaltoken-server.service", "finaltoken-proxy.service"
|
||||
present = (SYSTEMD / proxy).is_file()
|
||||
active = run(["systemctl", "is-active", "--quiet", server], check=False, capture=True).returncode == 0
|
||||
proxy_active = present and run(["systemctl", "is-active", "--quiet", proxy], check=False, capture=True).returncode == 0
|
||||
proxy_enabled = present and run(["systemctl", "is-enabled", "--quiet", proxy], check=False, capture=True).returncode == 0
|
||||
atomic(ETC / "server.env.pre-external-proxy", text, once=True)
|
||||
try:
|
||||
atomic(path, replacement)
|
||||
if active:
|
||||
run(["systemctl", "restart", server])
|
||||
if not healthy([server], updated):
|
||||
raise ValueError("External-proxy backend health check failed")
|
||||
if present:
|
||||
run(["systemctl", "disable", "--now", proxy])
|
||||
except Exception:
|
||||
atomic(path, text)
|
||||
if active:
|
||||
run(["systemctl", "restart", server], check=False)
|
||||
if proxy_enabled:
|
||||
run(["systemctl", "enable", proxy], check=False)
|
||||
if proxy_active:
|
||||
run(["systemctl", "restart", proxy], check=False)
|
||||
raise
|
||||
return updated
|
||||
|
||||
|
||||
def healthy(services, meta):
|
||||
@@ -367,6 +384,10 @@ def provision(manifest, archive):
|
||||
activate(release, meta, first)
|
||||
meta.update(installed=True, release=str(release))
|
||||
json_file(marker, meta)
|
||||
if meta.get("network") != "external":
|
||||
meta = migrate_external_proxy(meta)
|
||||
json_file(marker, meta)
|
||||
install_updater()
|
||||
if meta["role"] != "worker":
|
||||
print("Dashboard: https://" + meta["domain"])
|
||||
print("Dashboard key is root-readable at /etc/finaltoken/dashboard-key (not printed).")
|
||||
@@ -382,5 +403,5 @@ if __name__ == "__main__":
|
||||
provision(json.loads(args.manifest.read_text(encoding="utf-8")), args.archive)
|
||||
except (ValueError, OSError, subprocess.CalledProcessError) as error:
|
||||
print("Guest setup failed: " + (str(error) if isinstance(error, ValueError) else type(error).__name__), file=sys.stderr)
|
||||
print("Configuration, history and CLI profiles were retained. Inspect services; retry with host update.", file=sys.stderr)
|
||||
print("Configuration, history and CLI profiles were retained. Retry finaltoken-update inside the container.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
+23
-76
@@ -1,6 +1,5 @@
|
||||
"""Create/update an unprivileged Debian 13 LXC from a local FinalToken source snapshot."""
|
||||
"""Create an unprivileged Debian 13 LXC. Updates run inside the container."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
@@ -9,17 +8,14 @@ import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from source_policy import is_private_path
|
||||
from source_bundle import PROJECTS, snapshot
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PROJECTS = ("FinalToken.Core", "FinalToken.Fleet", "FinalToken.Web", "FinalToken.Worker")
|
||||
TEMPLATE = re.compile(r"debian-13-standard_[A-Za-z0-9.+_-]+_amd64\.tar\.(?:zst|xz|gz)\Z")
|
||||
|
||||
|
||||
@@ -55,8 +51,8 @@ def server_url(value):
|
||||
|
||||
def parser():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("action", choices=("install", "update"))
|
||||
p.add_argument("--ctid", type=int, help="New CT id; defaults to Proxmox nextid. Required for update.")
|
||||
p.add_argument("action", choices=("install",), help="Create a CT. Run finaltoken-update inside an existing CT.")
|
||||
p.add_argument("--ctid", type=int, help="New CT id; defaults to Proxmox nextid.")
|
||||
p.add_argument("--source", type=Path, default=ROOT, help="Local checkout including uncommitted source")
|
||||
p.add_argument("--storage", help="Proxmox rootdir storage, e.g. local-lvm (required for install)")
|
||||
p.add_argument("--template-storage", default="local")
|
||||
@@ -68,9 +64,8 @@ def parser():
|
||||
p.add_argument("--memory", type=int, default=4096, help="MiB; builds need at least 4096")
|
||||
p.add_argument("--cores", type=int, default=2)
|
||||
p.add_argument("--disk", type=int, default=20, help="GiB")
|
||||
p.add_argument("--role", choices=("both", "server", "worker"), help="Install default: both; update preserves role")
|
||||
p.add_argument("--role", choices=("both", "server", "worker"), help="Install default: both")
|
||||
p.add_argument("--domain", help="Dashboard DNS name; required for server/both")
|
||||
p.add_argument("--tls", choices=("acme", "internal"), default="acme")
|
||||
p.add_argument("--email", help="Expected provider email for both selected providers")
|
||||
p.add_argument("--claude-email")
|
||||
p.add_argument("--codex-email")
|
||||
@@ -86,16 +81,10 @@ def parser():
|
||||
def validate(args):
|
||||
if args.ctid is not None and not 100 <= args.ctid <= 999999999:
|
||||
raise ValueError("CT id must be between 100 and 999999999")
|
||||
if args.action == "update" and args.ctid is None:
|
||||
raise ValueError("Update requires --ctid")
|
||||
args.source = args.source.resolve()
|
||||
for project in PROJECTS:
|
||||
if not (args.source / "src" / project / (project + ".csproj")).is_file():
|
||||
raise ValueError("Source must include the web/worker implementation: " + project)
|
||||
if args.action == "update":
|
||||
if args.role or args.domain or args.email or args.claude_email or args.codex_email or args.machine_id or args.server_url or args.worker_key_file:
|
||||
raise ValueError("Update preserves identity/configuration; pass only CT id and source (plus --dry-run)")
|
||||
return
|
||||
args.role = args.role or "both"
|
||||
for value in (args.storage or "", args.template_storage, args.bridge):
|
||||
if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_-]{0,63}", value):
|
||||
@@ -116,7 +105,7 @@ def validate(args):
|
||||
raise ValueError("Template must be a Debian 13 standard amd64 template filename")
|
||||
if args.role != "worker":
|
||||
if not args.domain:
|
||||
raise ValueError("Server/both requires --domain for HTTPS; use --tls internal for a private CA")
|
||||
raise ValueError("Server/both requires the public hostname configured on your existing HTTPS reverse proxy")
|
||||
args.domain = domain_name(args.domain)
|
||||
else:
|
||||
if not args.server_url or not args.worker_key_file:
|
||||
@@ -153,37 +142,6 @@ def create_command(args, ctid, template):
|
||||
"--description", "FinalToken installer; retains configuration and CLI profiles on update"]
|
||||
|
||||
|
||||
def snapshot(source, destination):
|
||||
"""Allowlist source inputs, including uncommitted changes, excluding secrets, outputs and symlinks."""
|
||||
files = [source / n for n in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE")]
|
||||
for project in PROJECTS:
|
||||
directory = source / "src" / project
|
||||
if directory.is_symlink() or directory.resolve() != directory.absolute():
|
||||
raise ValueError("Source snapshot refuses a symlinked project or parent: " + project)
|
||||
files.extend(directory.rglob("*"))
|
||||
total, count = 0, 0
|
||||
with tarfile.open(destination, "w:gz") as archive:
|
||||
for path in sorted(set(files)):
|
||||
relative = path.relative_to(source)
|
||||
if is_private_path(relative):
|
||||
continue # .gitignore does not apply to tarfile: do not copy local deployment data.
|
||||
if any(p in ("bin", "obj", "artifacts", ".git", "node_modules") or p.startswith(".") for p in relative.parts):
|
||||
continue
|
||||
if path.is_symlink():
|
||||
raise ValueError("Source snapshot refuses symlinks: " + str(relative))
|
||||
if path.is_dir():
|
||||
continue
|
||||
if not path.is_file():
|
||||
raise ValueError("Missing or non-regular source file: " + str(relative))
|
||||
size = path.stat().st_size
|
||||
total += size
|
||||
count += 1
|
||||
if size > 16 * 1024 * 1024 or total > 256 * 1024 * 1024 or count > 10000:
|
||||
raise ValueError("Source snapshot exceeds the guest archive bounds")
|
||||
archive.add(path, arcname=relative.as_posix(), recursive=False)
|
||||
return hashlib.sha256(destination.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def execute(args):
|
||||
if not sys.platform.startswith("linux") or os.geteuid() != 0:
|
||||
raise ValueError("Run as root on the Proxmox host; --dry-run works without Proxmox")
|
||||
@@ -203,32 +161,21 @@ def execute(args):
|
||||
def deploy(args, archive, sha):
|
||||
ctid = args.ctid or int(json.loads(run(["pvesh", "get", "/cluster/nextid", "--output-format", "json"], capture=True).stdout))
|
||||
status = run(["pct", "status", ctid], capture=True, check=False)
|
||||
if args.action == "install":
|
||||
if status.returncode == 0:
|
||||
raise ValueError("CT already exists; refusing to overwrite it. Use update for a managed installation.")
|
||||
run(["pveam", "update"])
|
||||
template = args.template
|
||||
if not template:
|
||||
available = run(["pveam", "available", "--section", "system"], capture=True).stdout
|
||||
candidates = [word for word in available.split() if TEMPLATE.fullmatch(word)]
|
||||
if not candidates:
|
||||
raise ValueError("No Debian 13 amd64 template found; pass --template explicitly")
|
||||
template = sorted(candidates, key=lambda s: [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", s)])[-1]
|
||||
path = run(["pvesm", "path", f"{args.template_storage}:vztmpl/{template}"], capture=True, check=False)
|
||||
if path.returncode or not Path(path.stdout.strip()).is_file():
|
||||
run(["pveam", "download", args.template_storage, template])
|
||||
run(create_command(args, ctid, template))
|
||||
else:
|
||||
if status.returncode:
|
||||
raise ValueError("Cannot access selected CT")
|
||||
# Reject foreign CTs before starting them or installing packages.
|
||||
metadata = json.loads(run(["pct", "exec", ctid, "--", "cat", "/etc/finaltoken/install.json"], capture=True).stdout) if "running" in status.stdout else None
|
||||
if metadata is None:
|
||||
raise ValueError("Start the existing managed CT before updating; stopped CTs are not modified")
|
||||
if metadata.get("installer") != "finaltoken-proxmox-v1" or metadata.get("ctid") != ctid:
|
||||
raise ValueError("Selected CT is not managed by this installer")
|
||||
if args.action == "install":
|
||||
run(["pct", "start", ctid])
|
||||
if status.returncode == 0:
|
||||
raise ValueError("CT already exists; run finaltoken-update inside that container")
|
||||
run(["pveam", "update"])
|
||||
template = args.template
|
||||
if not template:
|
||||
available = run(["pveam", "available", "--section", "system"], capture=True).stdout
|
||||
candidates = [word for word in available.split() if TEMPLATE.fullmatch(word)]
|
||||
if not candidates:
|
||||
raise ValueError("No Debian 13 amd64 template found; pass --template explicitly")
|
||||
template = sorted(candidates, key=lambda s: [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", s)])[-1]
|
||||
path = run(["pvesm", "path", f"{args.template_storage}:vztmpl/{template}"], capture=True, check=False)
|
||||
if path.returncode or not Path(path.stdout.strip()).is_file():
|
||||
run(["pveam", "download", args.template_storage, template])
|
||||
run(create_command(args, ctid, template))
|
||||
run(["pct", "start", ctid])
|
||||
for _ in range(30):
|
||||
if run(["pct", "exec", ctid, "--", "test", "-d", "/run/systemd/system"], capture=True, check=False).returncode == 0:
|
||||
break
|
||||
@@ -242,7 +189,7 @@ def deploy(args, archive, sha):
|
||||
tmp = Path(tmp)
|
||||
manifest = {"installer": "finaltoken-proxmox-v1", "ctid": ctid, "action": args.action, "sourceSha256": sha}
|
||||
if args.action == "install":
|
||||
manifest.update(role=args.role, domain=args.domain, tls=args.tls, machineId=args.machine_id or f"lxc_{ctid}",
|
||||
manifest.update(role=args.role, domain=args.domain, network="external", machineId=args.machine_id or f"lxc_{ctid}",
|
||||
timezone=args.timezone, providers=args.providers, serverUrl=args.server_url,
|
||||
emails={p: getattr(args, p + "_email") or args.email for p in args.providers})
|
||||
if args.role == "worker":
|
||||
@@ -274,7 +221,7 @@ def main(argv=None):
|
||||
print("Unprivileged Debian 13 amd64; build NativeAOT inside CT; preserve config, keys, history and CLI profiles.")
|
||||
if args.action == "install":
|
||||
print(f"Root storage={args.storage}; template storage={args.template_storage}; bridge={args.bridge}; IP={args.ip}")
|
||||
print(f"Dashboard={('https://' + args.domain) if args.domain else args.server_url}; TLS={args.tls}")
|
||||
print(f"Dashboard={('https://' + args.domain) if args.domain else args.server_url}; backend=HTTP :5187 behind your existing reverse proxy")
|
||||
return 0
|
||||
execute(args)
|
||||
return 0
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Allowlisted application source shared by CT creation and in-container updates."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tarfile
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from source_policy import is_private_path
|
||||
|
||||
PROJECTS = ("FinalToken.Core", "FinalToken.Fleet", "FinalToken.Web", "FinalToken.Worker")
|
||||
|
||||
|
||||
def snapshot(source, destination):
|
||||
"""Allowlist source inputs, including uncommitted changes, excluding secrets, outputs and symlinks."""
|
||||
files = [source / n for n in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE", "tools/lxc_update.py")]
|
||||
for project in PROJECTS:
|
||||
directory = source / "src" / project
|
||||
if directory.is_symlink() or directory.resolve() != directory.absolute():
|
||||
raise ValueError("Source snapshot refuses a symlinked project or parent: " + project)
|
||||
files.extend(directory.rglob("*"))
|
||||
total, count = 0, 0
|
||||
with tarfile.open(destination, "w:gz") as archive:
|
||||
for path in sorted(set(files)):
|
||||
relative = path.relative_to(source)
|
||||
if is_private_path(relative):
|
||||
continue # .gitignore does not apply to tarfile: do not copy local deployment data.
|
||||
if any(p in ("bin", "obj", "artifacts", ".git", "node_modules") or p.startswith(".") for p in relative.parts):
|
||||
continue
|
||||
if path.is_symlink() or path.resolve() != path.absolute():
|
||||
raise ValueError("Source snapshot refuses symlinks: " + str(relative))
|
||||
if path.is_dir():
|
||||
continue
|
||||
if not path.is_file():
|
||||
raise ValueError("Missing or non-regular source file: " + str(relative))
|
||||
size = path.stat().st_size
|
||||
total += size
|
||||
count += 1
|
||||
if size > 16 * 1024 * 1024 or total > 256 * 1024 * 1024 or count > 10000:
|
||||
raise ValueError("Source snapshot exceeds the guest archive bounds")
|
||||
archive.add(path, arcname=relative.as_posix(), recursive=False)
|
||||
return hashlib.sha256(destination.read_bytes()).hexdigest()
|
||||
+136
-43
@@ -83,10 +83,10 @@ class HostTests(unittest.TestCase):
|
||||
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_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:
|
||||
@@ -101,7 +101,8 @@ class HostTests(unittest.TestCase):
|
||||
(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"):
|
||||
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)
|
||||
@@ -125,45 +126,13 @@ class HostTests(unittest.TestCase):
|
||||
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"):
|
||||
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_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):
|
||||
@@ -209,6 +178,127 @@ class HostTests(unittest.TestCase):
|
||||
|
||||
|
||||
class GuestTests(unittest.TestCase):
|
||||
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", "domain": "usage.example.test", "tls": "acme"})
|
||||
environment = (guest.ETC / "server.env").read_text()
|
||||
self.assertTrue("ASPNETCORE_URLS=http://0.0.0.0:5187" in environment)
|
||||
self.assertIn("FINALTOKEN_PUBLIC_ORIGIN=https://usage.example.test", 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_codex_npm_install_creates_the_configured_launcher(self):
|
||||
node, npm = shutil.which("node"), shutil.which("npm")
|
||||
if not node or not npm:
|
||||
@@ -269,7 +359,7 @@ class GuestTests(unittest.TestCase):
|
||||
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",
|
||||
"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"
|
||||
@@ -284,7 +374,7 @@ class GuestTests(unittest.TestCase):
|
||||
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()):
|
||||
patch.object(guest, "install_updater"), 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()
|
||||
@@ -307,6 +397,9 @@ class GuestTests(unittest.TestCase):
|
||||
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):
|
||||
@@ -345,7 +438,7 @@ class GuestTests(unittest.TestCase):
|
||||
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")):
|
||||
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"))
|
||||
@@ -365,7 +458,7 @@ class GuestTests(unittest.TestCase):
|
||||
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())
|
||||
self.assertFalse((guest.ETC / "Caddyfile").exists())
|
||||
|
||||
def test_units_use_profile_owner_and_kill_child_processes(self):
|
||||
worker = guest.service_unit("worker")
|
||||
|
||||
+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