tools: update inside LXC and use the existing proxy (#22)

Use the operator's HTTPS proxy with a private backend on port 5187. Limit the Proxmox host script to container creation and install a self-updating command inside the LXC. Preserve keys/history during legacy proxy migration and keep root updater code isolated from unprivileged build output.

Closes #21
This commit was merged in pull request #22.
This commit is contained in:
2026-11-15 13:06:04 +01:00
parent c75446008c
commit 43caf1e412
20 changed files with 657 additions and 608 deletions
+71 -40
View File
@@ -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")),
@@ -232,6 +200,17 @@ def configure(meta, enrollment_key=None):
def build(archive, meta):
# The updater runs as root: capture it from the verified, root-owned archive,
# never from source or output writable by the unprivileged compiler.
with tarfile.open(archive, "r:gz") as bundle:
try:
member = bundle.getmember("tools/lxc_update.py")
except KeyError:
raise ValueError("Source archive has no updater script") from None
if not member.isfile() or member.size > 16 * 1024 * 1024:
raise ValueError("Source archive has an invalid updater script")
with bundle.extractfile(member) as stream:
trusted_updater = stream.read().decode("utf-8")
entry = user("finaltoken-build", BUILD)
temporary = Path(tempfile.mkdtemp(prefix="build-", dir=BUILD))
try:
@@ -253,7 +232,7 @@ def build(archive, meta):
destination.parent.mkdir(parents=True, exist_ok=True)
APP.chmod(0o755)
destination.parent.chmod(0o755)
shutil.copytree(release, destination)
shutil.copytree(release, destination, ignore=shutil.ignore_patterns("finaltoken-update"))
destination.chmod(0o755)
for path in destination.rglob("*"):
path.chmod(0o755 if path.is_dir() else 0o644)
@@ -267,6 +246,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)
atomic(destination / "finaltoken-update", trusted_updater, 0o755)
return destination
finally:
# Only this invocation's fresh build directory, never profiles, state or previous releases.
@@ -285,7 +265,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 +394,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 +413,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)