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:
@@ -0,0 +1,171 @@
|
||||
"""Read-only publication check. Reports paths/pattern names, never matching secret values."""
|
||||
import argparse
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from source_policy import is_private_path as sensitive_path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LIMIT = 2 * 1024 * 1024
|
||||
PATTERNS = (
|
||||
("private key", re.compile(rb"-----BEGIN (?:RSA |EC |OPENSSH |DSA |ENCRYPTED )?PRIVATE KEY-----")),
|
||||
("provider token", re.compile(rb"\bsk-(?:ant-|proj-|svcacct-)[A-Za-z0-9_-]{24,}")),
|
||||
("Git hosting token", re.compile(rb"\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})")),
|
||||
("credential in URL", re.compile(rb"https?://[^\s/:@]+:[^\s/@]+@")),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Finding:
|
||||
path: str
|
||||
kind: str
|
||||
line: int = 0
|
||||
|
||||
|
||||
def inspect(path, data):
|
||||
if b"\0" in data[:8192]:
|
||||
return []
|
||||
return [Finding(path, kind, data.count(b"\n", 0, match.start()) + 1)
|
||||
for kind, pattern in PATTERNS for match in pattern.finditer(data)]
|
||||
|
||||
|
||||
def git(root, *arguments, data=None):
|
||||
return subprocess.run(["git", *arguments], cwd=root, input=data, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, check=True).stdout
|
||||
|
||||
|
||||
def working_tree(root):
|
||||
names = set(git(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard").decode("utf-8").split("\0")) - {""}
|
||||
findings, skipped, scanned = [], [], 0
|
||||
for name in sorted(names):
|
||||
path = root / name
|
||||
if sensitive_path(name):
|
||||
findings.append(Finding(name, "local configuration/credential/runtime filename"))
|
||||
elif path.is_symlink() or not path.resolve().is_relative_to(root.resolve()):
|
||||
findings.append(Finding(name, "symlink/outside source tree"))
|
||||
elif not path.exists():
|
||||
continue # Removed tracked file; history is checked separately.
|
||||
elif not path.is_file() or path.stat().st_size > LIMIT:
|
||||
skipped.append(name)
|
||||
else:
|
||||
data = path.read_bytes()
|
||||
if b"\0" in data[:8192]:
|
||||
skipped.append(name)
|
||||
continue
|
||||
findings.extend(inspect(name, data))
|
||||
scanned += 1
|
||||
staged, staged_count, staged_skipped = index(root)
|
||||
return findings + staged, scanned + staged_count, skipped + staged_skipped
|
||||
|
||||
|
||||
def index(root):
|
||||
"""Audit actual index blobs, not their potentially different working copies. No staging changes."""
|
||||
records = git(root, "ls-files", "--stage", "-z").decode("utf-8").split("\0")
|
||||
findings, skipped, scanned = [], [], 0
|
||||
for record in filter(None, records):
|
||||
metadata, name = record.split("\t", 1)
|
||||
mode, oid, stage = metadata.split()
|
||||
label = "index:" + name
|
||||
if sensitive_path(name):
|
||||
findings.append(Finding(label, "staged local configuration/credential/runtime filename"))
|
||||
elif stage != "0" or mode not in ("100644", "100755"):
|
||||
findings.append(Finding(label, "unmerged index, symlink or submodule needs review"))
|
||||
elif int(git(root, "cat-file", "-s", oid)) > LIMIT:
|
||||
skipped.append(label)
|
||||
else:
|
||||
data = git(root, "cat-file", "blob", oid)
|
||||
if b"\0" in data[:8192]:
|
||||
skipped.append(label)
|
||||
else:
|
||||
findings.extend(inspect(label, data))
|
||||
scanned += 1
|
||||
return findings, scanned, skipped
|
||||
|
||||
|
||||
def historical_private_paths(root):
|
||||
# rev-list --objects gives only one name hint per blob. A blob can have been
|
||||
# renamed/copied under a private filename in another tree without changing its id.
|
||||
private = {}
|
||||
for commit in git(root, "rev-list", "--all").decode("ascii").splitlines():
|
||||
for record in git(root, "ls-tree", "-r", "-z", "--full-tree", commit).decode("utf-8").split("\0"):
|
||||
if not record:
|
||||
continue
|
||||
metadata, name = record.split("\t", 1)
|
||||
if sensitive_path(name):
|
||||
private.setdefault(metadata.split()[2], set()).add(name)
|
||||
return private
|
||||
|
||||
|
||||
def history(root):
|
||||
private = historical_private_paths(root)
|
||||
objects = {}
|
||||
for entry in git(root, "rev-list", "--objects", "--all").decode("utf-8").splitlines():
|
||||
oid, _, name = entry.partition(" ")
|
||||
objects[oid] = name
|
||||
findings, skipped, scanned = [], [], 0
|
||||
metadata = git(root, "cat-file", "--batch-check", data="".join(o + "\n" for o in objects).encode()).decode("ascii")
|
||||
candidates = []
|
||||
for row in metadata.splitlines():
|
||||
oid, kind, size = row.split()
|
||||
if kind not in ("blob", "commit", "tag"):
|
||||
continue
|
||||
name = objects[oid] or "<" + kind + ">"
|
||||
label = "history:" + oid[:12] + ":" + name
|
||||
if oid in private or sensitive_path(name):
|
||||
findings.extend(Finding("history:" + oid[:12] + ":" + p, "historical local configuration/credential/runtime filename")
|
||||
for p in sorted(private.get(oid, {name})))
|
||||
elif int(size) > LIMIT:
|
||||
skipped.append(label)
|
||||
else:
|
||||
candidates.append((oid, label))
|
||||
# One batch process avoids starting Git separately for every historical source blob.
|
||||
with subprocess.Popen(["git", "cat-file", "--batch"], cwd=root, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL) as process:
|
||||
for oid, label in candidates:
|
||||
process.stdin.write((oid + "\n").encode())
|
||||
process.stdin.flush()
|
||||
header = process.stdout.readline().split()
|
||||
if len(header) != 3 or header[1] not in (b"blob", b"commit", b"tag"):
|
||||
raise ValueError("Unexpected Git object response")
|
||||
data = process.stdout.read(int(header[2]))
|
||||
if process.stdout.read(1) != b"\n":
|
||||
raise ValueError("Truncated Git object response")
|
||||
if b"\0" in data[:8192]:
|
||||
skipped.append(label)
|
||||
else:
|
||||
findings.extend(inspect(label, data))
|
||||
scanned += 1
|
||||
process.stdin.close()
|
||||
if process.wait() != 0:
|
||||
raise ValueError("Git object read failed")
|
||||
return findings, scanned, skipped
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--history", action="store_true", help="Also inspect reachable Git source, commit and tag text")
|
||||
args = parser.parse_args(argv)
|
||||
findings, count, skipped = working_tree(ROOT)
|
||||
print(f"Worktree/index: {count} text versions scanned; {len(skipped)} binary/oversized versions skipped.")
|
||||
if args.history:
|
||||
old, count, old_skipped = history(ROOT)
|
||||
findings.extend(old)
|
||||
skipped.extend(old_skipped)
|
||||
print(f"Reachable history: {count} text objects; {len(old_skipped)} binary/oversized objects skipped.")
|
||||
print("Git author/committer identities remain unchanged; inspect them before publication.")
|
||||
for item in findings:
|
||||
print(f"{item.path}:{item.line}: {item.kind}")
|
||||
for path in skipped:
|
||||
print("Not content-scanned: " + path)
|
||||
print(f"Pattern findings: {len(findings)}. This targeted check cannot prove absence of arbitrary secrets.")
|
||||
return 1 if findings else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (OSError, ValueError, subprocess.CalledProcessError):
|
||||
print("Publication check could not complete; no source/credential values are printed.", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
@@ -10,7 +10,7 @@ import sys
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
|
||||
SKIP = {".git", "bin", "obj", ".artifacts", "node_modules"}
|
||||
SKIP = {".git", "bin", "obj", ".artifacts", "artifacts", "node_modules"}
|
||||
IDENTIFIER = re.compile(r"\b[RD][0-9]+\b")
|
||||
LINK = re.compile(r"!?\[[^\]\n]*\]\((<[^>\n]+>|[^()\s]*(?:\([^()\s]*\)[^()\s]*)*)(?:\s+[\"'][^\n]*?[\"'])?\)")
|
||||
REFERENCE = re.compile(r"^\s{0,3}\[[^\]]+\]:\s*(<[^>]+>|\S+)")
|
||||
|
||||
@@ -69,7 +69,7 @@ class DocumentationCheck(unittest.TestCase):
|
||||
self.assertEqual(["notes.md:4: missing anchor: #hidden"], check(self.root))
|
||||
|
||||
def test_excluded_trees(self):
|
||||
for directory in (".git", "bin", "obj", ".artifacts", "node_modules"):
|
||||
for directory in (".git", "bin", "obj", ".artifacts", "artifacts", "node_modules"):
|
||||
self.write(f"{directory}/notes.md", "R99 [Gone](gone.md)\n")
|
||||
self.write("nested/.git", "gitdir: elsewhere\n")
|
||||
self.write("nested/notes.md", "R99\n")
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run from a dedicated trusted clone on the Proxmox host. Always enter the fetched installer.
|
||||
set -euo pipefail
|
||||
set +x
|
||||
|
||||
fail() { printf '%s\n' "FinalToken update: $*" >&2; exit 1; }
|
||||
usage() { printf '%s\n' 'Usage: bash /path/to/FinalToken/tools/proxmox-update.sh CTID [--dry-run]'; }
|
||||
|
||||
if [[ ${1:-} == --help || ${1:-} == -h ]]; then
|
||||
usage
|
||||
exit 0
|
||||
fi
|
||||
if [[ $# -lt 1 || $# -gt 2 || ! $1 =~ ^[1-9][0-9]{2,8}$ || ( $# == 2 && $2 != --dry-run ) ]]; then
|
||||
usage >&2
|
||||
exit 2
|
||||
fi
|
||||
ctid=$1
|
||||
dry_run=${2:-}
|
||||
source_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)
|
||||
for program in git bash; do
|
||||
command -v "$program" >/dev/null || fail "Missing host command: $program"
|
||||
done
|
||||
|
||||
top=$(git -C "$source_dir" rev-parse --show-toplevel 2>/dev/null) || fail 'Use a dedicated Git clone of FinalToken.'
|
||||
[[ $(cd -- "$top" && pwd -P) == "$source_dir" ]] || fail 'Installer must be at the root of its own Git checkout.'
|
||||
git -C "$source_dir" symbolic-ref --quiet HEAD >/dev/null 2>&1 || fail 'Detached checkout; select the published branch first.'
|
||||
git -C "$source_dir" rev-parse --verify '@{upstream}' >/dev/null 2>&1 || fail 'The checked-out branch needs a tracking upstream.'
|
||||
|
||||
clean_checkout() {
|
||||
local changes
|
||||
changes=$(GIT_OPTIONAL_LOCKS=0 git -C "$source_dir" status --porcelain=v1 --untracked-files=all) || fail 'Cannot inspect checkout status.'
|
||||
[[ -z $changes ]] || fail 'Use a clean dedicated checkout; local tracked, staged or untracked changes were retained.'
|
||||
}
|
||||
clean_checkout
|
||||
|
||||
if [[ $dry_run == --dry-run ]]; then
|
||||
printf '%s\n' 'Plan: fast-forward the tracking branch, then deploy to the selected managed CT. No fetch or changes in dry-run.'
|
||||
exec bash "$source_dir/tools/proxmox.sh" update --ctid "$ctid" --source "$source_dir" --dry-run
|
||||
fi
|
||||
|
||||
command -v flock >/dev/null || fail 'Missing host command: flock (util-linux).'
|
||||
git_dir=$(git -C "$source_dir" rev-parse --absolute-git-dir)
|
||||
# Keep this checkout locked through the installer, in addition to host.py's deployment lock.
|
||||
exec 9>"$git_dir/finaltoken-proxmox-update.lock"
|
||||
flock -n 9 || fail 'Another update is using this checkout; wait for it to finish.'
|
||||
clean_checkout
|
||||
|
||||
printf '%s\n' 'Refreshing the published tracking branch (fast-forward only)...'
|
||||
# Git output can contain an operator-supplied credential URL. Never echo it or persist it.
|
||||
branch=$(git -C "$source_dir" symbolic-ref --quiet HEAD)
|
||||
remote=$(git -C "$source_dir" for-each-ref --format='%(upstream:remotename)' "$branch")
|
||||
[[ -n $remote && $remote != . ]] || fail 'Use a branch tracking a published remote, rather than another local branch.'
|
||||
if ! GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=Never git -C "$source_dir" fetch --no-tags --no-recurse-submodules -- "$remote" >/dev/null 2>&1; then
|
||||
fail 'Source fetch failed; check Git access/network. No deployment was started; local work was not reset.'
|
||||
fi
|
||||
upstream=$(git -C "$source_dir" rev-parse '@{upstream}')
|
||||
git -C "$source_dir" merge-base --is-ancestor HEAD "$upstream" || fail 'Local-only or diverged commits were retained; use a checkout matching its published upstream. No deployment was started.'
|
||||
# Unlike plain git pull, this also refuses upstream paths that collide with ignored local data.
|
||||
if ! git -C "$source_dir" merge --ff-only --no-autostash --no-overwrite-ignore "$upstream" >/dev/null 2>&1; then
|
||||
fail 'Fast-forward failed; check for local or ignored files that conflict with upstream. Local work was not reset and no deployment was started.'
|
||||
fi
|
||||
head=$(git -C "$source_dir" rev-parse HEAD)
|
||||
[[ $head == "$upstream" ]] || fail 'Checkout does not match the fetched upstream; no deployment was started.'
|
||||
clean_checkout
|
||||
printf '%s\n' "Deploying source $head to CT $ctid; preserving existing configuration and data."
|
||||
exec bash "$source_dir/tools/proxmox.sh" update --ctid "$ctid" --source "$source_dir"
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run on the Proxmox host, from a trusted checkout. No curl-to-shell bootstrap.
|
||||
set -euo pipefail
|
||||
set +x
|
||||
exec python3 "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/proxmox/host.py" "$@"
|
||||
@@ -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`.
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -51,6 +51,8 @@ def main():
|
||||
else:
|
||||
shutil.copy2(file, target)
|
||||
shutil.copytree(root / 'src' / 'FinalToken.StreamDeck' / 'plugin', plugin, dirs_exist_ok=True)
|
||||
shutil.copy2(root / 'LICENSE', output / 'LICENSE')
|
||||
shutil.copy2(root / 'LICENSE', plugin / 'LICENSE')
|
||||
manifest_path = plugin / 'manifest.json'
|
||||
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
|
||||
manifest['Version'] = plugin_version
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Shared publication/deployment policy for local runtime files; never read their contents."""
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
PRIVATE_NAMES = {"server.json", "worker.json", "server.env", "worker.env", "transport-keys.json", "dashboard-key", "worker-key",
|
||||
"auth.json", ".credentials.json", "snapshot.json", "fleet.json", "history.json", "history.state.json",
|
||||
"history.journal.jsonl", "usage.json", "profile.json", "settings.json", "id_rsa", "id_ecdsa", "id_ed25519"}
|
||||
|
||||
|
||||
def is_private_path(path):
|
||||
p = PurePosixPath(str(path).replace("\\", "/").lower())
|
||||
return (p.name in PRIVATE_NAMES or p.name == ".env" or p.name.startswith(".env.") and p.name != ".env.example"
|
||||
or p.suffix in (".env", ".key", ".pem", ".pfx", ".p12")
|
||||
or any(part in (".claude", ".codex", ".ssh", ".aws", ".azure") for part in p.parts)
|
||||
or len(p.parts) > 1 and p.parts[0] in ("data", "state", "logs", "runs", "history"))
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Publication guard tests use synthetic values and read-only Git ignore queries."""
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import check_public
|
||||
|
||||
|
||||
class PublicCheckTests(unittest.TestCase):
|
||||
def test_private_names_are_reported_without_reading_them(self):
|
||||
for path in ("server.json", "deploy/worker.env", "profiles/.codex/auth.json", "fleet.json", "private.pem", ".env.production"):
|
||||
with self.subTest(path=path):
|
||||
self.assertTrue(check_public.sensitive_path(path))
|
||||
|
||||
def test_source_and_placeholder_examples_are_allowed(self):
|
||||
for path in ("server.example.json", "src/FinalToken.Core/HistoryStore.cs", "docs/web-dashboard.md", ".env.example", "LICENSE"):
|
||||
self.assertFalse(check_public.sensitive_path(path))
|
||||
|
||||
def test_matching_values_never_appear_in_findings(self):
|
||||
synthetic = "sk-" + "ant-" + "x" * 32
|
||||
findings = check_public.inspect("synthetic.txt", ("header\n" + synthetic).encode())
|
||||
self.assertEqual(1, len(findings))
|
||||
self.assertEqual(2, findings[0].line)
|
||||
self.assertEqual("provider token", findings[0].kind)
|
||||
self.assertNotIn(synthetic, repr(findings))
|
||||
|
||||
def test_private_key_and_url_credentials_are_detected(self):
|
||||
key = b"-----BEGIN " + b"PRIVATE KEY-----"
|
||||
url = b"https://" + b"fixture:[email protected]/repo.git"
|
||||
self.assertEqual({"private key", "credential in URL"}, {f.kind for f in check_public.inspect("fixture", key + b"\n" + url)})
|
||||
|
||||
def test_binary_input_is_not_treated_as_source(self):
|
||||
self.assertEqual([], check_public.inspect("image.png", b"\0" + b"sk-" + b"ant-" + b"x" * 32))
|
||||
|
||||
def test_staged_secret_is_found_even_when_working_copy_is_clean(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "source.txt").write_text("clean working copy")
|
||||
staged = ("sk-" + "proj-" + "x" * 32).encode()
|
||||
oid = "a" * 40
|
||||
def fake_git(where, *args, data=None):
|
||||
if args[0] == "ls-files" and "--stage" in args:
|
||||
return f"100644 {oid} 0\tsource.txt\0".encode()
|
||||
if args[0] == "ls-files":
|
||||
return b"source.txt\0"
|
||||
if args[:2] == ("cat-file", "-s"):
|
||||
return str(len(staged)).encode()
|
||||
if args[:2] == ("cat-file", "blob"):
|
||||
return staged
|
||||
self.fail("Unexpected Git read")
|
||||
with patch.object(check_public, "git", side_effect=fake_git):
|
||||
findings, _, _ = check_public.working_tree(root)
|
||||
self.assertTrue(any(f.path.startswith("index:") and f.kind == "provider token" for f in findings))
|
||||
|
||||
def test_working_tree_symlink_is_rejected_before_resolving_its_target(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
with patch.object(check_public, "git", return_value=b"link.cs\0"), \
|
||||
patch.object(check_public, "index", return_value=([], 0, [])), \
|
||||
patch.object(Path, "is_symlink", return_value=True), patch.object(Path, "read_bytes", side_effect=AssertionError("must not read")):
|
||||
findings, _, _ = check_public.working_tree(root)
|
||||
self.assertEqual("symlink/outside source tree", findings[0].kind)
|
||||
|
||||
def test_historical_private_name_is_detected_when_same_blob_had_a_public_name(self):
|
||||
oid = "c" * 40
|
||||
def fake_git(root, *args, data=None):
|
||||
if args[0] == "rev-list":
|
||||
return b"first\nsecond\n"
|
||||
name = "examples/example.json" if args[-1] == "first" else "auth.json"
|
||||
return f"100644 blob {oid}\t{name}\0".encode()
|
||||
with patch.object(check_public, "git", side_effect=fake_git):
|
||||
paths = check_public.historical_private_paths(Path("unused"))
|
||||
self.assertEqual({oid: {"auth.json"}}, paths)
|
||||
|
||||
def test_staged_private_file_is_reported_without_opening_its_blob(self):
|
||||
def fake_git(root, *args, data=None):
|
||||
self.assertEqual("ls-files", args[0])
|
||||
return ("100644 " + "a" * 40 + " 0\tserver.env\0").encode()
|
||||
with patch.object(check_public, "git", side_effect=fake_git):
|
||||
findings, count, _ = check_public.index(Path("unused"))
|
||||
self.assertEqual(0, count)
|
||||
self.assertEqual("index:server.env", findings[0].path)
|
||||
|
||||
def test_git_ignores_live_runtime_data_but_keeps_examples(self):
|
||||
paths = ["server.json", "deploy/worker.json", "server.env", ".env.production", "transport-keys.json", "fleet.json",
|
||||
"snapshot.json", "history.journal.jsonl", "profiles/.codex/auth.json", "private.key", "logs/session.log"]
|
||||
result = subprocess.run(["git", "check-ignore", "-z", "--stdin"], cwd=check_public.ROOT,
|
||||
input=("\0".join(paths) + "\0").encode(), capture_output=True, check=True)
|
||||
self.assertEqual(set(paths), set(result.stdout.decode().strip("\0").split("\0")))
|
||||
examples = subprocess.run(["git", "check-ignore", "-z", "--stdin"], cwd=check_public.ROOT,
|
||||
input=b".env.example\0server.example.json\0LICENSE\0", capture_output=True)
|
||||
self.assertEqual(1, examples.returncode)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -7,12 +7,28 @@ import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
|
||||
import publish
|
||||
|
||||
|
||||
class PublishTests(unittest.TestCase):
|
||||
def test_published_manifest_uses_shared_version(self):
|
||||
self.check_package()
|
||||
|
||||
def test_license_copy_preserves_lf_and_crlf_bytes(self):
|
||||
for newline in (b'\n', b'\r\n'):
|
||||
with self.subTest(newline=newline), tempfile.TemporaryDirectory(prefix='finaltoken-license-') as temporary:
|
||||
root = Path(temporary)
|
||||
(root / 'Directory.Build.props').write_text('<Project><Version>1.2.3</Version></Project>')
|
||||
(root / 'LICENSE').write_bytes(newline.join([b'Synthetic MIT notice', b'Copyright fixture', b'']))
|
||||
plugin = root / 'src/FinalToken.StreamDeck/plugin'
|
||||
plugin.mkdir(parents=True)
|
||||
(plugin / 'manifest.json').write_text('{"Version":"0.0.0.0"}')
|
||||
with patch.object(publish, '__file__', str(root / 'tools/publish.py')):
|
||||
self.check_package()
|
||||
|
||||
def check_package(self):
|
||||
def fake_publish(command, **kwargs):
|
||||
stage = Path(command[command.index('-o') + 1])
|
||||
stage.mkdir(parents=True)
|
||||
@@ -28,6 +44,11 @@ class PublishTests(unittest.TestCase):
|
||||
self.assertIsNotNone(version)
|
||||
manifest = json.loads((output / 'streamdeck/de.finalfactory.finaltoken.sdPlugin/manifest.json').read_text(encoding='utf-8'))
|
||||
self.assertEqual(version + '.0', manifest['Version'])
|
||||
license_bytes = (Path(publish.__file__).resolve().parent.parent / 'LICENSE').read_bytes()
|
||||
self.assertEqual(license_bytes, (output / 'LICENSE').read_bytes())
|
||||
self.assertEqual(license_bytes, (output / 'streamdeck/de.finalfactory.finaltoken.sdPlugin/LICENSE').read_bytes())
|
||||
with zipfile.ZipFile(output.with_suffix('.zip')) as bundle:
|
||||
self.assertEqual(license_bytes, bundle.read('LICENSE'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Provider-free HTTP + real worker/process integration. Build the solution first. Never uses installed providers."""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import getpass
|
||||
import http.cookiejar
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
KEY = "synthetic-dashboard-key-for-local-tests-only-123456"
|
||||
WORKER_KEY = "synthetic-worker-key-for-local-tests-only-abcdef"
|
||||
|
||||
|
||||
def wait_for(check, timeout=30):
|
||||
end = time.monotonic() + timeout
|
||||
while time.monotonic() < end:
|
||||
value = check()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(.1)
|
||||
raise AssertionError("Timed out waiting for synthetic integration condition")
|
||||
|
||||
|
||||
class Fixture:
|
||||
def __init__(self, port=None):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix="finaltoken-web-test-")
|
||||
self.path = Path(self.temp.name)
|
||||
self.processes = []
|
||||
if port is None:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
self.url = f"http://127.0.0.1:{port}"
|
||||
self.jar = http.cookiejar.CookieJar()
|
||||
self.browser = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.jar))
|
||||
self.csrf = None
|
||||
self.now = dt.datetime.now(dt.timezone.utc)
|
||||
self.claude = self.path / "claude"
|
||||
self.codex = self.path / "codex"
|
||||
self.claude.mkdir()
|
||||
self.codex.mkdir()
|
||||
# Windows locks loaded assemblies. Run fixture-owned copies so builds can continue during visual QA.
|
||||
for project in ("FinalToken.Web", "FinalToken.Worker", "FinalToken.FakeCli"):
|
||||
shutil.copytree(ROOT / "artifacts/bin" / project / "Release/net10.0", self.path / project)
|
||||
self.json(self.path / "server.json", {
|
||||
"accounts": [{"id": "claude", "provider": "Claude", "label": "Personal Claude", "expectedEmail": "[email protected]"},
|
||||
{"id": "codex", "provider": "Codex", "label": "Personal Codex", "expectedEmail": "[email protected]"}],
|
||||
"machines": [{"id": "a", "label": "Synthetic workstation", "osUser": getpass.getuser(),
|
||||
"profiles": [{"id": "main", "accountId": "claude"}, {"id": "code", "accountId": "codex"}]}]})
|
||||
fake = self.path / "FinalToken.FakeCli" / ("FinalToken.FakeCli.exe" if os.name == "nt" else "FinalToken.FakeCli")
|
||||
if not fake.exists():
|
||||
raise RuntimeError("Build FinalToken.slnx in Release before running this check")
|
||||
self.json(self.path / "worker.json", {"machineId": "a", "serverUrl": self.url,
|
||||
"stateDirectory": str(self.path / "worker-state"), "profiles": [
|
||||
{"id": "main", "provider": "Claude", "expectedEmail": "[email protected]", "configDirectory": str(self.claude), "dataDirectory": str(self.path / "claude-data"), "cliPath": str(fake)},
|
||||
{"id": "code", "provider": "Codex", "expectedEmail": "[email protected]", "configDirectory": str(self.codex), "dataDirectory": str(self.path / "codex-data"), "cliPath": str(fake)}]})
|
||||
# Handwritten transcript/rollout metadata. No real messages or credentials.
|
||||
projects = self.claude / "projects" / "fixture"
|
||||
projects.mkdir(parents=True)
|
||||
transcript = {"type": "assistant", "timestamp": self.now.isoformat(), "requestId": "req-fixture",
|
||||
"message": {"id": "msg-fixture", "model": "claude-opus-4-6", "usage": {"input_tokens": 100, "output_tokens": 20}}}
|
||||
(projects / "fixture.jsonl").write_text(json.dumps(transcript) + "\n" + json.dumps(transcript) + "\n", encoding="utf-8")
|
||||
sessions = self.codex / "sessions"
|
||||
sessions.mkdir()
|
||||
rows = [{"type": "session_meta", "payload": {"id": "fixture-session"}},
|
||||
{"type": "turn_context", "payload": {"model": "gpt-5.4"}},
|
||||
{"type": "event_msg", "timestamp": self.now.isoformat(), "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 100, "output_tokens": 20, "total_tokens": 120}}}}]
|
||||
(sessions / "rollout-fixture.jsonl").write_text("\n".join(map(json.dumps, rows)) + "\n", encoding="utf-8")
|
||||
env = os.environ.copy()
|
||||
env.update(FINALTOKEN_SERVER_CONFIG=str(self.path / "server.json"), FINALTOKEN_SERVER_DATA=str(self.path / "server-data"),
|
||||
FINALTOKEN_DASHBOARD_KEY=KEY, FINALTOKEN_MACHINE_a=WORKER_KEY, FINALTOKEN_PUBLIC_ORIGIN=self.url, ASPNETCORE_URLS=self.url)
|
||||
self.spawn(["dotnet", str(self.path / "FinalToken.Web/FinalToken.Web.dll")], env, ROOT / "src/FinalToken.Web")
|
||||
wait_for(self.ready)
|
||||
worker_env = os.environ.copy()
|
||||
# Synthetic CLI must not inherit either real profile override from the host.
|
||||
worker_env.pop("CLAUDE_CONFIG_DIR", None)
|
||||
worker_env.pop("CODEX_HOME", None)
|
||||
worker_env["FINALTOKEN_WORKER_KEY"] = WORKER_KEY
|
||||
self.spawn(["dotnet", str(self.path / "FinalToken.Worker/finaltoken-worker.dll"), str(self.path / "worker.json")], worker_env, ROOT)
|
||||
|
||||
@staticmethod
|
||||
def json(path, value):
|
||||
path.write_text(json.dumps(value), encoding="utf-8")
|
||||
|
||||
def spawn(self, command, env, cwd):
|
||||
self.processes.append(subprocess.Popen(command, env=env, cwd=cwd, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
|
||||
start_new_session=os.name != "nt"))
|
||||
|
||||
def ready(self):
|
||||
try:
|
||||
return urllib.request.urlopen(self.url, timeout=1).status == 200
|
||||
except (OSError, urllib.error.URLError):
|
||||
return False
|
||||
|
||||
def call(self, path, body=None, opener=None, headers=None):
|
||||
h = {"Content-Type": "application/json", "X-FinalToken": "1"}
|
||||
if self.csrf:
|
||||
h["X-CSRF"] = self.csrf
|
||||
h.update(headers or {})
|
||||
request = urllib.request.Request(self.url + path, data=None if body is None else json.dumps(body).encode(), headers=h)
|
||||
with (opener or self.browser).open(request, timeout=10) as response:
|
||||
data = response.read()
|
||||
return json.loads(data) if data else None
|
||||
|
||||
def sign_in(self):
|
||||
self.csrf = self.call("/session", {"key": KEY})["csrf"]
|
||||
|
||||
def online(self):
|
||||
return self.call("/api/dashboard")["machines"][0]["online"]
|
||||
|
||||
def login_state(self, login, state):
|
||||
view = self.call("/api/logins/" + login["id"])
|
||||
return view if view["state"] == state else None
|
||||
|
||||
def authorize(self):
|
||||
self.sign_in()
|
||||
wait_for(self.online)
|
||||
login = self.call("/api/logins", {"machineId": "a", "profileId": "main"})
|
||||
wait_for(lambda: self.login_state(login, "WaitingForCode"))
|
||||
self.call(f"/api/logins/{login['id']}/response", {"response": "fixture-code#fixture-state"})
|
||||
wait_for(lambda: self.login_state(login, "Succeeded"))
|
||||
device = self.call("/api/logins", {"machineId": "a", "profileId": "code"})
|
||||
wait_for(lambda: self.login_state(device, "WaitingForBrowser"))
|
||||
(self.codex / "authorize-device").touch()
|
||||
wait_for(lambda: self.login_state(device, "Succeeded"))
|
||||
return login, device
|
||||
|
||||
def close(self):
|
||||
for process in reversed(self.processes):
|
||||
if process.poll() is None:
|
||||
if os.name == "nt":
|
||||
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
|
||||
else:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
process.wait(timeout=10)
|
||||
self.temp.cleanup()
|
||||
|
||||
|
||||
class WebIntegration(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.fixture = Fixture()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.fixture.close()
|
||||
|
||||
def test_end_to_end(self):
|
||||
f = self.fixture
|
||||
anonymous = urllib.request.build_opener()
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||
f.call("/api/dashboard", opener=anonymous)
|
||||
self.assertEqual(401, error.exception.code)
|
||||
f.sign_in()
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||
f.call("/api/logins", {"machineId": "a", "profileId": "main"}, headers={"X-CSRF": "wrong"})
|
||||
self.assertEqual(403, error.exception.code)
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||
f.call("/api/logins", {}, headers={"Origin": "https://evil.test"})
|
||||
self.assertEqual(403, error.exception.code)
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||
f.call("/worker/report", {}, opener=anonymous)
|
||||
self.assertEqual(401, error.exception.code)
|
||||
login, device = f.authorize()
|
||||
self.assertEqual("[email protected]", f.login_state(login, "Succeeded")["email"])
|
||||
self.assertIsNone(f.login_state(login, "Succeeded")["url"])
|
||||
wait_for(lambda: all(a["total"]["total"] == 120 for a in f.call("/api/dashboard")["accounts"]))
|
||||
dashboard = f.call("/api/dashboard")
|
||||
codex = next(a for a in dashboard["accounts"] if a["account"]["id"] == "codex")
|
||||
self.assertEqual(65, codex["windows"][0]["window"]["usedPercent"])
|
||||
self.assertGreater(codex["windows"][0]["useAtReset"], 100)
|
||||
other = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
|
||||
f.call("/session", {"key": KEY}, opener=other)
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||
f.call("/api/logins/" + login["id"], opener=other)
|
||||
self.assertEqual(404, error.exception.code)
|
||||
for path in (f.path / "server-data").rglob("*"):
|
||||
if path.is_file() and path.suffix == ".json":
|
||||
data = path.read_bytes()
|
||||
self.assertNotIn(b"fixture-code", data)
|
||||
self.assertNotIn(b"fixture-state", data)
|
||||
self.assertNotIn(b"ABCD-12345", data)
|
||||
# Real child process cancellation, then wrong-account verification.
|
||||
(f.codex / "authorize-device").unlink()
|
||||
cancel = f.call("/api/logins", {"machineId": "a", "profileId": "code"})
|
||||
wait_for(lambda: f.login_state(cancel, "WaitingForBrowser"))
|
||||
f.call(f"/api/logins/{cancel['id']}/cancel", {})
|
||||
wait_for(lambda: f.login_state(cancel, "Cancelled"))
|
||||
mismatch = f.call("/api/logins", {"machineId": "a", "profileId": "main"})
|
||||
wait_for(lambda: f.login_state(mismatch, "WaitingForCode"))
|
||||
f.call(f"/api/logins/{mismatch['id']}/response", {"response": "wrong-code#fixture-state"})
|
||||
wait_for(lambda: f.login_state(mismatch, "AccountMismatch"))
|
||||
(f.claude / "overflow-login").touch()
|
||||
overflow = f.call("/api/logins", {"machineId": "a", "profileId": "main"})
|
||||
wait_for(lambda: f.login_state(overflow, "Failed"), timeout=15)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--serve-fixture", action="store_true", help="Keep synthetic server/worker running for local visual QA")
|
||||
args = parser.parse_args()
|
||||
if args.serve_fixture:
|
||||
fixture = Fixture(port=5187)
|
||||
try:
|
||||
fixture.authorize()
|
||||
print("Synthetic dashboard ready at " + fixture.url, flush=True)
|
||||
print("Access key: " + KEY, flush=True)
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
fixture.close()
|
||||
else:
|
||||
unittest.main(argv=[__file__])
|
||||
Reference in New Issue
Block a user