Files
FinalToken/tools/proxmox/guest.py
T
Florian Schmidt afa6d83f2a
agent-review agent review: pass
tools: register the updater in the normal command path
Install the container updater under /usr/local/bin so shells without sbin can discover it. Print the absolute installed path as a fallback for custom environments and retain existing managed links. Reproduce command discovery through a real Bash lookup before fixing registration.

Refs #23
2026-11-15 15:05:16 +01:00

418 lines
20 KiB
Python

"""Private guest provisioner, invoked by host.py inside the selected LXC. Not a host entry point."""
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import pwd
import re
import secrets
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.request
import uuid
INSTALLER = "finaltoken-proxmox-v1"
ETC = Path("/etc/finaltoken")
APP = Path("/opt/finaltoken")
BUILD = Path("/var/cache/finaltoken-build")
SERVER_HOME = Path("/var/lib/finaltoken-server")
WORKER_HOME = Path("/var/lib/finaltoken-worker")
UPDATER = Path("/usr/local/bin/finaltoken-update")
SYSTEMD = Path("/etc/systemd/system")
def run(command, *, check=True, capture=False, cwd=None):
return subprocess.run([str(a) for a in command], check=check, text=True,
stdout=subprocess.PIPE if capture else None, stderr=subprocess.PIPE if capture else None, cwd=cwd)
def atomic(path, data, mode=0o600, *, once=False):
"""D5: same-directory replace; existing operator configuration is never overwritten."""
if once and path.exists():
return False
path.parent.mkdir(parents=True, exist_ok=True)
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", newline="") as stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
return True
def json_file(path, data, *, once=False):
return atomic(path, json.dumps(data, indent=2) + "\n", once=once)
def unpack(archive_path, destination):
"""No links, devices, absolute paths, traversal or unbounded archive expansion."""
destination.mkdir(parents=True, exist_ok=True)
with tarfile.open(archive_path, "r:gz") as archive:
members = archive.getmembers()
if len(members) > 10000 or sum(m.size for m in members) > 256 * 1024 * 1024:
raise ValueError("Source archive exceeds its metadata/size bound")
for member in members:
path = PurePosixPath(member.name)
if path.is_absolute() or ".." in path.parts or not member.isfile() or member.size > 16 * 1024 * 1024:
raise ValueError("Source archive has an unsafe entry")
target = destination.joinpath(*path.parts)
target.parent.mkdir(parents=True, exist_ok=True)
with archive.extractfile(member) as source, target.open("xb") as output:
shutil.copyfileobj(source, output)
target.chmod(0o644)
def user(name, home):
try:
entry = pwd.getpwnam(name)
if entry.pw_dir != str(home):
raise ValueError("Existing service user has an unexpected home: " + name)
except KeyError:
run(["useradd", "--system", "--create-home", "--home-dir", home, "--shell", "/bin/bash", "--user-group", name])
entry = pwd.getpwnam(name)
home.mkdir(parents=True, exist_ok=True)
os.chown(home, entry.pw_uid, entry.pw_gid)
home.chmod(0o750)
return entry
def as_user(name, home, command, cwd=None):
# Do not inherit host/root provider secrets, proxy overrides or build credentials.
return run(["runuser", "--user", name, "--", "env", "-i", "HOME=" + str(home),
"PATH=" + str(home / ".local/bin") + ":/usr/local/bin:/usr/bin:/bin",
"DOTNET_CLI_HOME=" + str(home), "DOTNET_CLI_TELEMETRY_OPTOUT=1", "DOTNET_NOLOGO=1", *command], cwd=cwd or home)
def packages(role, providers):
run(["apt-get", "update"])
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])
repository = Path("/etc/apt/sources.list.d/microsoft-prod.list")
if not repository.exists():
with tempfile.TemporaryDirectory(prefix="finaltoken-sdk-") as tmp:
package = Path(tmp) / "packages-microsoft-prod.deb"
run(["curl", "--fail", "--silent", "--show-error", "--location", "--proto", "=https", "--tlsv1.2",
"https://packages.microsoft.com/config/debian/13/packages-microsoft-prod.deb", "--output", package])
run(["dpkg", "-i", package])
run(["apt-get", "update"])
run(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "dotnet-sdk-10.0"])
def official_clis(providers):
"""Install official clients as their own OS user; never run a login or read auth files."""
if "claude" in providers and not (WORKER_HOME / ".local/bin/claude").exists():
with tempfile.TemporaryDirectory(prefix="finaltoken-claude-") as tmp:
os.chmod(tmp, 0o755)
script = Path(tmp) / "install.sh"
run(["curl", "--fail", "--silent", "--show-error", "--location", "--proto", "=https", "--tlsv1.2",
"https://claude.ai/install.sh", "--output", script])
script.chmod(0o644)
as_user("finaltoken", WORKER_HOME, ["bash", str(script), "stable"])
if "codex" in providers and not (WORKER_HOME / ".local/bin/codex").exists():
as_user("finaltoken", WORKER_HOME, ["npm", "install", "--global", "--prefix", str(WORKER_HOME / ".local"), "@openai/codex@latest"])
for provider in providers:
as_user("finaltoken", WORKER_HOME, [str(WORKER_HOME / ".local/bin" / provider), "--version"])
def service_unit(role):
server = role == "server"
home = SERVER_HOME if server else WORKER_HOME
account = "finaltoken-server" if server else "finaltoken"
executable = APP / "current" / ("web/FinalToken.Web" if server else "worker/finaltoken-worker")
arguments = "" if server else " " + str(ETC / "worker.json")
return f"""[Unit]
Description=FinalToken {role}
Wants=network-online.target
After=network-online.target
[Service]
Type=exec
User={account}
Group={account}
WorkingDirectory={executable.parent}
EnvironmentFile={ETC}/{role}.env
Environment=HOME={home}
Environment=PATH={WORKER_HOME}/.local/bin:/usr/local/bin:/usr/bin:/bin
ExecStart={executable}{arguments}
Restart=on-failure
RestartSec=5
TimeoutStopSec=75
KillMode=control-group
UMask=0077
NoNewPrivileges=true
StandardOutput=null
StandardError=null
[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)
if role != "server":
user("finaltoken", WORKER_HOME)
keys_path = ETC / "transport-keys.json"
if not keys_path.exists():
json_file(keys_path, {"dashboard": secrets.token_hex(32), "worker": enrollment_key or secrets.token_hex(32)}, once=True)
keys = json.loads(keys_path.read_text(encoding="utf-8"))
if role != "worker":
accounts = [{"id": p, "provider": p.capitalize(), "label": p.capitalize(), "expectedEmail": meta["emails"][p], "timeZone": meta["timezone"]}
for p in providers if meta["emails"].get(p)]
machines = [] if role == "server" else [{"id": meta["machineId"], "label": f"LXC {meta['ctid']}", "osUser": "finaltoken",
"profiles": [{"id": p, "accountId": p} for p in providers]}]
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://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)
atomic(SYSTEMD / "finaltoken-server.service", service_unit("server"), 0o644, once=True)
if role != "server":
profiles = [{"id": p, "provider": p.capitalize(), "expectedEmail": meta["emails"][p],
"configDirectory": str(WORKER_HOME / (".claude" if p == "claude" else ".codex")),
"dataDirectory": str(WORKER_HOME / "history" / p), "cliPath": str(WORKER_HOME / ".local/bin" / p)} for p in providers]
json_file(ETC / "worker.json", {"machineId": meta["machineId"], "serverUrl": "http://127.0.0.1:5187" if role == "both" else meta["serverUrl"],
"stateDirectory": str(WORKER_HOME / "collector"), "profiles": profiles}, once=True)
atomic(ETC / "worker.env", "FINALTOKEN_WORKER_KEY=" + keys["worker"] + "\n", once=True)
atomic(SYSTEMD / "finaltoken-worker.service", service_unit("worker"), 0o644, once=True)
# systemd reads env files as root. Only the intended service user can read its JSON config.
for filename, account in (("server.json", "finaltoken-server"), ("worker.json", "finaltoken")):
path = ETC / filename
if path.exists():
path.chmod(0o640)
os.chown(path, 0, pwd.getpwnam(account).pw_gid)
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:
source = temporary / "src"
unpack(archive, source)
for path in [temporary, *temporary.rglob("*")]:
os.chown(path, entry.pw_uid, entry.pw_gid)
release = temporary / "release"
for project, output in (("FinalToken.Web", "web"), ("FinalToken.Worker", "worker")):
if meta["role"] == "server" and output == "worker" or meta["role"] == "worker" and output == "web":
continue
# D1: build on target Linux with NativeAOT, never copy a Windows executable into LXC.
as_user("finaltoken-build", BUILD, ["dotnet", "publish", str(source / "src" / project / (project + ".csproj")),
"-c", "Release", "-r", "linux-x64", "--self-contained", "true", "-p:PublishAot=true", "-o", str(release / output)], cwd=source)
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")
destination = APP / "releases" / (meta["sourceSha256"][:16] + "-" + uuid.uuid4().hex[:8])
destination.parent.mkdir(parents=True, exist_ok=True)
APP.chmod(0o755)
destination.parent.chmod(0o755)
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)
for executable in (destination / "web/FinalToken.Web", destination / "worker/finaltoken-worker"):
wanted = meta["role"] != ("worker" if executable.name == "FinalToken.Web" else "server")
if wanted:
if not executable.is_file():
raise ValueError("Native build did not produce its expected executable")
with executable.open("rb") as stream:
header = stream.read(20)
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.
shutil.rmtree(temporary)
def switch(release):
if release.parent.resolve() != (APP / "releases").resolve() or not release.is_dir():
raise ValueError("Release must be an existing direct child of the releases directory")
pending = APP / (".current-" + uuid.uuid4().hex)
try:
pending.symlink_to(release, target_is_directory=True)
os.replace(pending, APP / "current")
finally:
pending.unlink(missing_ok=True)
def units(role):
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):
for _ in range(20):
live = all(run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0 for s in services)
if live and "finaltoken-server.service" in services:
try:
request = urllib.request.Request("http://127.0.0.1:5187/", headers={"Host": meta["domain"]})
with urllib.request.urlopen(request, timeout=2) as response:
live = response.status == 200
except OSError:
live = False
if live:
# Catch immediate startup failures. Remote provider login is deliberately not a health probe.
time.sleep(2)
return all(run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0 for s in services)
time.sleep(1)
return False
def activate(release, meta, first):
current = APP / "current"
previous = current.resolve() if current.is_symlink() else None
services = units(meta["role"])
active = services if first else [s for s in services if run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0]
try:
switch(release)
run(["systemctl", "daemon-reload"])
if first:
run(["systemctl", "enable", *services])
if active:
run(["systemctl", "restart", *active])
if not healthy(active, meta):
raise ValueError("New release did not pass local service/HTTP health checks")
except Exception:
if previous is not None:
switch(previous)
if active:
run(["systemctl", "restart", *active], check=False)
print("Activation failed; previous binary release restored. State/configuration were not rewound.", file=sys.stderr)
else:
run(["systemctl", "disable", "--now", *services], check=False)
raise
def provision(manifest, archive):
if os.geteuid() != 0 or os.uname().machine != "x86_64":
raise ValueError("Guest setup requires root in a Linux x86_64 CT")
os_release = Path("/etc/os-release").read_text(encoding="utf-8")
if 'ID=debian' not in os_release or 'VERSION_ID="13"' not in os_release:
raise ValueError("Only Debian 13 amd64 guests are supported")
if manifest.get("installer") != INSTALLER or manifest.get("action") not in ("install", "update"):
raise ValueError("Unsupported deployment manifest")
with archive.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
if digest != manifest.get("sourceSha256"):
raise ValueError("Uploaded source checksum mismatch")
marker = ETC / "install.json"
if manifest["action"] == "update":
meta = json.loads(marker.read_text(encoding="utf-8"))
if meta.get("installer") != INSTALLER or meta.get("ctid") != manifest["ctid"]:
raise ValueError("Guest marker does not match selected CT")
meta["sourceSha256"] = digest
else:
if marker.exists():
raise ValueError("An install marker already exists; use update")
meta = {k: v for k, v in manifest.items() if k != "workerKey"}
meta["installed"] = False
json_file(ETC / "transport-keys.json", {"dashboard": secrets.token_hex(32),
"worker": manifest.get("workerKey") or secrets.token_hex(32)}, once=True)
json_file(marker, meta, once=True) # Partial installs can be resumed through update.
first = not meta.get("installed", False)
packages(meta["role"], meta["providers"])
if first:
configure(meta, manifest.get("workerKey"))
if meta["role"] != "server":
official_clis(meta["providers"])
release = build(archive, meta)
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).")
print("Official CLI login still requires your browser authorization. No provider credentials were copied.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--archive", type=Path, required=True)
args = parser.parse_args()
try:
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. Retry finaltoken-update inside the container.", file=sys.stderr)
sys.exit(1)