core: publish self-hosted weekly dashboard and Proxmox deployment (#20)

Reuse existing weekly/reset analysis in an authenticated dashboard and local official CLI workers. Add safe Proxmox installation and updates, account-attributed history, and MIT distribution. Provider credentials stay owned by each CLI.

Closes #19
This commit was merged in pull request #20.
This commit is contained in:
2026-11-15 11:24:55 +01:00
parent c02829e2e1
commit c75446008c
59 changed files with 4208 additions and 30 deletions
+2
View File
@@ -0,0 +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`.
+386
View File
@@ -0,0 +1,386 @@
"""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 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")
PROXY_HOME = Path("/var/lib/finaltoken-proxy")
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") 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 = ["ca-certificates", "curl", "clang", "zlib1g-dev", "libicu-dev", "libssl-dev", "tzdata"]
if role != "worker":
wanted.append("caddy")
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 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"
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://127.0.0.1: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")),
"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):
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)
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)
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", "finaltoken-proxy.service"] if role != "worker" else []) + (["finaltoken-worker.service"] if role != "server" else [])
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["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. Inspect services; retry with host update.", file=sys.stderr)
sys.exit(1)
+290
View File
@@ -0,0 +1,290 @@
"""Create/update an unprivileged Debian 13 LXC from a local FinalToken source snapshot."""
import argparse
import hashlib
import ipaddress
import json
import os
from pathlib import Path
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
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")
def run(command, *, capture=False, check=True):
command = [str(a) for a in command]
if command[:2] == ["pct", "exec"]:
# Proxmox defaults differ between versions; never forward the host's secret environment.
command[3:3] = ["--keep-env", "0"]
return subprocess.run(command, check=check, text=True,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.PIPE if capture else None)
def identifier(value):
if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,63}", value):
raise ValueError("Machine id must start with a letter and contain only letters, digits and underscores")
return value
def domain_name(value):
if len(value) > 253 or not all(re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", p) for p in value.split(".")) or "." not in value:
raise ValueError("Domain must be a DNS name without a scheme, port, path or shell syntax")
return value.lower()
def server_url(value):
url = urlsplit(value)
if url.scheme != "https" or not url.hostname or url.username or url.password or url.path not in ("", "/") or url.query or url.fragment:
raise ValueError("Remote server URL must be an HTTPS origin")
_ = url.port
return value.rstrip("/")
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("--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")
p.add_argument("--template", help="Optional Debian 13 amd64 standard template filename")
p.add_argument("--bridge", default="vmbr0")
p.add_argument("--ip", default="dhcp", help="dhcp or static IPv4 CIDR")
p.add_argument("--gateway")
p.add_argument("--vlan", type=int)
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("--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")
p.add_argument("--providers", default="claude,codex")
p.add_argument("--machine-id", help="Default: lxc_<ctid>")
p.add_argument("--timezone", default="UTC")
p.add_argument("--server-url", help="Existing HTTPS dashboard, for worker-only install")
p.add_argument("--worker-key-file", type=Path, help="Root-readable enrollment key file; never pass the key as an argument")
p.add_argument("--dry-run", action="store_true", help="Print validated plan; do not run Proxmox or create files")
return p
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):
raise ValueError("Install requires valid --storage, template-storage and bridge identifiers")
if args.memory < 4096 or args.cores < 1 or args.disk < 12:
raise ValueError("Require memory >=4096 MiB, cores >=1 and disk >=12 GiB for native builds")
if args.vlan is not None and not 1 <= args.vlan <= 4094:
raise ValueError("VLAN must be in 1..4094")
if args.ip != "dhcp":
if not isinstance(ipaddress.ip_interface(args.ip), ipaddress.IPv4Interface):
raise ValueError("Use an IPv4 CIDR")
if not args.gateway:
raise ValueError("Static IP requires --gateway")
if args.gateway:
if args.ip == "dhcp" or not isinstance(ipaddress.ip_address(args.gateway), ipaddress.IPv4Address):
raise ValueError("Gateway is only supported with static IPv4")
if args.template and not TEMPLATE.fullmatch(args.template):
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")
args.domain = domain_name(args.domain)
else:
if not args.server_url or not args.worker_key_file:
raise ValueError("Worker-only install requires --server-url and --worker-key-file")
args.server_url = server_url(args.server_url)
args.providers = args.providers.split(",")
if not args.providers or len(set(args.providers)) != len(args.providers) or any(p not in ("claude", "codex") for p in args.providers):
raise ValueError("Providers must be claude, codex, or claude,codex")
for provider in args.providers:
email = getattr(args, provider + "_email") or args.email
if args.role != "server" and (not email or not re.fullmatch(r"[^\s@\x00-\x1f]+@[^\s@\x00-\x1f]+", email) or len(email) > 320):
raise ValueError("Worker/both requires --email or a provider-specific email for each selected provider")
if args.machine_id:
identifier(args.machine_id)
if not re.fullmatch(r"[A-Za-z0-9_+/-]{1,100}", args.timezone) or ".." in args.timezone:
raise ValueError("Invalid timezone id")
if args.role == "worker" and not args.dry_run:
key = args.worker_key_file.read_text(encoding="utf-8").strip()
if not re.fullmatch(r"[A-Za-z0-9_-]{32,512}", key):
raise ValueError("Enrollment file must contain one 32+ character transport key")
args.enrollment_key = key
def create_command(args, ctid, template):
network = f"name=eth0,bridge={args.bridge},ip={args.ip},type=veth,firewall=1"
if args.gateway:
network += ",gw=" + args.gateway
if args.vlan:
network += ",tag=" + str(args.vlan)
return ["pct", "create", str(ctid), f"{args.template_storage}:vztmpl/{template}",
"--hostname", f"finaltoken-{ctid}", "--ostype", "debian", "--arch", "amd64",
"--unprivileged", "1", "--onboot", "1", "--memory", str(args.memory), "--swap", "2048",
"--cores", str(args.cores), "--rootfs", f"{args.storage}:{args.disk}", "--net0", network,
"--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")
for program in ("pct", "pvesh", "pveam", "pvesm"):
if not shutil.which(program):
raise ValueError("Missing Proxmox host command: " + program)
import fcntl
with open("/run/lock/finaltoken-proxmox.lock", "w", encoding="utf-8") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
# Prepare and validate the complete source bundle before creating any CT.
with tempfile.TemporaryDirectory(prefix="finaltoken-source-") as directory:
archive = Path(directory) / "source.tar.gz"
sha = snapshot(args.source, archive)
deploy(args, archive, sha)
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])
for _ in range(30):
if run(["pct", "exec", ctid, "--", "test", "-d", "/run/systemd/system"], capture=True, check=False).returncode == 0:
break
time.sleep(1)
else:
raise ValueError("CT did not become ready; it was retained for inspection")
guest = Path(__file__).with_name("guest.py")
token = uuid.uuid4().hex
remote = "/tmp/finaltoken-" + token
with tempfile.TemporaryDirectory(prefix="finaltoken-proxmox-") as tmp:
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}",
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":
manifest["workerKey"] = args.enrollment_key
manifest_path = tmp / "manifest.json"
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
manifest_path.chmod(0o600)
# Only CT packages are changed. The Proxmox host package configuration is untouched.
run(["pct", "exec", ctid, "--", "apt-get", "update"])
run(["pct", "exec", ctid, "--", "env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "python3", "ca-certificates"])
try:
for local, suffix in ((guest, ".py"), (archive, ".tar.gz"), (manifest_path, ".json")):
run(["pct", "push", ctid, local, remote + suffix, "--perms", "0600"])
run(["pct", "exec", ctid, "--", "python3", remote + ".py", "--manifest", remote + ".json", "--archive", remote + ".tar.gz"])
finally:
run(["pct", "exec", ctid, "--", "rm", "-f", remote + ".py", remote + ".json", remote + ".tar.gz"], capture=True, check=False)
print(f"FinalToken {args.action} finished in CT {ctid}. Configuration and state are inside that CT.")
print(f"Inspect services: pct exec {ctid} -- systemctl status 'finaltoken-*'")
print(f"Read dashboard access key, when server installed: pct exec {ctid} -- cat /etc/finaltoken/dashboard-key")
print("No container, profile or history is ever automatically deleted on failure.")
def main(argv=None):
args = parser().parse_args(argv)
validate(args)
if args.dry_run:
role = args.role or "preserve installed role"
print(f"Plan: {args.action} CT {args.ctid or '<next free id>'}; role={role}; source={args.source}")
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}")
return 0
execute(args)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except (ValueError, OSError, subprocess.CalledProcessError) as error:
# Never dump captured command output or the manifest (contains service keys).
print("FinalToken setup failed: " + (str(error) if isinstance(error, ValueError) else type(error).__name__), file=sys.stderr)
print("The CT and existing data were retained. Inspect it before retrying.", file=sys.stderr)
sys.exit(1)
+442
View File
@@ -0,0 +1,442 @@
"""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_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_https_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", "http://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_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_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"):
(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"):
(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):
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_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", "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, "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))
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_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"), ("PROXY_HOME", "proxy"), ("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.assertIn("tls internal", (guest.ETC / "Caddyfile").read_text())
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()
+189
View File
@@ -0,0 +1,189 @@
"""Real local Git/Bash updater checks. No network, Proxmox, package or service changes."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
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):
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.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"]
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 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 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)
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_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_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_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_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_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_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())
if __name__ == "__main__":
unittest.main()