tools: add Proxmox installation and one-command updates
agent-review agent review: fail

Create unprivileged server or worker LXCs and build native binaries inside the container. Refresh a clean published checkout before updates, preserve configuration and history, and roll back failed binary activation without resetting local source work.

Refs #19
This commit is contained in:
Florian Schmidt
2026-11-15 10:59:41 +01:00
parent ab3dcf64e8
commit b23b7289c7
13 changed files with 1644 additions and 15 deletions
+13
View File
@@ -0,0 +1,13 @@
# Architecture
- [2026-11-14] D14's Fleet library reuses Core Pace/LimitAnalysis/ApiPrices; the web host and outbound worker add no second forecast implementation. Working-time schedules remain outside D7.
- [2026-11-14] Quota is one newest observation per account/window, not a sum. Source ids dedupe consumption across machines; local/session figures include shared copies and cannot be summed as machine-exclusive use.
- [2026-11-14] Legacy hourly history needs one source and UTC-hour cutoff. Reconcile Codex increases before clipping; without a pre-cutoff baseline, omit the first cumulative total and warn rather than potentially counting imported use twice.
- [2026-11-14] LoginCoordinator is memory-only and binds browser session/machine/profile/worker boot/deadline. CLI identity verification is separate from process success; never serialize login URLs, codes or authorization responses into fleet state.
- [2026-11-14] Persist worker export metadata before cursor advancement. Server merges acknowledged source records so an empty restart heartbeat cannot erase history. Current login health and historical data attribution are separate fields.
- [2026-11-15] Proxmox setup creates an unprivileged Debian 13 CT and builds NativeAOT inside it as a separate user. `proxmox-update.sh CTID` fast-forwards a clean tracking clone and enters the fetched installer; the local-source entry point stays offline. Updates preserve role/config/keys/profiles/history with binary-health rollback; no automatic CT or old-release deletion.
- [2026-11-15] Public source uses MIT; notices travel with ZIP/plugin and Proxmox outputs. `tools/source_policy.py` excludes recognized live config/keys/runtime data from both publication checks and source archives. Audit disk and index separately; inspect all historical trees, not just one filename hint per blob. Visibility/history changes need explicit authorization.
## Archive
+8
View File
@@ -5,4 +5,12 @@
- [2026-10-18] Avalonia 12 `CustomPopupPlacementCallback` gets the target's bounds in window coordinates, and a flip mirrors anchor and gravity but not the offset. Put a gap into the anchor rectangle (see `DataTooltip.BesidePointer`).
- [2026-10-18] Fluent caps `ToolTip` `MaxWidth` at 320 px, and a tooltip that covers the pointer takes pointer-over from its control, which raises `PointerExited`. `Ui.Theme` raises the cap; tall tips open beside the pointer.
- [2026-11-14] Official Claude manual-code login must be relayed to the original process, not a browser's remote localhost. Redirected-stdin support needs live verification; Codex uses device auth. Worker D3 print-mode quota probing is opt-in because current docs do not promise it as a non-interactive quota API.
- [2026-11-14] Proxmox `pct exec` environment defaults differ by version. Installer calls explicitly use `--keep-env 0`; build/CLI installation also uses a clean environment under the intended non-root user.
- [2026-11-15] Documentation checks must skip `artifacts/` as well as `.artifacts/`: ignored build/audit downloads can contain third-party Markdown and are not project documentation.
- [2026-11-15] Plain `git pull` can silently overwrite ignored files newly tracked upstream. The Proxmox updater fetches then merges with `--ff-only --no-overwrite-ignore`; a real-Git regression covers ignored operator-state collisions.
## Archive
+5 -4
View File
@@ -2,13 +2,14 @@
> Always-loaded. Everything else is on-demand. Update TOC when files change.
## Current Focus
- [2026-10-18] Reset history (D12), API value (D13) and panel fixes on issue #14, PR #16.
- [2026-11-15] Publish the D14 dashboard/workers and Proxmox delivery. Live Linux/LXC/TLS and official provider-login verification remains outstanding.
## Invariants
- No credential is ever read, stored or sent; providers are reached only through their CLIs (D2).
- Provider access/refresh tokens, API keys and cookies stay with the CLIs; only a pending login's authorization response may be relayed transiently (D2, D14).
- Everything shipped stays NativeAOT-safe on win-x64 and linux-x64 (D1).
- A response counts once, across restarts, rescans and resumed sessions (D3, D4, D5).
- `snapshot.json` is the only interface between the app and other processes (D9).
- Desktop/Stream Deck retain `snapshot.json` (D9); the optional authenticated server/worker transport is separate (D14).
## Table of Contents
- `gotchas.md` — 4 entries — CLI probing pitfalls on this machine; Avalonia tooltip placement.
- `gotchas.md` — 8 entries — CLI login, Proxmox isolation/update safety, documentation output boundaries and Avalonia tooltips.
- `architecture.md` — 7 entries — Fleet analysis, attribution, migration, authentication, durability, Proxmox and publication.
+17 -4
View File
@@ -1,8 +1,8 @@
# FinalToken
A small tray app that tracks Claude Code and Codex usage and limits on Windows 11 and CachyOS. It
never signs in to a provider and never handles a token: all data comes from the installed CLIs
and the files they write. A stats panel shows history, small popups warn when usage runs ahead
keeps provider credentials owned by the installed CLIs. The optional web dashboard coordinates
official CLI login with transient authorization-code relay (D14). A stats panel shows history, small popups warn when usage runs ahead
of or behind a limit's pace, and a Stream Deck plugin puts stats on keys. Developer:
schmidt.florian (Gitea user name).
@@ -30,6 +30,9 @@ the decision, why and gives-up format, and carries the `type/decision` label.
| `src/FinalToken.App` | Avalonia desktop app (D8): stats panel, tray, settings, popups |
| `src/FinalToken.Cli` | `finaltoken-cli` console: runs a refresh and prints the snapshot, for scripts and checks |
| `src/FinalToken.StreamDeck` | Stream Deck plugin executable and its `.sdPlugin` assets (D10) |
| `src/FinalToken.Fleet` | Account/machine metadata, shared analysis and pending official CLI logins (D14) |
| `src/FinalToken.Web` | Authenticated self-hosted dashboard and outbound-worker API (D14) |
| `src/FinalToken.Worker` | Per-OS-user collector and official CLI login process host (D14) |
| `tests/*` | One test project per tested project, named `<Project>.Tests` |
| `tools/` | Repository tools, listed under [Tools](#tools) |
@@ -41,8 +44,10 @@ the decision, why and gives-up format, and carries the `type/decision` label.
no reflection-driven serialization, binding or loading, no `dynamic`, no runtime code
generation. Trim and AOT analyzer warnings are errors; never suppress one without a one-line
reason at that spot.
- Never touch credentials (D2): do not open credential files, environment secrets or keychains,
never log message text, and never call a provider's HTTP API.
- Never touch provider credentials (D2): do not open credential files, provider environment secrets or keychains,
never log message text, and never call a provider's HTTP API. D14 permits authenticated,
transient authorization-response relay to the pending official CLI login. Dashboard/worker
access keys authenticate FinalToken transport; they are not provider credentials.
- Child processes (`claude`, `codex`) run without a shell, with arguments as a list, a timeout and
cancellation, and are killed with their process tree when they overrun (D6).
- Every file the app writes for itself is written atomically (D5).
@@ -130,6 +135,14 @@ a screenshot of each changed view: compiling is not working.
- `tools/publish.py`: publishes the app, `finaltoken-cli` and Stream Deck plugin with NativeAOT
into an empty output directory and creates a ZIP beside it. Run on the target OS. It stamps
the plugin manifest's `Version` from `<Version>`; its test is `python -B tools/test_publish.py`.
- `tools/test_web_dashboard.py`: provider-free HTTP/worker/process integration; build Release first.
`--serve-fixture` runs a temporary synthetic dashboard for screenshots. See `docs/web-dashboard.md`.
- `tools/proxmox.sh`: creates/updates a managed Debian 13 LXC from the Proxmox host. Its Python
helpers live in `tools/proxmox/`; test with `python -B tools/proxmox/test_installer.py`. See `docs/proxmox.md`.
- `tools/proxmox-update.sh CTID`: fast-forwards a clean tracking checkout, then runs the fetched
installer against a managed CT; test with `python -B tools/proxmox/test_update.py`.
- `tools/check_public.py --history`: read-only publication pattern check. It reports paths/pattern
names, never matching values; tests are `python -B tools/test_check_public.py`. See `docs/publication.md`.
## Writing
+25 -7
View File
@@ -1,18 +1,26 @@
# FinalToken
FinalToken is a tray app for Claude Code and Codex usage. It shows token history, provider limits,
and pace, warns when usage runs ahead of or behind a limit, and puts selected stats on Stream Deck
keys. Starting the app opens the stats panel; closing it keeps the tray app running by default.
FinalToken answers: **at my current usage, will my allowance last until the weekly reset?**
It tracks Claude Code and Codex limits, average/recent forecasts, daily budgets and reset history.
Use the desktop tray app, the optional self-hosted web dashboard, or Stream Deck keys.
Starting the desktop app opens its stats panel; closing it keeps the tray app running by default.
FinalToken does not sign in to a provider, handle API keys or OAuth tokens, or read credential
files. It reads the installed CLIs' usage files and runs their local commands. It never calls a
provider's HTTP API itself. Missing or logged-out CLIs show as unavailable.
FinalToken reads the installed CLIs' usage files and runs their commands. Provider credentials
stay owned by those CLIs; FinalToken never reads credential files or calls a provider's HTTP API.
The optional [self-hosted dashboard and worker](docs/web-dashboard.md) combine multiple machines
and coordinate official CLI login with transient authorization-code relay. Weekly forecasts,
daily budgets and reset history reuse the desktop app's analysis. Missing or logged-out CLIs
show their observed health; stale allowances have no current forecast.
For automatic container creation from a Proxmox host, use the [LXC install/update script](docs/proxmox.md).
It supports a server-only LXC and a single-command update that refreshes the deployment checkout.
## Requirements
- Claude Code and/or Codex CLI installed and logged in through the CLI. Their paths can be
overridden in Settings.
- Windows 11, or Linux with X11 or XWayland. CachyOS with KDE Plasma uses XWayland.
- Desktop: Windows 11, or Linux with X11 or XWayland. CachyOS with KDE Plasma uses XWayland.
- Web server/client: .NET 10 source build or a target-OS NativeAOT build; no desktop required.
- For keys: Stream Deck 7 on Windows, or OpenDeck on Linux. These are optional.
## Install and use
@@ -55,3 +63,13 @@ python -B tools/publish.py win-x64 --out artifacts/package-win-x64
The publish directory must be empty. The tool bundles all three executables and plugin assets,
then creates a ZIP beside the directory. Publish `win-x64` on Windows and `linux-x64` on Linux.
## Public source and contributing
Once the repository is publicly readable, cloning/fetching/pulling over HTTPS needs no Git login.
Push access, dashboard access and official provider logins remain separate authenticated operations.
See [contributing](CONTRIBUTING.md) and [publication checks](docs/publication.md).
## License
[MIT](LICENSE). Third-party dependencies retain their own licenses.
+248
View File
@@ -0,0 +1,248 @@
# Proxmox LXC install and update
Run [tools/proxmox.sh](../tools/proxmox.sh) **as root on the Proxmox host**, from a trusted local
copy of this checkout. It creates the container itself; do not run it inside an existing LXC.
The default is a dashboard plus a collector/client in one new, unprivileged Debian 13 amd64 CT.
This follows [D14](decisions.md#d14--self-hosted-dashboard-and-workers).
Use a checkout containing the web/worker and installer source. A public repository can be
[cloned and updated over HTTPS without a Git login](publication.md#anonymous-git-reads).
Alternatively copy the source to the host, including `tools/proxmox/`, `tools/proxmox.sh`, `tools/source_policy.py`,
`LICENSE`, root build files and the four Core/Fleet/Web/Worker source directories. Git metadata
and build artifacts are not needed. The installer snapshots the selected local source, including
uncommitted files; this local-source installer never pulls, commits or pushes Git changes.
The separate [one-command updater](../tools/proxmox-update.sh) refreshes a clean Git checkout
before invoking the installer.
The snapshot excludes recognized local configuration, key and runtime-data paths independently
of Git ignore rules; those files are not read or transferred with the source.
## Install dashboard and client
From the copied repository root on the Proxmox host:
```bash
bash tools/proxmox.sh install --ctid 201 --storage local-lvm \
--domain usage.example.com --email [email protected] --timezone Europe/Berlin
```
Replace the storage, CT id, domain and email. Omit `--ctid` to ask Proxmox for the next free id.
`--storage` is deliberately required: the installer does not choose where to allocate your disk.
Add `--dry-run` to print the validated plan without calling Proxmox or changing files.
The installer:
1. Downloads the latest available Debian 13 standard amd64 template to `local`, or uses the
filename selected with `--template`. `--template-storage` selects another template storage.
2. Creates an unprivileged CT, with on-boot startup, 2 cores, 4096 MiB RAM, 2048 MiB swap,
a 20 GiB root disk and DHCP on `vmbr0`. It does not enable nesting or privileged mode.
3. Uploads an allowlisted source archive and builds `linux-x64` NativeAOT **inside the CT**, as
the separate `finaltoken-build` OS user. Windows-built executables are never deployed to Linux.
4. Installs the .NET 10 SDK/native compiler prerequisites in the CT, Caddy for HTTPS, and the
official Claude native stable installer and Codex npm package as the `finaltoken` user.
Official CLI downloads run under that user, not root. No provider login is attempted.
5. Generates service keys, account/profile bindings, systemd services and a loopback web backend.
Caddy exposes `https://<domain>`. The new client is automatically registered with this server.
6. Checks local services and the dashboard HTTP response. Keys are not printed by the script.
The host needs Proxmox's `pct`, `pvesh`, `pveam`, `pvesm` and Python 3. Its package repositories
are not changed. The CT needs working DNS and outbound package/download access. Native builds
need time and memory; increase `--memory`, `--cores` or `--disk` for a slower/smaller host.
The first build restores .NET packages. Later updates also run package installation in the CT;
this is not a fully offline or byte-for-byte reproducible supply-chain build.
For static networking:
```bash
bash tools/proxmox.sh install --ctid 201 --storage local-lvm \
--bridge vmbr0 --ip 192.0.2.20/24 --gateway 192.0.2.1 --vlan 10 \
--domain usage.example.com --email [email protected]
```
`--vlan` is optional. Set DNS to point the chosen domain to the CT. Allow incoming TCP 80/443
through your Proxmox/network firewall and, for public ACME certificates, forward the required
ports. The script sets the CT interface's firewall flag; it does not modify cluster/host firewall
rules, DNS, NAT or routing. The public certificate/network path is not proven by the local
health check. Caddy's default ACME certificate issuance needs the domain to be reachable.
For a private LAN hostname, add `--tls internal`. Caddy then uses a private CA; explicitly trust
its root certificate on browsers and remote clients. Do not disable TLS verification.
The root certificate is inside the CT at:
```text
/var/lib/finaltoken-proxy/caddy/pki/authorities/local/root.crt
```
Read the dashboard access key from the Proxmox root console when you need to sign in:
```bash
pct exec 201 -- cat /etc/finaltoken/dashboard-key
```
Open the dashboard and use **Log in / renew** for each provider profile. This is the actual
official CLI login, bound to that CT's `finaltoken` user. The CLI still requires your browser
authorization. The client only observes coding activity in this CT's profiles; it cannot see
coding sessions on a desktop or a different CT unless a client is installed there too.
Claude quota probing remains subject to the [web integration limitations](web-dashboard.md#provider-usage-limitations).
## Client-only or server-only
For a **server-only** container, run this as root on the Proxmox host after these changes are
published to `master` and anonymous HTTPS reads are enabled. The host needs Git in addition to
the Proxmox commands and Python 3. Use a new checkout path and a free CT id; replace the storage,
domain and timezone for your setup:
```bash
git clone --branch master --single-branch https://git.finalfactory.de/FinalFactory/FinalToken.git /opt/finaltoken-src && \
bash /opt/finaltoken-src/tools/proxmox.sh install --role server --ctid 201 \
--storage local-lvm --domain usage.example.com --timezone Europe/Berlin
```
This installs only the dashboard and HTTPS proxy. No provider login or provider email is required
on the server. Optional `--email` seeds the provider accounts; accounts and remote machine
bindings can also be configured afterwards. Set the domain's DNS and TCP 80/443 access as
described above. Private-LAN deployments can add `--tls internal` and trust the private CA.
Read the dashboard key with `pct exec 201 -- cat /etc/finaltoken/dashboard-key`.
Keep `/opt/finaltoken-src` as a dedicated deployment checkout for the update command below.
For a separate collector LXC, first configure an account/machine binding on the existing server
as described in [the dashboard setup](web-dashboard.md#run-locally). The machine's `osUser` must
be `finaltoken`, with the selected provider ids as its profile ids. Put that machine's matching
transport key in a root-readable host file (mode 0600); it is a FinalToken key, not a provider token.
```bash
bash tools/proxmox.sh install --ctid 202 --storage local-lvm --role worker \
--server-url https://usage.example.com --machine-id lxc_202 \
--worker-key-file /root/lxc_202.key --email [email protected]
```
The script creates the client CT, installs its CLIs, configures profiles and starts its service.
The existing server must already authorize that machine id/key; this mode does not edit another
server's configuration. If the existing server uses a private CA, install that CA in the new CT's
system trust store with `update-ca-certificates` before expecting the worker to connect.
`--role server` omits the local client/CLIs and starts with no machine bindings. You can supply
`--email` to seed provider accounts, then configure remote machines in `/etc/finaltoken/server.json`
and add their distinct `FINALTOKEN_MACHINE_<id>` keys in `/etc/finaltoken/server.env`.
Restart the server after editing its configuration. The operator guide documents this static
configuration contract; there is no automatic remote enrollment HTTP API.
Use `--providers codex` or `--providers claude` to install only one provider.
`--claude-email` and `--codex-email` override `--email` independently. Machine ids must begin with
a letter and use letters/digits/underscores, because they also name systemd environment variables.
## Update or resume a partial installation
For a clean clone at `/opt/finaltoken-src`, run this **single command as root on the host**
from any working directory. Change `201` to the installed CT id:
```bash
bash /opt/finaltoken-src/tools/proxmox-update.sh 201
```
It fetches the checkout's tracking branch with fast-forward-only/no-autostash rules, verifies that
HEAD matches that upstream, then enters the **newly fetched** installer. Re-running the command
with no new commit still retries deployment, which is useful after a package/build interruption.
The existing managed CT marker preserves the installed role, including server-only installations.
It refuses a detached branch, missing upstream, local-only commits and tracked/staged/untracked
changes; it never resets, stashes, commits or pushes local work. Upstream paths that would overwrite
ignored local files also stop the update. Ignored runtime state is retained
and filtered from source archives. Update failures return a nonzero exit status. Git failures
stop before deployment and do not echo remote URLs that might contain operator credentials.
The updater locks its checkout with `flock` (util-linux); the installer also holds its existing
host-wide deployment lock. Do not edit the dedicated clone during an update.
To validate the current source and deployment arguments without fetching or changing the CT:
```bash
bash /opt/finaltoken-src/tools/proxmox-update.sh 201 --dry-run
```
For a manually copied checkout or a deliberately selected local source snapshot, copy the
desired new source into place and use the original offline-source entry point:
```bash
bash tools/proxmox.sh update --ctid 201
```
Use `--source /absolute/path/to/another/checkout` to select a different local source snapshot.
Update requires a running CT with this installer's marker and matching CT id. It refuses foreign
or stopped containers. It does not overwrite identity settings; install-only identity flags are
rejected on update. Service keys, configuration, CLI profiles and usage history are preserved.
Updates do not reinstall/upgrade the official CLIs; they keep their normal CLI-owned lifecycle.
A new binary release is built before the `current` symlink changes. Only services that were
running are restarted; intentionally stopped services remain stopped. A local health failure
restores the previous binary release and attempts to restart the previously running services.
That is binary rollback, not a history/configuration/OS-package rollback. Old releases are kept;
no automatic pruning or container deletion takes place. A future incompatible data schema needs
an explicit migration/backup plan before deploying it.
Restarting a server/client interrupts pending login attempts; finish or cancel them first.
An interrupted package download or build leaves the CT for inspection. Once the guest marker
exists, the same `update` command resumes an incomplete initial installation without rotating
its enrollment key. If creation failed before the marker was written, inspect the CT and its
network rather than trying to overwrite it with another `install`.
## Files and service ownership
| Location | Purpose |
|---|---|
| `/etc/finaltoken/install.json` | Managed CT id, role, source checksum and last successful release |
| `/etc/finaltoken/server.json`, `worker.json` | Operator-editable account/profile configuration |
| `/etc/finaltoken/server.env`, `worker.env` | Root-only FinalToken service keys/environment |
| `/etc/finaltoken/transport-keys.json` | Root-only initial transport-key backup; not provider credentials |
| `/opt/finaltoken/releases/`, `/opt/finaltoken/current` | Root-owned staged/active native binaries |
| `/var/lib/finaltoken-server/` | Server data; owned by `finaltoken-server` |
| `/var/lib/finaltoken-worker/` | CLI profiles, per-provider history and collector state; owned by `finaltoken` |
| `/var/lib/finaltoken-proxy/` | Caddy state/certificates; owned by `finaltoken-proxy` |
| `/var/cache/finaltoken-build/` | Separate build user home/cache; per-build source directories are removed |
Generated units use separate non-root users, restrictive file permissions, no-new-privileges and
process-group shutdown. They avoid mount-namespace sandbox settings that require extra LXC
features. Unit files are created once and preserved on update; put site overrides in systemd
drop-ins. Default package `caddy.service` is disabled in favor of `finaltoken-proxy.service`.
```bash
pct exec 201 -- systemctl status finaltoken-server finaltoken-worker finaltoken-proxy
pct exec 201 -- journalctl -u finaltoken-worker -u finaltoken-server --since today
```
Application stdout/stderr are discarded by these units to prevent CLI/login material entering
the journal. The journal still shows service exit/restart metadata. Inspect configuration and
CLI installation under the intended user when diagnosing a failed service. Do not dump provider
credential files into logs or support reports. For coding inside the worker CT, use
`pct enter 201`, then `su - finaltoken`; its official CLIs are in `~/.local/bin`.
## Verification and limits
Run from the repository root:
```text
python -B tools/proxmox/test_installer.py
python -B tools/proxmox/test_update.py
bash -n tools/proxmox.sh
bash -n tools/proxmox-update.sh
python -B tools/docs/check_docs.py
```
Installer tests mock Proxmox, package installation, native publishing and systemd. They cover
argument validation, CT refusal, command order, environment isolation, archive safety, preservation
of configuration/keys, partial setup, stopped services and activation rollback. They do not prove
a real Proxmox create/update, Linux build, certificate issuance or provider login. No Proxmox
host/container was changed while developing this script.
Updater tests use real local Git repositories and Bash with a synthetic installer. They verify
two-version fast-forward deployment, no-change retry, dirty/diverged/ahead/detached refusal,
fetch failure, dry-run, exit status, ignored-state retention and ignored-file collisions. Advisory lock command results
are substituted so the checks also run on Windows; real Linux locking is not exercised here.
References: [Proxmox CLI source](https://github.com/proxmox/pve-container/blob/master/src/PVE/CLI/pct.pm),
[.NET on Debian](https://learn.microsoft.com/en-us/dotnet/core/install/linux-debian),
[NativeAOT prerequisites](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/),
[Caddy TLS](https://caddyserver.com/docs/caddyfile/directives/tls),
[Claude installation](https://code.claude.com/docs/en/setup),
[Codex installation](https://github.com/openai/codex/blob/main/README.md).
Source refresh uses [Git fetch](https://git-scm.com/docs/git-fetch),
[fast-forward merge](https://git-scm.com/docs/git-merge) and
[flock](https://man7.org/linux/man-pages/man1/flock.1.html).
+66
View File
@@ -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"
+5
View File
@@ -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" "$@"
+2
View File
@@ -0,0 +1,2 @@
# Proxmox deployment tools
Host creates only a new explicitly selected CT; update requires this installer's marker. Never destroy a CT, alter host package repositories, overwrite existing configuration, or read provider credentials. Builds run inside the CT as an isolated user. Transport keys are FinalToken service keys, not provider tokens. Keep commands as argv lists; never shell-interpolate deployment inputs. Test with `python -B tools/proxmox/test_installer.py`.
+386
View File
@@ -0,0 +1,386 @@
"""Private guest provisioner, invoked by host.py inside the selected LXC. Not a host entry point."""
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import pwd
import secrets
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.request
import uuid
INSTALLER = "finaltoken-proxmox-v1"
ETC = Path("/etc/finaltoken")
APP = Path("/opt/finaltoken")
BUILD = Path("/var/cache/finaltoken-build")
SERVER_HOME = Path("/var/lib/finaltoken-server")
WORKER_HOME = Path("/var/lib/finaltoken-worker")
PROXY_HOME = Path("/var/lib/finaltoken-proxy")
SYSTEMD = Path("/etc/systemd/system")
def run(command, *, check=True, capture=False, cwd=None):
return subprocess.run([str(a) for a in command], check=check, text=True,
stdout=subprocess.PIPE if capture else None, stderr=subprocess.PIPE if capture else None, cwd=cwd)
def atomic(path, data, mode=0o600, *, once=False):
"""D5: same-directory replace; existing operator configuration is never overwritten."""
if once and path.exists():
return False
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp")
try:
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
with os.fdopen(fd, "w", encoding="utf-8") as stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
return True
def json_file(path, data, *, once=False):
return atomic(path, json.dumps(data, indent=2) + "\n", once=once)
def unpack(archive_path, destination):
"""No links, devices, absolute paths, traversal or unbounded archive expansion."""
destination.mkdir(parents=True, exist_ok=True)
with tarfile.open(archive_path, "r:gz") as archive:
members = archive.getmembers()
if len(members) > 10000 or sum(m.size for m in members) > 256 * 1024 * 1024:
raise ValueError("Source archive exceeds its metadata/size bound")
for member in members:
path = PurePosixPath(member.name)
if path.is_absolute() or ".." in path.parts or not member.isfile() or member.size > 16 * 1024 * 1024:
raise ValueError("Source archive has an unsafe entry")
target = destination.joinpath(*path.parts)
target.parent.mkdir(parents=True, exist_ok=True)
with archive.extractfile(member) as source, target.open("xb") as output:
shutil.copyfileobj(source, output)
target.chmod(0o644)
def user(name, home):
try:
entry = pwd.getpwnam(name)
if entry.pw_dir != str(home):
raise ValueError("Existing service user has an unexpected home: " + name)
except KeyError:
run(["useradd", "--system", "--create-home", "--home-dir", home, "--shell", "/bin/bash", "--user-group", name])
entry = pwd.getpwnam(name)
home.mkdir(parents=True, exist_ok=True)
os.chown(home, entry.pw_uid, entry.pw_gid)
home.chmod(0o750)
return entry
def as_user(name, home, command, cwd=None):
# Do not inherit host/root provider secrets, proxy overrides or build credentials.
return run(["runuser", "--user", name, "--", "env", "-i", "HOME=" + str(home),
"PATH=" + str(home / ".local/bin") + ":/usr/local/bin:/usr/bin:/bin",
"DOTNET_CLI_HOME=" + str(home), "DOTNET_CLI_TELEMETRY_OPTOUT=1", "DOTNET_NOLOGO=1", *command], cwd=cwd or home)
def packages(role, providers):
run(["apt-get", "update"])
wanted = ["ca-certificates", "curl", "clang", "zlib1g-dev", "libicu-dev", "libssl-dev", "tzdata"]
if role != "worker":
wanted.append("caddy")
if role != "server" and "codex" in providers:
wanted.extend(["nodejs", "npm"])
run(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", *wanted])
repository = Path("/etc/apt/sources.list.d/microsoft-prod.list")
if not repository.exists():
with tempfile.TemporaryDirectory(prefix="finaltoken-sdk-") as tmp:
package = Path(tmp) / "packages-microsoft-prod.deb"
run(["curl", "--fail", "--silent", "--show-error", "--location", "--proto", "=https", "--tlsv1.2",
"https://packages.microsoft.com/config/debian/13/packages-microsoft-prod.deb", "--output", package])
run(["dpkg", "-i", package])
run(["apt-get", "update"])
run(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "dotnet-sdk-10.0"])
def official_clis(providers):
"""Install official clients as their own OS user; never run a login or read auth files."""
if "claude" in providers and not (WORKER_HOME / ".local/bin/claude").exists():
with tempfile.TemporaryDirectory(prefix="finaltoken-claude-") as tmp:
os.chmod(tmp, 0o755)
script = Path(tmp) / "install.sh"
run(["curl", "--fail", "--silent", "--show-error", "--location", "--proto", "=https", "--tlsv1.2",
"https://claude.ai/install.sh", "--output", script])
script.chmod(0o644)
as_user("finaltoken", WORKER_HOME, ["bash", str(script), "stable"])
if "codex" in providers and not (WORKER_HOME / ".local/bin/codex").exists():
as_user("finaltoken", WORKER_HOME, ["npm", "install", "--prefix", str(WORKER_HOME / ".local"), "@openai/codex@latest"])
for provider in providers:
as_user("finaltoken", WORKER_HOME, [str(WORKER_HOME / ".local/bin" / provider), "--version"])
def service_unit(role):
server = role == "server"
home = SERVER_HOME if server else WORKER_HOME
account = "finaltoken-server" if server else "finaltoken"
executable = APP / "current" / ("web/FinalToken.Web" if server else "worker/finaltoken-worker")
arguments = "" if server else " " + str(ETC / "worker.json")
return f"""[Unit]
Description=FinalToken {role}
Wants=network-online.target
After=network-online.target
[Service]
Type=exec
User={account}
Group={account}
WorkingDirectory={executable.parent}
EnvironmentFile={ETC}/{role}.env
Environment=HOME={home}
Environment=PATH={WORKER_HOME}/.local/bin:/usr/local/bin:/usr/bin:/bin
ExecStart={executable}{arguments}
Restart=on-failure
RestartSec=5
TimeoutStopSec=75
KillMode=control-group
UMask=0077
NoNewPrivileges=true
StandardOutput=null
StandardError=null
[Install]
WantedBy=multi-user.target
"""
def proxy_unit():
return f"""[Unit]
Description=FinalToken HTTPS proxy
After=network-online.target finaltoken-server.service
Wants=network-online.target
[Service]
Type=exec
User=finaltoken-proxy
Group=finaltoken-proxy
Environment=HOME={PROXY_HOME}
Environment=XDG_DATA_HOME={PROXY_HOME}
ExecStart=/usr/bin/caddy run --config {ETC}/Caddyfile --adapter caddyfile
ExecReload=/usr/bin/caddy reload --config {ETC}/Caddyfile --adapter caddyfile
Restart=on-failure
RestartSec=5
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=true
UMask=0077
[Install]
WantedBy=multi-user.target
"""
def configure(meta, enrollment_key=None):
role, providers = meta["role"], meta["providers"]
ETC.mkdir(parents=True, exist_ok=True)
ETC.chmod(0o755)
if role != "worker":
user("finaltoken-server", SERVER_HOME)
user("finaltoken-proxy", PROXY_HOME)
if role != "server":
user("finaltoken", WORKER_HOME)
keys_path = ETC / "transport-keys.json"
if not keys_path.exists():
json_file(keys_path, {"dashboard": secrets.token_hex(32), "worker": enrollment_key or secrets.token_hex(32)}, once=True)
keys = json.loads(keys_path.read_text(encoding="utf-8"))
if role != "worker":
accounts = [{"id": p, "provider": p.capitalize(), "label": p.capitalize(), "expectedEmail": meta["emails"][p], "timeZone": meta["timezone"]}
for p in providers if meta["emails"].get(p)]
machines = [] if role == "server" else [{"id": meta["machineId"], "label": f"LXC {meta['ctid']}", "osUser": "finaltoken",
"profiles": [{"id": p, "accountId": p} for p in providers]}]
json_file(ETC / "server.json", {"accounts": accounts, "machines": machines}, once=True)
atomic(ETC / "server.env", f"FINALTOKEN_SERVER_CONFIG={ETC}/server.json\nFINALTOKEN_SERVER_DATA={SERVER_HOME}/data\n"
f"FINALTOKEN_DASHBOARD_KEY={keys['dashboard']}\nFINALTOKEN_PUBLIC_ORIGIN=https://{meta['domain']}\n"
f"ASPNETCORE_URLS=http://127.0.0.1:5187\nFINALTOKEN_MACHINE_{meta['machineId']}={keys['worker']}\n", once=True)
atomic(ETC / "dashboard-key", keys["dashboard"] + "\n", once=True)
atomic(ETC / "worker-key", keys["worker"] + "\n", once=True)
tls = " tls internal\n" if meta["tls"] == "internal" else ""
atomic(ETC / "Caddyfile", f"{meta['domain']} {{\n{tls} reverse_proxy 127.0.0.1:5187\n}}\n", 0o644, once=True)
atomic(SYSTEMD / "finaltoken-server.service", service_unit("server"), 0o644, once=True)
atomic(SYSTEMD / "finaltoken-proxy.service", proxy_unit(), 0o644, once=True)
run(["systemctl", "disable", "--now", "caddy.service"])
if role != "server":
profiles = [{"id": p, "provider": p.capitalize(), "expectedEmail": meta["emails"][p],
"configDirectory": str(WORKER_HOME / (".claude" if p == "claude" else ".codex")),
"dataDirectory": str(WORKER_HOME / "history" / p), "cliPath": str(WORKER_HOME / ".local/bin" / p)} for p in providers]
json_file(ETC / "worker.json", {"machineId": meta["machineId"], "serverUrl": "http://127.0.0.1:5187" if role == "both" else meta["serverUrl"],
"stateDirectory": str(WORKER_HOME / "collector"), "profiles": profiles}, once=True)
atomic(ETC / "worker.env", "FINALTOKEN_WORKER_KEY=" + keys["worker"] + "\n", once=True)
atomic(SYSTEMD / "finaltoken-worker.service", service_unit("worker"), 0o644, once=True)
# systemd reads env files as root. Only the intended service user can read its JSON config.
for filename, account in (("server.json", "finaltoken-server"), ("worker.json", "finaltoken")):
path = ETC / filename
if path.exists():
path.chmod(0o640)
os.chown(path, 0, pwd.getpwnam(account).pw_gid)
def build(archive, meta):
entry = user("finaltoken-build", BUILD)
temporary = Path(tempfile.mkdtemp(prefix="build-", dir=BUILD))
try:
source = temporary / "src"
unpack(archive, source)
for path in [temporary, *temporary.rglob("*")]:
os.chown(path, entry.pw_uid, entry.pw_gid)
release = temporary / "release"
for project, output in (("FinalToken.Web", "web"), ("FinalToken.Worker", "worker")):
if meta["role"] == "server" and output == "worker" or meta["role"] == "worker" and output == "web":
continue
# D1: build on target Linux with NativeAOT, never copy a Windows executable into LXC.
as_user("finaltoken-build", BUILD, ["dotnet", "publish", str(source / "src" / project / (project + ".csproj")),
"-c", "Release", "-r", "linux-x64", "--self-contained", "true", "-p:PublishAot=true", "-o", str(release / output)], cwd=source)
if meta["role"] != "worker" and not (release / "web/wwwroot/index.html").is_file():
shutil.copytree(source / "src/FinalToken.Web/wwwroot", release / "web/wwwroot", dirs_exist_ok=True)
shutil.copy2(source / "LICENSE", release / "LICENSE")
destination = APP / "releases" / (meta["sourceSha256"][:16] + "-" + uuid.uuid4().hex[:8])
destination.parent.mkdir(parents=True, exist_ok=True)
APP.chmod(0o755)
destination.parent.chmod(0o755)
shutil.copytree(release, destination)
destination.chmod(0o755)
for path in destination.rglob("*"):
path.chmod(0o755 if path.is_dir() else 0o644)
for executable in (destination / "web/FinalToken.Web", destination / "worker/finaltoken-worker"):
wanted = meta["role"] != ("worker" if executable.name == "FinalToken.Web" else "server")
if wanted:
if not executable.is_file():
raise ValueError("Native build did not produce its expected executable")
with executable.open("rb") as stream:
header = stream.read(20)
if header[:4] != b"\x7fELF" or header[18:20] != b"\x3e\x00":
raise ValueError("Published executable is not a Linux x64 ELF binary")
executable.chmod(0o755)
return destination
finally:
# Only this invocation's fresh build directory, never profiles, state or previous releases.
shutil.rmtree(temporary)
def switch(release):
if release.parent.resolve() != (APP / "releases").resolve() or not release.is_dir():
raise ValueError("Release must be an existing direct child of the releases directory")
pending = APP / (".current-" + uuid.uuid4().hex)
try:
pending.symlink_to(release, target_is_directory=True)
os.replace(pending, APP / "current")
finally:
pending.unlink(missing_ok=True)
def units(role):
return (["finaltoken-server.service", "finaltoken-proxy.service"] if role != "worker" else []) + (["finaltoken-worker.service"] if role != "server" else [])
def healthy(services, meta):
for _ in range(20):
live = all(run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0 for s in services)
if live and "finaltoken-server.service" in services:
try:
request = urllib.request.Request("http://127.0.0.1:5187/", headers={"Host": meta["domain"]})
with urllib.request.urlopen(request, timeout=2) as response:
live = response.status == 200
except OSError:
live = False
if live:
# Catch immediate startup failures. Remote provider login is deliberately not a health probe.
time.sleep(2)
return all(run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0 for s in services)
time.sleep(1)
return False
def activate(release, meta, first):
current = APP / "current"
previous = current.resolve() if current.is_symlink() else None
services = units(meta["role"])
active = services if first else [s for s in services if run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0]
try:
switch(release)
run(["systemctl", "daemon-reload"])
if first:
run(["systemctl", "enable", *services])
if active:
run(["systemctl", "restart", *active])
if not healthy(active, meta):
raise ValueError("New release did not pass local service/HTTP health checks")
except Exception:
if previous is not None:
switch(previous)
if active:
run(["systemctl", "restart", *active], check=False)
print("Activation failed; previous binary release restored. State/configuration were not rewound.", file=sys.stderr)
else:
run(["systemctl", "disable", "--now", *services], check=False)
raise
def provision(manifest, archive):
if os.geteuid() != 0 or os.uname().machine != "x86_64":
raise ValueError("Guest setup requires root in a Linux x86_64 CT")
os_release = Path("/etc/os-release").read_text(encoding="utf-8")
if 'ID=debian' not in os_release or 'VERSION_ID="13"' not in os_release:
raise ValueError("Only Debian 13 amd64 guests are supported")
if manifest.get("installer") != INSTALLER or manifest.get("action") not in ("install", "update"):
raise ValueError("Unsupported deployment manifest")
with archive.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
if digest != manifest.get("sourceSha256"):
raise ValueError("Uploaded source checksum mismatch")
marker = ETC / "install.json"
if manifest["action"] == "update":
meta = json.loads(marker.read_text(encoding="utf-8"))
if meta.get("installer") != INSTALLER or meta.get("ctid") != manifest["ctid"]:
raise ValueError("Guest marker does not match selected CT")
meta["sourceSha256"] = digest
else:
if marker.exists():
raise ValueError("An install marker already exists; use update")
meta = {k: v for k, v in manifest.items() if k != "workerKey"}
meta["installed"] = False
json_file(ETC / "transport-keys.json", {"dashboard": secrets.token_hex(32),
"worker": manifest.get("workerKey") or secrets.token_hex(32)}, once=True)
json_file(marker, meta, once=True) # Partial installs can be resumed through update.
first = not meta.get("installed", False)
packages(meta["role"], meta["providers"])
if first:
configure(meta, manifest.get("workerKey"))
if meta["role"] != "server":
official_clis(meta["providers"])
release = build(archive, meta)
activate(release, meta, first)
meta.update(installed=True, release=str(release))
json_file(marker, meta)
if meta["role"] != "worker":
print("Dashboard: https://" + meta["domain"])
print("Dashboard key is root-readable at /etc/finaltoken/dashboard-key (not printed).")
print("Official CLI login still requires your browser authorization. No provider credentials were copied.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--archive", type=Path, required=True)
args = parser.parse_args()
try:
provision(json.loads(args.manifest.read_text(encoding="utf-8")), args.archive)
except (ValueError, OSError, subprocess.CalledProcessError) as error:
print("Guest setup failed: " + (str(error) if isinstance(error, ValueError) else type(error).__name__), file=sys.stderr)
print("Configuration, history and CLI profiles were retained. Inspect services; retry with host update.", file=sys.stderr)
sys.exit(1)
+290
View File
@@ -0,0 +1,290 @@
"""Create/update an unprivileged Debian 13 LXC from a local FinalToken source snapshot."""
import argparse
import hashlib
import ipaddress
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
from urllib.parse import urlsplit
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from source_policy import is_private_path
ROOT = Path(__file__).resolve().parents[2]
PROJECTS = ("FinalToken.Core", "FinalToken.Fleet", "FinalToken.Web", "FinalToken.Worker")
TEMPLATE = re.compile(r"debian-13-standard_[A-Za-z0-9.+_-]+_amd64\.tar\.(?:zst|xz|gz)\Z")
def run(command, *, capture=False, check=True):
command = [str(a) for a in command]
if command[:2] == ["pct", "exec"]:
# Proxmox defaults differ between versions; never forward the host's secret environment.
command[3:3] = ["--keep-env", "0"]
return subprocess.run(command, check=check, text=True,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.PIPE if capture else None)
def identifier(value):
if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,63}", value):
raise ValueError("Machine id must start with a letter and contain only letters, digits and underscores")
return value
def domain_name(value):
if len(value) > 253 or not all(re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", p) for p in value.split(".")) or "." not in value:
raise ValueError("Domain must be a DNS name without a scheme, port, path or shell syntax")
return value.lower()
def server_url(value):
url = urlsplit(value)
if url.scheme != "https" or not url.hostname or url.username or url.password or url.path not in ("", "/") or url.query or url.fragment:
raise ValueError("Remote server URL must be an HTTPS origin")
_ = url.port
return value.rstrip("/")
def parser():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("action", choices=("install", "update"))
p.add_argument("--ctid", type=int, help="New CT id; defaults to Proxmox nextid. Required for update.")
p.add_argument("--source", type=Path, default=ROOT, help="Local checkout including uncommitted source")
p.add_argument("--storage", help="Proxmox rootdir storage, e.g. local-lvm (required for install)")
p.add_argument("--template-storage", default="local")
p.add_argument("--template", help="Optional Debian 13 amd64 standard template filename")
p.add_argument("--bridge", default="vmbr0")
p.add_argument("--ip", default="dhcp", help="dhcp or static IPv4 CIDR")
p.add_argument("--gateway")
p.add_argument("--vlan", type=int)
p.add_argument("--memory", type=int, default=4096, help="MiB; builds need at least 4096")
p.add_argument("--cores", type=int, default=2)
p.add_argument("--disk", type=int, default=20, help="GiB")
p.add_argument("--role", choices=("both", "server", "worker"), help="Install default: both; update preserves role")
p.add_argument("--domain", help="Dashboard DNS name; required for server/both")
p.add_argument("--tls", choices=("acme", "internal"), default="acme")
p.add_argument("--email", help="Expected provider email for both selected providers")
p.add_argument("--claude-email")
p.add_argument("--codex-email")
p.add_argument("--providers", default="claude,codex")
p.add_argument("--machine-id", help="Default: lxc_<ctid>")
p.add_argument("--timezone", default="UTC")
p.add_argument("--server-url", help="Existing HTTPS dashboard, for worker-only install")
p.add_argument("--worker-key-file", type=Path, help="Root-readable enrollment key file; never pass the key as an argument")
p.add_argument("--dry-run", action="store_true", help="Print validated plan; do not run Proxmox or create files")
return p
def validate(args):
if args.ctid is not None and not 100 <= args.ctid <= 999999999:
raise ValueError("CT id must be between 100 and 999999999")
if args.action == "update" and args.ctid is None:
raise ValueError("Update requires --ctid")
args.source = args.source.resolve()
for project in PROJECTS:
if not (args.source / "src" / project / (project + ".csproj")).is_file():
raise ValueError("Source must include the web/worker implementation: " + project)
if args.action == "update":
if args.role or args.domain or args.email or args.claude_email or args.codex_email or args.machine_id or args.server_url or args.worker_key_file:
raise ValueError("Update preserves identity/configuration; pass only CT id and source (plus --dry-run)")
return
args.role = args.role or "both"
for value in (args.storage or "", args.template_storage, args.bridge):
if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_-]{0,63}", value):
raise ValueError("Install requires valid --storage, template-storage and bridge identifiers")
if args.memory < 4096 or args.cores < 1 or args.disk < 12:
raise ValueError("Require memory >=4096 MiB, cores >=1 and disk >=12 GiB for native builds")
if args.vlan is not None and not 1 <= args.vlan <= 4094:
raise ValueError("VLAN must be in 1..4094")
if args.ip != "dhcp":
if not isinstance(ipaddress.ip_interface(args.ip), ipaddress.IPv4Interface):
raise ValueError("Use an IPv4 CIDR")
if not args.gateway:
raise ValueError("Static IP requires --gateway")
if args.gateway:
if args.ip == "dhcp" or not isinstance(ipaddress.ip_address(args.gateway), ipaddress.IPv4Address):
raise ValueError("Gateway is only supported with static IPv4")
if args.template and not TEMPLATE.fullmatch(args.template):
raise ValueError("Template must be a Debian 13 standard amd64 template filename")
if args.role != "worker":
if not args.domain:
raise ValueError("Server/both requires --domain for HTTPS; use --tls internal for a private CA")
args.domain = domain_name(args.domain)
else:
if not args.server_url or not args.worker_key_file:
raise ValueError("Worker-only install requires --server-url and --worker-key-file")
args.server_url = server_url(args.server_url)
args.providers = args.providers.split(",")
if not args.providers or len(set(args.providers)) != len(args.providers) or any(p not in ("claude", "codex") for p in args.providers):
raise ValueError("Providers must be claude, codex, or claude,codex")
for provider in args.providers:
email = getattr(args, provider + "_email") or args.email
if args.role != "server" and (not email or not re.fullmatch(r"[^\s@\x00-\x1f]+@[^\s@\x00-\x1f]+", email) or len(email) > 320):
raise ValueError("Worker/both requires --email or a provider-specific email for each selected provider")
if args.machine_id:
identifier(args.machine_id)
if not re.fullmatch(r"[A-Za-z0-9_+/-]{1,100}", args.timezone) or ".." in args.timezone:
raise ValueError("Invalid timezone id")
if args.role == "worker" and not args.dry_run:
key = args.worker_key_file.read_text(encoding="utf-8").strip()
if not re.fullmatch(r"[A-Za-z0-9_-]{32,512}", key):
raise ValueError("Enrollment file must contain one 32+ character transport key")
args.enrollment_key = key
def create_command(args, ctid, template):
network = f"name=eth0,bridge={args.bridge},ip={args.ip},type=veth,firewall=1"
if args.gateway:
network += ",gw=" + args.gateway
if args.vlan:
network += ",tag=" + str(args.vlan)
return ["pct", "create", str(ctid), f"{args.template_storage}:vztmpl/{template}",
"--hostname", f"finaltoken-{ctid}", "--ostype", "debian", "--arch", "amd64",
"--unprivileged", "1", "--onboot", "1", "--memory", str(args.memory), "--swap", "2048",
"--cores", str(args.cores), "--rootfs", f"{args.storage}:{args.disk}", "--net0", network,
"--description", "FinalToken installer; retains configuration and CLI profiles on update"]
def snapshot(source, destination):
"""Allowlist source inputs, including uncommitted changes, excluding secrets, outputs and symlinks."""
files = [source / n for n in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE")]
for project in PROJECTS:
directory = source / "src" / project
if directory.is_symlink() or directory.resolve() != directory.absolute():
raise ValueError("Source snapshot refuses a symlinked project or parent: " + project)
files.extend(directory.rglob("*"))
total, count = 0, 0
with tarfile.open(destination, "w:gz") as archive:
for path in sorted(set(files)):
relative = path.relative_to(source)
if is_private_path(relative):
continue # .gitignore does not apply to tarfile: do not copy local deployment data.
if any(p in ("bin", "obj", "artifacts", ".git", "node_modules") or p.startswith(".") for p in relative.parts):
continue
if path.is_symlink():
raise ValueError("Source snapshot refuses symlinks: " + str(relative))
if path.is_dir():
continue
if not path.is_file():
raise ValueError("Missing or non-regular source file: " + str(relative))
size = path.stat().st_size
total += size
count += 1
if size > 16 * 1024 * 1024 or total > 256 * 1024 * 1024 or count > 10000:
raise ValueError("Source snapshot exceeds the guest archive bounds")
archive.add(path, arcname=relative.as_posix(), recursive=False)
return hashlib.sha256(destination.read_bytes()).hexdigest()
def execute(args):
if not sys.platform.startswith("linux") or os.geteuid() != 0:
raise ValueError("Run as root on the Proxmox host; --dry-run works without Proxmox")
for program in ("pct", "pvesh", "pveam", "pvesm"):
if not shutil.which(program):
raise ValueError("Missing Proxmox host command: " + program)
import fcntl
with open("/run/lock/finaltoken-proxmox.lock", "w", encoding="utf-8") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
# Prepare and validate the complete source bundle before creating any CT.
with tempfile.TemporaryDirectory(prefix="finaltoken-source-") as directory:
archive = Path(directory) / "source.tar.gz"
sha = snapshot(args.source, archive)
deploy(args, archive, sha)
def deploy(args, archive, sha):
ctid = args.ctid or int(json.loads(run(["pvesh", "get", "/cluster/nextid", "--output-format", "json"], capture=True).stdout))
status = run(["pct", "status", ctid], capture=True, check=False)
if args.action == "install":
if status.returncode == 0:
raise ValueError("CT already exists; refusing to overwrite it. Use update for a managed installation.")
run(["pveam", "update"])
template = args.template
if not template:
available = run(["pveam", "available", "--section", "system"], capture=True).stdout
candidates = [word for word in available.split() if TEMPLATE.fullmatch(word)]
if not candidates:
raise ValueError("No Debian 13 amd64 template found; pass --template explicitly")
template = sorted(candidates, key=lambda s: [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", s)])[-1]
path = run(["pvesm", "path", f"{args.template_storage}:vztmpl/{template}"], capture=True, check=False)
if path.returncode or not Path(path.stdout.strip()).is_file():
run(["pveam", "download", args.template_storage, template])
run(create_command(args, ctid, template))
else:
if status.returncode:
raise ValueError("Cannot access selected CT")
# Reject foreign CTs before starting them or installing packages.
metadata = json.loads(run(["pct", "exec", ctid, "--", "cat", "/etc/finaltoken/install.json"], capture=True).stdout) if "running" in status.stdout else None
if metadata is None:
raise ValueError("Start the existing managed CT before updating; stopped CTs are not modified")
if metadata.get("installer") != "finaltoken-proxmox-v1" or metadata.get("ctid") != ctid:
raise ValueError("Selected CT is not managed by this installer")
if args.action == "install":
run(["pct", "start", ctid])
for _ in range(30):
if run(["pct", "exec", ctid, "--", "test", "-d", "/run/systemd/system"], capture=True, check=False).returncode == 0:
break
time.sleep(1)
else:
raise ValueError("CT did not become ready; it was retained for inspection")
guest = Path(__file__).with_name("guest.py")
token = uuid.uuid4().hex
remote = "/tmp/finaltoken-" + token
with tempfile.TemporaryDirectory(prefix="finaltoken-proxmox-") as tmp:
tmp = Path(tmp)
manifest = {"installer": "finaltoken-proxmox-v1", "ctid": ctid, "action": args.action, "sourceSha256": sha}
if args.action == "install":
manifest.update(role=args.role, domain=args.domain, tls=args.tls, machineId=args.machine_id or f"lxc_{ctid}",
timezone=args.timezone, providers=args.providers, serverUrl=args.server_url,
emails={p: getattr(args, p + "_email") or args.email for p in args.providers})
if args.role == "worker":
manifest["workerKey"] = args.enrollment_key
manifest_path = tmp / "manifest.json"
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
manifest_path.chmod(0o600)
# Only CT packages are changed. The Proxmox host package configuration is untouched.
run(["pct", "exec", ctid, "--", "apt-get", "update"])
run(["pct", "exec", ctid, "--", "env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "python3", "ca-certificates"])
try:
for local, suffix in ((guest, ".py"), (archive, ".tar.gz"), (manifest_path, ".json")):
run(["pct", "push", ctid, local, remote + suffix, "--perms", "0600"])
run(["pct", "exec", ctid, "--", "python3", remote + ".py", "--manifest", remote + ".json", "--archive", remote + ".tar.gz"])
finally:
run(["pct", "exec", ctid, "--", "rm", "-f", remote + ".py", remote + ".json", remote + ".tar.gz"], capture=True, check=False)
print(f"FinalToken {args.action} finished in CT {ctid}. Configuration and state are inside that CT.")
print(f"Inspect services: pct exec {ctid} -- systemctl status 'finaltoken-*'")
print(f"Read dashboard access key, when server installed: pct exec {ctid} -- cat /etc/finaltoken/dashboard-key")
print("No container, profile or history is ever automatically deleted on failure.")
def main(argv=None):
args = parser().parse_args(argv)
validate(args)
if args.dry_run:
role = args.role or "preserve installed role"
print(f"Plan: {args.action} CT {args.ctid or '<next free id>'}; role={role}; source={args.source}")
print("Unprivileged Debian 13 amd64; build NativeAOT inside CT; preserve config, keys, history and CLI profiles.")
if args.action == "install":
print(f"Root storage={args.storage}; template storage={args.template_storage}; bridge={args.bridge}; IP={args.ip}")
print(f"Dashboard={('https://' + args.domain) if args.domain else args.server_url}; TLS={args.tls}")
return 0
execute(args)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except (ValueError, OSError, subprocess.CalledProcessError) as error:
# Never dump captured command output or the manifest (contains service keys).
print("FinalToken setup failed: " + (str(error) if isinstance(error, ValueError) else type(error).__name__), file=sys.stderr)
print("The CT and existing data were retained. Inspect it before retrying.", file=sys.stderr)
sys.exit(1)
+390
View File
@@ -0,0 +1,390 @@
"""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 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_server_update_uses_persisted_identity_and_preserves_config_and_history(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
etc = root / "etc"
etc.mkdir()
archive = root / "source.tgz"
archive.write_bytes(b"updated server fixture")
digest = hashlib.sha256(archive.read_bytes()).hexdigest()
identity = {"installer": guest.INSTALLER, "ctid": 201, "installed": True,
"role": "server", "providers": [], "domain": "usage.example.test",
"sourceSha256": "0" * 64, "release": "previous"}
(etc / "install.json").write_text(json.dumps(identity))
config, history = etc / "server.json", root / "history.json"
config.write_text('{"operator":"custom"}')
history.write_text("synthetic retained history")
manifest = {"installer": guest.INSTALLER, "ctid": 201, "action": "update", "sourceSha256": digest}
original_read = Path.read_text
def read(path, *a, **kw):
return 'ID=debian\nVERSION_ID="13"\n' if path.as_posix() == "/etc/os-release" else original_read(path, *a, **kw)
with patch.object(guest, "ETC", etc), patch.object(guest.os, "geteuid", return_value=0, create=True), \
patch.object(guest.os, "uname", return_value=types.SimpleNamespace(machine="x86_64"), create=True), \
patch.object(Path, "read_text", read), patch.object(guest, "packages") as packages, \
patch.object(guest, "configure") as configure, patch.object(guest, "official_clis") as clis, \
patch.object(guest, "build", return_value=root / "release-v2") as build, \
patch.object(guest, "activate") as activate, contextlib.redirect_stdout(io.StringIO()):
guest.provision(manifest, archive)
packages.assert_called_once_with("server", [])
configure.assert_not_called()
clis.assert_not_called()
activate.assert_called_once_with(root / "release-v2", build.call_args.args[1], False)
updated = json.loads((etc / "install.json").read_text())
self.assertEqual("server", updated["role"])
self.assertEqual("usage.example.test", updated["domain"])
self.assertEqual(digest, updated["sourceSha256"])
self.assertEqual(str(root / "release-v2"), updated["release"])
self.assertEqual('{"operator":"custom"}', config.read_text())
self.assertEqual("synthetic retained history", history.read_text())
def test_native_release_preserves_source_license(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
archive = root / "source.tgz"
license_text = b"Synthetic MIT notice\n"
with tarfile.open(archive, "w:gz") as stream:
item = tarfile.TarInfo("LICENSE")
item.size = len(license_text)
stream.addfile(item, io.BytesIO(license_text))
home = root / "build"
home.mkdir()
def fake_publish(name, home, command, **kwargs):
target = Path(command[command.index("-o") + 1])
target.mkdir(parents=True)
header = b"\x7fELF" + b"\0" * 14 + b"\x3e\x00"
(target / "finaltoken-worker").write_bytes(header)
with patch.object(guest, "APP", root / "app"), patch.object(guest, "BUILD", home), \
patch.object(guest, "user", return_value=types.SimpleNamespace(pw_uid=0, pw_gid=0)), \
patch.object(guest.os, "chown", create=True), patch.object(guest, "as_user", side_effect=fake_publish):
release = guest.build(archive, {"role": "worker", "sourceSha256": "0" * 64})
self.assertEqual(license_text, (release / "LICENSE").read_bytes())
def test_atomic_configuration_is_never_replaced_on_update(self):
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "config.json"
guest.atomic(target, "original", once=True)
self.assertFalse(guest.atomic(target, "replacement", once=True))
self.assertEqual("original", target.read_text())
guest.atomic(target, "explicit replacement")
self.assertEqual("explicit replacement", target.read_text())
self.assertEqual([target], list(target.parent.iterdir()))
def test_archive_rejects_traversal_links_and_devices(self):
for name, kind in (("../escape", tarfile.REGTYPE), ("/absolute", tarfile.REGTYPE), ("link", tarfile.SYMTYPE), ("device", tarfile.CHRTYPE)):
with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
archive = Path(tmp) / "source.tgz"
with tarfile.open(archive, "w:gz") as stream:
item = tarfile.TarInfo(name)
item.type = kind
stream.addfile(item)
with self.assertRaises(ValueError):
guest.unpack(archive, Path(tmp) / "extract")
self.assertFalse((Path(tmp) / "escape").exists())
def test_config_generates_bound_profiles_and_preserves_keys_and_settings(self):
with tempfile.TemporaryDirectory() as tmp, contextlib.ExitStack() as stack:
root = Path(tmp)
for name, relative in (("ETC", "etc"), ("WORKER_HOME", "worker"), ("SERVER_HOME", "server"), ("PROXY_HOME", "proxy"), ("SYSTEMD", "units")):
stack.enter_context(patch.object(guest, name, root / relative))
stack.enter_context(patch.object(guest, "run"))
stack.enter_context(patch.object(guest, "user"))
stack.enter_context(patch.object(guest.pwd, "getpwnam", return_value=types.SimpleNamespace(pw_gid=1000)))
stack.enter_context(patch.object(guest.os, "chown", create=True))
meta = {"role": "both", "providers": ["claude", "codex"], "ctid": 201, "machineId": "lxc_201", "timezone": "UTC",
"domain": "usage.example.test", "tls": "internal", "emails": {"claude": "[email protected]", "codex": "[email protected]"}}
guest.configure(meta)
config = json.loads((guest.ETC / "server.json").read_text())
self.assertEqual("finaltoken", config["machines"][0]["osUser"])
self.assertEqual("lxc_201", config["machines"][0]["id"])
worker = json.loads((guest.ETC / "worker.json").read_text())
self.assertEqual("http://127.0.0.1:5187", worker["serverUrl"])
self.assertEqual(2, len(worker["profiles"]))
keys = (guest.ETC / "transport-keys.json").read_bytes()
(guest.ETC / "worker.json").write_text('{"operator":"custom"}')
guest.configure(meta)
self.assertEqual(keys, (guest.ETC / "transport-keys.json").read_bytes())
self.assertEqual({"operator": "custom"}, json.loads((guest.ETC / "worker.json").read_text()))
self.assertIn("tls internal", (guest.ETC / "Caddyfile").read_text())
def test_units_use_profile_owner_and_kill_child_processes(self):
worker = guest.service_unit("worker")
self.assertIn("User=finaltoken\n", worker)
self.assertIn("KillMode=control-group", worker)
self.assertIn("NoNewPrivileges=true", worker)
self.assertIn("User=finaltoken-server", guest.service_unit("server"))
self.assertNotIn("MemoryDenyWriteExecute", worker) # Node-based CLIs can need JIT.
def test_worker_commands_do_not_inherit_root_environment(self):
with patch.object(guest, "run") as runner:
guest.as_user("finaltoken", PurePosixPath("/worker"), ["claude", "--version"])
command = runner.call_args.args[0]
self.assertIn("-i", command)
self.assertIn("HOME=/worker", command)
self.assertNotIn("shell", runner.call_args.kwargs)
def test_failed_activation_restores_previous_release_without_touching_data(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
old = root / "releases/old"
old.mkdir(parents=True)
new = root / "releases/new"
new.mkdir()
history = root / "history.json"
history.write_text("unchanged")
fake_current = Mock()
fake_current.is_symlink.return_value = True
fake_current.resolve.return_value = old
fake_app = Mock()
fake_app.__truediv__ = Mock(return_value=fake_current)
with patch.object(guest, "APP", fake_app), patch.object(guest, "switch") as switch, \
patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 0)), patch.object(guest, "healthy", return_value=False), \
contextlib.redirect_stderr(io.StringIO()), self.assertRaises(ValueError):
guest.activate(new, {"role": "both"}, False)
self.assertEqual([new, old], [c.args[0] for c in switch.call_args_list])
self.assertEqual("unchanged", history.read_text())
def test_update_does_not_start_intentionally_stopped_services(self):
current = Mock()
current.is_symlink.return_value = False
app = Mock()
app.__truediv__ = Mock(return_value=current)
with patch.object(guest, "APP", app), patch.object(guest, "switch"), patch.object(guest, "healthy") as health, \
patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 3)) as runner:
guest.activate(Path("unused"), {"role": "worker"}, False)
health.assert_not_called()
self.assertFalse(any("restart" in call.args[0] or "enable" in call.args[0] for call in runner.call_args_list))
def test_enrollment_key_survives_partial_install_before_packages_fail(self):
with tempfile.TemporaryDirectory() as tmp:
directory = Path(tmp)
archive = directory / "source.tgz"
archive.write_bytes(b"fixture")
meta = {"installer": guest.INSTALLER, "action": "install", "ctid": 201,
"sourceSha256": hashlib.sha256(b"fixture").hexdigest(), "workerKey": "a" * 64}
original_read = Path.read_text
def read(path, *a, **kw):
return 'ID=debian\nVERSION_ID="13"\n' if path.as_posix() == "/etc/os-release" else original_read(path, *a, **kw)
with patch.object(guest, "ETC", directory / "etc"), patch.object(guest.os, "geteuid", return_value=0, create=True), \
patch.object(guest.os, "uname", return_value=types.SimpleNamespace(machine="x86_64"), create=True), \
patch.object(Path, "read_text", read), patch.object(guest, "packages", side_effect=ValueError("network failure")):
meta.update(role="worker", providers=["codex"])
with self.assertRaises(ValueError):
guest.provision(meta, archive)
marker = json.loads((directory / "etc/install.json").read_text())
keys = json.loads((directory / "etc/transport-keys.json").read_text())
self.assertFalse(marker["installed"])
self.assertNotIn("workerKey", marker)
self.assertEqual("a" * 64, keys["worker"])
if __name__ == "__main__":
unittest.main()
+189
View File
@@ -0,0 +1,189 @@
"""Real local Git/Bash updater checks. No network, Proxmox, package or service changes."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "proxmox-update.sh"
GIT = shutil.which("git")
WINDOWS_BASH = Path(GIT).resolve().parents[1] / "bin/bash.exe" if GIT else Path("missing")
BASH = str(WINDOWS_BASH) if os.name == "nt" and WINDOWS_BASH.is_file() else shutil.which("bash")
class UpdaterTests(unittest.TestCase):
def setUp(self):
if not GIT or not BASH:
self.fail("Git and Bash are required for the updater integration checks")
self.temporary = tempfile.TemporaryDirectory(prefix="finaltoken-update-")
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.seed, self.remote, self.clone = (self.root / n for n in ("seed", "remote.git", "clone"))
self.output = self.root / "invocation"
self.env = dict(os.environ, GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_SYSTEM=os.devnull,
GIT_CONFIG_NOSYSTEM="1", GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="Never",
FT_TEST_RESULT=self.output.as_posix())
self.git(self.root, "init", "--bare", "--initial-branch=master", str(self.remote))
self.git(self.root, "init", "--initial-branch=master", str(self.seed))
(self.seed / "tools").mkdir()
(self.seed / "tools/proxmox-update.sh").write_bytes(SCRIPT.read_bytes())
(self.seed / ".gitignore").write_text("ignored-state/\n")
self.installer("v1")
self.commit(self.seed, "Initial fixture")
self.git(self.seed, "remote", "add", "origin", str(self.remote))
self.git(self.seed, "push", "-u", "origin", "master")
self.git(self.root, "clone", str(self.remote), str(self.clone))
# Git Bash has no flock. Exercise its refusal path with this command seam;
# Linux advisory locking itself is deliberately not claimed by these tests.
self.bin = self.root / "bin"
self.bin.mkdir()
(self.bin / "flock").write_text('#!/usr/bin/env bash\nexit "${FT_TEST_LOCK_EXIT:-0}"\n')
(self.bin / "flock").chmod(0o755)
self.env["PATH"] = str(self.bin) + os.pathsep + self.env["PATH"]
def git(self, directory, *arguments):
return subprocess.run([GIT, "-c", "user.name=Fixture", "-c", "[email protected]",
"-c", "commit.gpgsign=false", "-c", "core.hooksPath=", "-C", str(directory),
*arguments], env=self.env, text=True, capture_output=True, check=True)
def commit(self, directory, message):
self.git(directory, "add", ".")
self.git(directory, "commit", "-m", message)
def installer(self, version):
(self.seed / "tools/proxmox.sh").write_text(
'#!/usr/bin/env bash\nset -euo pipefail\n'
f'printf "%s\\n" "{version}" "$@" > "$FT_TEST_RESULT"\n'
'exit "${FT_TEST_EXIT:-0}"\n')
def publish(self):
self.installer("v2")
self.commit(self.seed, "Update fixture installer")
self.git(self.seed, "push")
def update(self, *arguments):
# The caller's cwd deliberately differs from the checkout location.
return subprocess.run([BASH, str(self.clone / "tools/proxmox-update.sh"), *arguments],
cwd=self.root, env=self.env, text=True, capture_output=True)
def test_refresh_executes_new_installer_and_passes_exact_ctid_and_source(self):
self.publish()
result = self.update("201")
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
lines = self.output.read_text().splitlines()
self.assertEqual(["v2", "update", "--ctid", "201", "--source"], lines[:-1])
# Git Bash reports /c/... while native Windows Python uses C:/....
self.assertTrue(lines[-1].replace("\\", "/").endswith("/clone"))
self.assertEqual(self.git(self.seed, "rev-parse", "HEAD").stdout,
self.git(self.clone, "rev-parse", "HEAD").stdout)
def test_no_new_commit_still_runs_installer_to_resume_failed_deployment(self):
result = self.update("201")
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
self.assertEqual("v1", self.output.read_text().splitlines()[0])
def test_dry_run_never_fetches_or_changes_checkout(self):
before = self.git(self.clone, "rev-parse", "HEAD").stdout
self.publish()
result = self.update("201", "--dry-run")
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
self.assertIn("--dry-run", self.output.read_text().splitlines())
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
self.assertFalse((self.clone / ".git/FETCH_HEAD").exists())
self.assertFalse((self.clone / ".git/finaltoken-proxmox-update.lock").exists())
def test_dirty_tracked_staged_or_untracked_source_is_retained_and_not_deployed(self):
for state in ("tracked", "staged", "untracked"):
with self.subTest(state=state):
path = self.clone / ("local.txt" if state == "untracked" else ".gitignore")
original = path.read_bytes() if path.exists() else None
path.write_text("operator local change\n")
if state == "staged":
self.git(self.clone, "add", str(path))
result = self.update("201")
self.assertNotEqual(0, result.returncode)
self.assertIn("clean", result.stderr)
self.assertFalse(self.output.exists())
self.assertEqual("operator local change\n", path.read_text())
self.git(self.clone, "reset", "--", str(path))
if original is None:
path.unlink()
else:
path.write_bytes(original)
def test_diverged_or_ahead_branch_is_not_deployed_or_reset(self):
(self.clone / "operator.txt").write_text("local commit fixture")
self.commit(self.clone, "Local-only fixture")
before = self.git(self.clone, "rev-parse", "HEAD").stdout
for diverged in (False, True):
with self.subTest(diverged=diverged):
if diverged:
self.publish()
result = self.update("201")
self.assertNotEqual(0, result.returncode)
self.assertFalse(self.output.exists())
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
self.assertEqual("local commit fixture", (self.clone / "operator.txt").read_text())
def test_no_upstream_or_detached_head_never_deploys(self):
self.git(self.clone, "branch", "--unset-upstream")
self.assertNotEqual(0, self.update("201").returncode)
self.git(self.clone, "checkout", "--detach")
self.assertNotEqual(0, self.update("201").returncode)
self.assertFalse(self.output.exists())
def test_fetch_failure_leaves_checkout_and_does_not_deploy_or_echo_remote(self):
self.git(self.clone, "remote", "set-url", "origin", str(self.root / "private-origin-not-available"))
before = self.git(self.clone, "rev-parse", "HEAD").stdout
result = self.update("201")
self.assertNotEqual(0, result.returncode)
self.assertNotIn("private-origin-not-available", result.stdout + result.stderr)
self.assertFalse(self.output.exists())
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
def test_busy_checkout_never_pulls_or_deploys(self):
self.env["FT_TEST_LOCK_EXIT"] = "1"
self.publish()
before = self.git(self.clone, "rev-parse", "HEAD").stdout
self.assertNotEqual(0, self.update("201").returncode)
self.assertFalse(self.output.exists())
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
def test_installer_failure_propagates_and_keeps_ignored_local_state(self):
state = self.clone / "ignored-state/history.json"
state.parent.mkdir()
state.write_text("synthetic local history")
self.env["FT_TEST_EXIT"] = "17"
result = self.update("201")
self.assertEqual(17, result.returncode, result.stdout + result.stderr)
self.assertEqual("synthetic local history", state.read_text())
def test_upstream_cannot_overwrite_ignored_operator_state(self):
relative = "ignored-state/history.json"
local = self.clone / relative
local.parent.mkdir()
local.write_text("synthetic retained operator history")
upstream = self.seed / relative
upstream.parent.mkdir()
upstream.write_text("upstream fixture must not overwrite operator data")
self.git(self.seed, "add", "--force", relative)
self.publish()
before = self.git(self.clone, "rev-parse", "HEAD").stdout
result = self.update("201")
self.assertNotEqual(0, result.returncode)
self.assertFalse(self.output.exists())
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
self.assertEqual("synthetic retained operator history", local.read_text())
def test_invalid_arguments_are_rejected_before_fetch(self):
for arguments in ((), ("99",), ("201", "--source", "/tmp/other"), ("201;touch /tmp/no",), ("201", "--unknown")):
with self.subTest(arguments=arguments):
self.assertNotEqual(0, self.update(*arguments).returncode)
self.assertFalse(self.output.exists())
self.assertFalse((self.clone / ".git/FETCH_HEAD").exists())
if __name__ == "__main__":
unittest.main()