tools: update inside LXC and use the existing proxy
agent-review agent review: fail

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:
Florian Schmidt
2026-11-15 12:49:53 +01:00
parent c75446008c
commit 7b70c7a0fa
20 changed files with 617 additions and 607 deletions
+60 -39
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")),
@@ -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)