tools: update inside LXC and use the existing proxy #22

Merged
schmidt.florian merged 2 commits from 21-external-proxy into master 2026-11-15 13:06:06 +01:00
20 changed files with 617 additions and 607 deletions
Showing only changes of commit 7b70c7a0fa - Show all commits
+1 -1
View File
@@ -6,7 +6,7 @@
- [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] Proxmox host creates the CT only. Existing HTTPS proxy targets private HTTP :5187; no bundled proxy is installed. `finaltoken-update` fetches a fresh public source tree and builds/activates inside the CT, preserving state. Legacy migration changes only the known listener and disables the owned proxy; binaries and listener have separate rollback.
- [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.
+1
View File
@@ -15,5 +15,6 @@
- [2026-11-15] npm's local `--prefix` install writes `node_modules/.bin`; the Linux worker's `.local/bin/codex` requires a user-owned global prefix. The regression installs an offline synthetic package with real npm.
- [2026-11-15] Compare copied/archived license bytes with source bytes. `read_text()` normalizes Windows CRLF while ZIP reads retain it; explicit LF/CRLF fixtures cover both checkouts.
- [2026-11-15] Do not assume a bundled proxy or host-driven updates for LXC deployments. Use the operator's existing proxy and an in-container updater; preserve the public Host/Origin when the private backend uses HTTP.
## Archive
+2 -2
View File
@@ -2,7 +2,7 @@
> Always-loaded. Everything else is on-demand. Update TOC when files change.
## Current Focus
- [2026-11-15] Validate live Linux/LXC/TLS and official provider login. D14 dashboard/workers and Proxmox delivery are implemented in 1.2.0.
- [2026-11-15] Validate live Linux/LXC and official provider login. 1.2.1 corrects deployment to use the existing HTTPS proxy and updates inside the CT.
## Invariants
- 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).
@@ -11,5 +11,5 @@
- Desktop/Stream Deck retain `snapshot.json` (D9); the optional authenticated server/worker transport is separate (D14).
## Table of Contents
- `gotchas.md` — 10 entries — CLI login, Proxmox/npm/update safety, publication checks and Avalonia tooltips.
- `gotchas.md` — 11 entries — CLI login, existing-proxy/in-container updates, publication checks and Avalonia tooltips.
- `architecture.md` — 7 entries — Fleet analysis, attribution, migration, authentication, durability, Proxmox and publication.
+1
View File
@@ -1,2 +1,3 @@
tools/proxmox*.sh text eol=lf
tools/proxmox/*.py text eol=lf
tools/lxc_update.py text eol=lf
+3 -3
View File
@@ -137,10 +137,10 @@ a screenshot of each changed view: compiling is not working.
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
- `tools/proxmox.sh`: creates 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/lxc_update.py`: installed as `finaltoken-update` inside the CT. Fetches/builds/activates
locally without Proxmox host commands; 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`.
+1 -1
View File
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<Version>1.2.0</Version>
<Version>1.2.1</Version>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14</LangVersion>
<Nullable>enable</Nullable>
+2 -1
View File
@@ -13,7 +13,8 @@ daily budgets and reset history reuse the desktop app's analysis. Missing or log
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.
It creates a server-only LXC behind your existing HTTPS proxy. Run `finaltoken-update` inside
the container for updates; no Proxmox-host checkout is needed afterwards.
## Requirements
+6
View File
@@ -328,6 +328,12 @@ worker per OS user, following the developer's direction in
Local settings remain local; the newest quota observation's profile supplies the pace threshold,
hidden windows and freshness interval. Account timezone controls calendar days. No working-hour
forecast is added. Old/expired limits are displayed but have no current forecast.
- The Proxmox host script creates the LXC only. It does not install a reverse proxy. The server
exposes private HTTP port 5187 behind the operator's existing HTTPS proxy, preserving Host.
`finaltoken-update` fetches/builds/activates updates inside the container. An update from the
old bundled-proxy layout changes its known listener and disables only the installer-owned
proxy, with configuration rollback on a failed backend check. See
[the deployment guide](proxmox.md).
- Quota is the newest observed account/window value, never the sum across machines. Consumption
uses Claude response ids and ordered Codex session cumulative counts across machine copies.
Conflicting event metadata is excluded with a warning. Raw metadata history and observations
+129 -208
View File
@@ -1,95 +1,13 @@
# 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 the **Proxmox host only to create the container**. Updates run **inside the LXC**.
FinalToken uses your existing HTTPS reverse proxy and installs no Caddy or other proxy.
The private backend listens on **HTTP port 5187**. 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 the server
## 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 you@example.com --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 you@example.com
```
`--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:
As root on the Proxmox host, with Git and Python 3 installed:
```bash
git clone --branch master --single-branch https://git.finalfactory.de/FinalFactory/FinalToken.git /opt/finaltoken-src && \
@@ -97,18 +15,93 @@ git clone --branch master --single-branch https://git.finalfactory.de/FinalFacto
--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.
Use a free CT id and your storage, hostname and timezone. Omit `--ctid` for the next free id.
The hostname is the public hostname on **your existing proxy**, not a certificate request.
Add `--dry-run` to validate without creating a CT. Anonymous HTTPS clone needs no Git login.
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.
Configure your existing reverse proxy:
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.
- Public URL: `https://usage.example.com` (your chosen hostname).
- Backend: `http://<LXC-IP>:5187`.
- Preserve the public `Host` header. Restrict backend network access to your proxy/private network.
- Allow worker metadata POST bodies up to 32 MiB, matching the server's request-size limit.
- TLS/certificates stay on your existing proxy. The LXC needs no inbound 80/443 or certificates.
The server pins its public Host/Origin and uses secure browser cookies. Do not expose this private
HTTP backend directly to the Internet or remove authentication. No forwarded-header trust is enabled.
The proxy must not log authorization headers or request bodies containing login responses.
Read the dashboard key on the CT's root console:
```bash
cat /etc/finaltoken/dashboard-key
```
`--role server` installs no coding CLIs or worker. Optional `--email` seeds provider account
metadata; no provider email/login is needed to install the server. Configure account/machine
bindings and distinct machine keys as in [web setup](web-dashboard.md#run-locally).
## Update inside the container
Open the LXC console as root and run:
```bash
finaltoken-update
```
This fetches public `master` into temporary source, builds NativeAOT as the isolated build user,
and activates the update **inside this container**. It does not call `pct`, contact the Proxmox
host or require the original host checkout. It preserves the CT role, service keys, settings,
CLI profiles and history. Official provider CLIs keep their own update/login lifecycle.
The updater is included in each binary release, so switching/rolling back releases updates it too.
```bash
finaltoken-update --dry-run
```
Dry-run reads the managed marker and prints the plan without downloading or changing services.
Concurrent updates are refused. A new binary release is built before switching `current`;
only previously running services restart, and a failed local health check restores the old binaries.
Stopped services stay stopped. Package/configuration/history rollback is not implied by binary rollback.
### Existing 1.2.0 containers
The old installer did not install this command and bundled a proxy. Run the following **once as
root inside that LXC** to fetch the corrected updater and perform the update:
```bash
(
set -e
update_script=$(mktemp)
trap 'rm -f -- "$update_script"' EXIT
curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
https://git.finalfactory.de/FinalFactory/FinalToken/raw/branch/master/tools/lxc_update.py \
--output "$update_script"
python3 "$update_script"
)
```
This installs Git in the CT if needed, updates the app, changes the old known loopback listener
to `0.0.0.0:5187` and disables **only** `finaltoken-proxy.service`. Point your existing proxy at
HTTP port 5187. Keys, public hostname, profiles, history, certificate files and installed packages
are retained. It does not stop an unrelated `caddy.service` or purge packages/configuration.
The old server environment is backed up as root-only `server.env.pre-external-proxy`. If the
backend health check fails, its listener and prior service states are restored. A custom listener
is retained and migration reports that it needs manual configuration. The application update
may already have succeeded when a later network migration fails; retry after fixing the cause.
Subsequent updates need only `finaltoken-update`. The old host updater refuses deployment and
points to this in-container command.
## Install dashboard and client
Omit `--role server` (or choose `--role both`) to create a CT that also collects its own coding
CLI usage. Add `--email [email protected]`; provider-specific emails override it independently.
The installer installs official CLIs as their own user and never performs provider login.
Open the dashboard and use **Log in / renew** for the selected profile.
It observes only coding activity inside this CT, not desktop activity on another machine.
For a worker-only CT, configure the matching machine/account/key on the existing server first:
```bash
bash tools/proxmox.sh install --ctid 202 --storage local-lvm --role worker \
@@ -116,108 +109,55 @@ bash tools/proxmox.sh install --ctid 202 --storage local-lvm --role worker \
--worker-key-file /root/lxc_202.key --email you@example.com
```
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.
The enrollment file holds a FinalToken transport key, not a provider token. The worker's OS user
is `finaltoken`; selected provider names are its profile ids. Workers connect outbound over HTTPS.
Use `finaltoken-update` inside worker CTs too.
`--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.
## Host and container requirements
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.
The host needs `pct`, `pvesh`, `pveam`, `pvesm` and Python 3. Its package repositories are untouched.
Creation uses an unprivileged Debian 13 amd64 standard CT, DHCP on `vmbr0`, on-boot startup,
2 cores, 4096 MiB RAM, 2048 MiB swap and a 20 GiB root disk. No privileged mode/nesting is enabled.
The CT needs DNS/outbound HTTPS and working package repositories. Builds install .NET 10/native
prerequisites and Git in the CT and run under `finaltoken-build`, not root. Increase resources
when needed. This is not an offline or byte-for-byte reproducible dependency build.
## Update or resume a partial installation
For static IPv4, add `--ip 192.0.2.20/24 --gateway 192.0.2.1`; `--bridge`, `--vlan`,
`--template-storage` and `--template` select host-specific resources. No host firewall, DNS or NAT
rules are changed. Your existing proxy must reach the CT on port 5187.
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`.
The host installer snapshots the selected local checkout, including uncommitted source, through
the shared allowlist in `tools/proxmox/source_bundle.py`. It excludes recognized local config,
credentials and runtime data independently of Git ignore rules, rejects symlinks and bounds size.
`--source` selects a different local checkout. It never overwrites an existing CT.
## 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 |
| `/etc/finaltoken/install.json` | Managed identity, role, source checksum and successful release |
| `/etc/finaltoken/server.json`, `worker.json` | Operator account/profile configuration |
| `/etc/finaltoken/server.env`, `worker.env` | Root-only service environment and transport keys |
| `/opt/finaltoken/releases/`, `/opt/finaltoken/current` | Root-owned native releases and updater |
| `/usr/local/sbin/finaltoken-update` | Link to the active release's in-container updater |
| `/var/lib/finaltoken-server/`, `/var/lib/finaltoken-worker/` | Metadata, history and CLI-owned profiles |
| `/var/cache/finaltoken-build/` | Separate build user's cache; temporary source is 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`.
No CT or old release is automatically deleted. A future incompatible schema needs its own
migration/backup plan. Update/restart interrupts pending CLI login attempts.
```bash
pct exec 201 -- systemctl status finaltoken-server finaltoken-worker finaltoken-proxy
pct exec 201 -- journalctl -u finaltoken-worker -u finaltoken-server --since today
systemctl status finaltoken-server finaltoken-worker
journalctl -u finaltoken-server -u finaltoken-worker --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`.
Units use non-root users, restrictive permissions and process-group shutdown. Application output
is discarded to keep CLI/login material out of the journal; service lifecycle events remain.
Never dump provider credential files into support reports. For coding in a worker CT use
`su - finaltoken`; its installed 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
@@ -226,28 +166,9 @@ 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.
One installer regression uses real Node.js/npm with an offline synthetic package to check the
configured Codex launcher and repeat installation. It skips explicitly when Node.js/npm are
unavailable. On Windows its fixture adapts npm's global-prefix layout to the guest's Linux `bin`
path; that checks npm install mode and actual files without claiming Linux execution.
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).
Tests substitute Proxmox, systemd, native publishing, package operations and Linux locking.
They cover source safety, service/config/key preservation, failed activation and legacy proxy
migration rollback. Updater tests use real local Git clones with a synthetic guest provisioner.
The npm regression uses an offline synthetic package and real npm; Windows adapts its global
prefix boundary to the expected Linux launcher directory. It explicitly skips without Node/npm.
No real Linux/LXC update, NativeAOT publish, advisory locking or provider login is claimed by these tests.
+3 -3
View File
@@ -18,14 +18,14 @@ bash tools/proxmox.sh install --ctid 201 --storage local-lvm \
--domain usage.example.com --email you@example.com
```
For a later update, refresh and deploy the clean checkout with one command:
For a later update, run as root **inside the LXC**:
```bash
bash tools/proxmox-update.sh 201
finaltoken-update
```
Here `--email` is the intended **provider account identity**, not a Git login. The installer
reads the local checkout; the separate updater fetches its tracking branch first. The branch being cloned must contain the
reads the local checkout only during creation; the in-container updater fetches public master itself. The branch being cloned must contain the
web/worker/installer changes. A public visibility setting alone does not publish uncommitted work.
## Files to keep local
+2
View File
@@ -16,3 +16,5 @@ Each requirement has a stable ID. [Decisions](decisions.md) say how FinalToken m
- **R8** An authenticated self-hosted dashboard combines the user's Windows/Linux machines,
keeping weekly sustainability central, account quota separate from deduplicated consumption,
and measured, estimated, unknown and stale values distinct. See [D14](decisions.md#d14--self-hosted-dashboard-and-workers).
Proxmox installation uses the host only to create the CT. Updates run inside the CT; HTTPS
comes from the user's existing reverse proxy.
+5 -2
View File
@@ -7,7 +7,9 @@ There is no inference gateway. Coding traffic continues through the user's own c
## Run locally
For automatic CT creation from a Proxmox host, use the [Proxmox install/update script](proxmox.md).
For automatic CT creation from a Proxmox host, use the [Proxmox installer](proxmox.md).
It uses your existing HTTPS proxy and exposes private HTTP :5187; updates run inside the CT
with `finaltoken-update`.
Build from the repository root:
@@ -51,7 +53,8 @@ By default it listens on `http://127.0.0.1:5187`. Open exactly that URL and ente
For a remote deployment, set `FINALTOKEN_PUBLIC_ORIGIN` to the public HTTPS origin and run a TLS
reverse proxy that preserves its Host header, or configure HTTPS directly in Kestrel.
`ASPNETCORE_URLS` changes the listening address. Do not expose a plain HTTP listener to a remote
network. No forwarded-header trust is enabled automatically. Restrict direct backend access;
network. A private HTTP hop from your existing TLS proxy is supported; restrict that backend
listener to the proxy/private network. No forwarded-header trust is enabled automatically. Restrict direct backend access;
the reverse proxy must not log request bodies or authorization headers. Login URLs/codes are
deliberately absent from server logs and disk state. TLS termination sees the transient code.
Keys authorize all profiles on their configured machine; use service-account file/environment
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Run as root INSIDE a managed FinalToken LXC. Fetch, build and activate the update here."""
import argparse
from contextlib import contextmanager
import importlib.util
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
ETC = Path("/etc/finaltoken")
REPOSITORY = "https://git.finalfactory.de/FinalFactory/FinalToken.git"
LOCK = Path("/run/lock/finaltoken-update.lock")
def run(command, **kwargs):
env = {key: os.environ[key] for key in ("PATH", "SystemRoot", "ComSpec", "PATHEXT", "TEMP", "TMP", "LANG", "LC_ALL") if key in os.environ}
env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull,
GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="Never")
return subprocess.run(list(map(str, command)), check=True, text=True, capture_output=True,
timeout=300, env=env, **kwargs)
@contextmanager
def update_lock():
import fcntl
with LOCK.open("w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
def load(name, path):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dry-run", action="store_true", help="Read metadata and print the plan; no fetch or changes")
args = parser.parse_args(argv)
if not sys.platform.startswith("linux") or os.geteuid() != 0:
raise ValueError("Run finaltoken-update as root INSIDE the FinalToken LXC, not on the Proxmox host")
if not (ETC / "install.json").is_file():
raise ValueError("No managed container marker; run finaltoken-update INSIDE the FinalToken LXC")
marker = json.loads((ETC / "install.json").read_text(encoding="utf-8"))
if marker.get("installer") != "finaltoken-proxmox-v1" or marker.get("role") not in ("server", "worker", "both") or not isinstance(marker.get("ctid"), int):
raise ValueError("This is not a managed FinalToken container")
if args.dry_run:
print("Plan: fetch public master, build and update inside this container; preserve keys, profiles and history.")
if marker["role"] != "worker":
print("Backend: HTTP :5187 behind your existing HTTPS proxy; disable only the old FinalToken proxy.")
return 0
with update_lock():
if not shutil.which("git"):
run(["apt-get", "update"])
run(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "git", "ca-certificates"])
with tempfile.TemporaryDirectory(prefix="finaltoken-update-") as directory:
directory = Path(directory)
source = directory / "source"
print("Fetching FinalToken master inside the container...", flush=True)
run(["git", "-c", "credential.helper=", "clone", "--depth", "1", "--branch", "master",
"--single-branch", REPOSITORY, source])
bundle = load("finaltoken_source_bundle", source / "tools/proxmox/source_bundle.py")
archive = directory / "source.tar.gz"
checksum = bundle.snapshot(source, archive)
guest = load("finaltoken_guest_update", source / "tools/proxmox/guest.py")
guest.provision({"installer": marker["installer"], "action": "update", "ctid": marker["ctid"],
"sourceSha256": checksum}, archive)
print("Update complete. Future updates: finaltoken-update")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except (ValueError, OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
print("FinalToken update failed: " + (str(error) if isinstance(error, ValueError) else type(error).__name__), file=sys.stderr)
print("Existing data retained. Fix the cause and retry inside this container.", file=sys.stderr)
sys.exit(1)
+3 -64
View File
@@ -1,66 +1,5 @@
#!/usr/bin/env bash
# Run from a dedicated trusted clone on the Proxmox host. Always enter the fetched installer.
# Kept only to explain the update entry point to older installations.
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"
printf '%s\n' 'Updates run INSIDE the FinalToken LXC as root: finaltoken-update' 'For a 1.2.0 container, see docs/proxmox.md for the one-time updater bootstrap.' >&2
exit 2
+1 -1
View File
@@ -1,2 +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`.
Host creates only a new explicitly selected CT. Updates run inside the CT with finaltoken-update and require this installer's marker. Use the operator's existing reverse proxy; new installs expose private HTTP :5187 and never install a proxy. Legacy migration may change only the known listener and disable finaltoken-proxy.service; preserve keys/data and unrelated services. Never destroy a CT, alter host package repositories or read provider credentials. Builds run inside the CT as an isolated user. Keep commands as argv lists. Test with `python -B tools/proxmox/test_installer.py` and `python -B tools/proxmox/test_update.py`.
+60 -39
View File
@@ -5,6 +5,7 @@ import json
import os
from pathlib import Path, PurePosixPath
import pwd
import re
import secrets
import shutil
import subprocess
@@ -21,7 +22,7 @@ APP = Path("/opt/finaltoken")
BUILD = Path("/var/cache/finaltoken-build")
SERVER_HOME = Path("/var/lib/finaltoken-server")
WORKER_HOME = Path("/var/lib/finaltoken-worker")
PROXY_HOME = Path("/var/lib/finaltoken-proxy")
UPDATER = Path("/usr/local/sbin/finaltoken-update")
SYSTEMD = Path("/etc/systemd/system")
@@ -38,7 +39,7 @@ def atomic(path, data, mode=0o600, *, once=False):
temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp")
try:
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
with os.fdopen(fd, "w", encoding="utf-8") as stream:
with os.fdopen(fd, "w", encoding="utf-8", newline="") as stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
@@ -93,9 +94,7 @@ def as_user(name, home, command, cwd=None):
def packages(role, providers):
run(["apt-get", "update"])
wanted = ["ca-certificates", "curl", "clang", "zlib1g-dev", "libicu-dev", "libssl-dev", "tzdata"]
if role != "worker":
wanted.append("caddy")
wanted = ["git", "ca-certificates", "curl", "clang", "zlib1g-dev", "libicu-dev", "libssl-dev", "tzdata"]
if role != "server" and "codex" in providers:
wanted.extend(["nodejs", "npm"])
run(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", *wanted])
@@ -160,39 +159,12 @@ WantedBy=multi-user.target
"""
def proxy_unit():
return f"""[Unit]
Description=FinalToken HTTPS proxy
After=network-online.target finaltoken-server.service
Wants=network-online.target
[Service]
Type=exec
User=finaltoken-proxy
Group=finaltoken-proxy
Environment=HOME={PROXY_HOME}
Environment=XDG_DATA_HOME={PROXY_HOME}
ExecStart=/usr/bin/caddy run --config {ETC}/Caddyfile --adapter caddyfile
ExecReload=/usr/bin/caddy reload --config {ETC}/Caddyfile --adapter caddyfile
Restart=on-failure
RestartSec=5
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=true
UMask=0077
[Install]
WantedBy=multi-user.target
"""
def configure(meta, enrollment_key=None):
role, providers = meta["role"], meta["providers"]
ETC.mkdir(parents=True, exist_ok=True)
ETC.chmod(0o755)
if role != "worker":
user("finaltoken-server", SERVER_HOME)
user("finaltoken-proxy", PROXY_HOME)
if role != "server":
user("finaltoken", WORKER_HOME)
keys_path = ETC / "transport-keys.json"
@@ -207,14 +179,10 @@ def configure(meta, enrollment_key=None):
json_file(ETC / "server.json", {"accounts": accounts, "machines": machines}, once=True)
atomic(ETC / "server.env", f"FINALTOKEN_SERVER_CONFIG={ETC}/server.json\nFINALTOKEN_SERVER_DATA={SERVER_HOME}/data\n"
f"FINALTOKEN_DASHBOARD_KEY={keys['dashboard']}\nFINALTOKEN_PUBLIC_ORIGIN=https://{meta['domain']}\n"
f"ASPNETCORE_URLS=http://127.0.0.1:5187\nFINALTOKEN_MACHINE_{meta['machineId']}={keys['worker']}\n", once=True)
f"ASPNETCORE_URLS=http://0.0.0.0:5187\nFINALTOKEN_MACHINE_{meta['machineId']}={keys['worker']}\n", once=True)
atomic(ETC / "dashboard-key", keys["dashboard"] + "\n", once=True)
atomic(ETC / "worker-key", keys["worker"] + "\n", once=True)
tls = " tls internal\n" if meta["tls"] == "internal" else ""
atomic(ETC / "Caddyfile", f"{meta['domain']} {{\n{tls} reverse_proxy 127.0.0.1:5187\n}}\n", 0o644, once=True)
atomic(SYSTEMD / "finaltoken-server.service", service_unit("server"), 0o644, once=True)
atomic(SYSTEMD / "finaltoken-proxy.service", proxy_unit(), 0o644, once=True)
run(["systemctl", "disable", "--now", "caddy.service"])
if role != "server":
profiles = [{"id": p, "provider": p.capitalize(), "expectedEmail": meta["emails"][p],
"configDirectory": str(WORKER_HOME / (".claude" if p == "claude" else ".codex")),
@@ -249,6 +217,7 @@ def build(archive, meta):
if meta["role"] != "worker" and not (release / "web/wwwroot/index.html").is_file():
shutil.copytree(source / "src/FinalToken.Web/wwwroot", release / "web/wwwroot", dirs_exist_ok=True)
shutil.copy2(source / "LICENSE", release / "LICENSE")
shutil.copy2(source / "tools/lxc_update.py", release / "finaltoken-update")
destination = APP / "releases" / (meta["sourceSha256"][:16] + "-" + uuid.uuid4().hex[:8])
destination.parent.mkdir(parents=True, exist_ok=True)
APP.chmod(0o755)
@@ -267,6 +236,7 @@ def build(archive, meta):
if header[:4] != b"\x7fELF" or header[18:20] != b"\x3e\x00":
raise ValueError("Published executable is not a Linux x64 ELF binary")
executable.chmod(0o755)
(destination / "finaltoken-update").chmod(0o755)
return destination
finally:
# Only this invocation's fresh build directory, never profiles, state or previous releases.
@@ -285,7 +255,54 @@ def switch(release):
def units(role):
return (["finaltoken-server.service", "finaltoken-proxy.service"] if role != "worker" else []) + (["finaltoken-worker.service"] if role != "server" else [])
return (["finaltoken-server.service"] if role != "worker" else []) + (["finaltoken-worker.service"] if role != "server" else [])
def install_updater():
target = APP / "current/finaltoken-update"
if UPDATER.is_symlink() and UPDATER.readlink() == target:
return
if UPDATER.exists() or UPDATER.is_symlink():
raise ValueError("Updater path already exists and is not owned by this installer")
UPDATER.parent.mkdir(parents=True, exist_ok=True)
UPDATER.symlink_to(target) # Atomic creation, without overwriting an operator file.
def migrate_external_proxy(meta):
"""The new in-container updater migrates the old installer-owned network layout."""
updated = dict(meta, network="external")
if meta["role"] == "worker":
return updated
path = ETC / "server.env"
text = path.read_bytes().decode("utf-8")
matches = re.findall(r"(?m)^ASPNETCORE_URLS=([^\r\n]*)", text)
if len(matches) != 1 or matches[0] not in ("http://127.0.0.1:5187", "http://0.0.0.0:5187"):
raise ValueError("Custom backend listener retained; configure it for your external proxy before migration")
replacement = re.sub(r"(?m)^ASPNETCORE_URLS=[^\r\n]*", "ASPNETCORE_URLS=http://0.0.0.0:5187", text)
server, proxy = "finaltoken-server.service", "finaltoken-proxy.service"
present = (SYSTEMD / proxy).is_file()
active = run(["systemctl", "is-active", "--quiet", server], check=False, capture=True).returncode == 0
proxy_active = present and run(["systemctl", "is-active", "--quiet", proxy], check=False, capture=True).returncode == 0
proxy_enabled = present and run(["systemctl", "is-enabled", "--quiet", proxy], check=False, capture=True).returncode == 0
atomic(ETC / "server.env.pre-external-proxy", text, once=True)
try:
atomic(path, replacement)
if active:
run(["systemctl", "restart", server])
if not healthy([server], updated):
raise ValueError("External-proxy backend health check failed")
if present:
run(["systemctl", "disable", "--now", proxy])
except Exception:
atomic(path, text)
if active:
run(["systemctl", "restart", server], check=False)
if proxy_enabled:
run(["systemctl", "enable", proxy], check=False)
if proxy_active:
run(["systemctl", "restart", proxy], check=False)
raise
return updated
def healthy(services, meta):
@@ -367,6 +384,10 @@ def provision(manifest, archive):
activate(release, meta, first)
meta.update(installed=True, release=str(release))
json_file(marker, meta)
if meta.get("network") != "external":
meta = migrate_external_proxy(meta)
json_file(marker, meta)
install_updater()
if meta["role"] != "worker":
print("Dashboard: https://" + meta["domain"])
print("Dashboard key is root-readable at /etc/finaltoken/dashboard-key (not printed).")
@@ -382,5 +403,5 @@ if __name__ == "__main__":
provision(json.loads(args.manifest.read_text(encoding="utf-8")), args.archive)
except (ValueError, OSError, subprocess.CalledProcessError) as error:
print("Guest setup failed: " + (str(error) if isinstance(error, ValueError) else type(error).__name__), file=sys.stderr)
print("Configuration, history and CLI profiles were retained. Inspect services; retry with host update.", file=sys.stderr)
print("Configuration, history and CLI profiles were retained. Retry finaltoken-update inside the container.", file=sys.stderr)
sys.exit(1)
+23 -76
View File
@@ -1,6 +1,5 @@
"""Create/update an unprivileged Debian 13 LXC from a local FinalToken source snapshot."""
"""Create an unprivileged Debian 13 LXC. Updates run inside the container."""
import argparse
import hashlib
import ipaddress
import json
import os
@@ -9,17 +8,14 @@ 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
from source_bundle import PROJECTS, snapshot
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")
@@ -55,8 +51,8 @@ def server_url(value):
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("action", choices=("install",), help="Create a CT. Run finaltoken-update inside an existing CT.")
p.add_argument("--ctid", type=int, help="New CT id; defaults to Proxmox nextid.")
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")
@@ -68,9 +64,8 @@ def parser():
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("--role", choices=("both", "server", "worker"), help="Install default: both")
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")
@@ -86,16 +81,10 @@ def parser():
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):
@@ -116,7 +105,7 @@ def validate(args):
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")
raise ValueError("Server/both requires the public hostname configured on your existing HTTPS reverse proxy")
args.domain = domain_name(args.domain)
else:
if not args.server_url or not args.worker_key_file:
@@ -153,37 +142,6 @@ def create_command(args, ctid, template):
"--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")
@@ -203,32 +161,21 @@ def execute(args):
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])
if status.returncode == 0:
raise ValueError("CT already exists; run finaltoken-update inside that container")
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))
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
@@ -242,7 +189,7 @@ def deploy(args, archive, sha):
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}",
manifest.update(role=args.role, domain=args.domain, network="external", 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":
@@ -274,7 +221,7 @@ def main(argv=None):
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}")
print(f"Dashboard={('https://' + args.domain) if args.domain else args.server_url}; backend=HTTP :5187 behind your existing reverse proxy")
return 0
execute(args)
return 0
+41
View File
@@ -0,0 +1,41 @@
"""Allowlisted application source shared by CT creation and in-container updates."""
import hashlib
from pathlib import Path
import sys
import tarfile
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from source_policy import is_private_path
PROJECTS = ("FinalToken.Core", "FinalToken.Fleet", "FinalToken.Web", "FinalToken.Worker")
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", "tools/lxc_update.py")]
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() or path.resolve() != path.absolute():
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()
+136 -43
View File
@@ -83,10 +83,10 @@ class HostTests(unittest.TestCase):
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_host_refuses_update_before_any_proxmox_command(self):
with patch.object(host, "run", side_effect=AssertionError("No host update")), contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit):
host.main(["update", "--ctid", "201"])
def test_snapshot_includes_uncommitted_source_but_excludes_outputs_and_hidden_files(self):
with tempfile.TemporaryDirectory() as tmp:
@@ -101,7 +101,8 @@ class HostTests(unittest.TestCase):
(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"):
for name in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE", "tools/lxc_update.py"):
(root / name).parent.mkdir(parents=True, exist_ok=True)
(root / name).write_text("fixture")
archive = Path(tmp) / "source.tgz"
digest = host.snapshot(root, archive)
@@ -125,45 +126,13 @@ class HostTests(unittest.TestCase):
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"):
for name in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE", "tools/lxc_update.py"):
(root / name).parent.mkdir(parents=True, exist_ok=True)
(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):
@@ -209,6 +178,127 @@ class HostTests(unittest.TestCase):
class GuestTests(unittest.TestCase):
def test_server_packages_do_not_install_a_reverse_proxy(self):
with patch.object(guest, "run") as runner, patch.object(Path, "exists", return_value=True):
guest.packages("server", [])
commands = [list(map(str, call.args[0])) for call in runner.call_args_list]
self.assertFalse(any("caddy" in command for command in commands))
def test_fresh_server_exposes_backend_without_proxy_configuration(self):
with tempfile.TemporaryDirectory() as tmp, contextlib.ExitStack() as stack:
root = Path(tmp)
for name, relative in (("ETC", "etc"), ("SERVER_HOME", "server"), ("SYSTEMD", "units")):
stack.enter_context(patch.object(guest, name, root / relative))
users = stack.enter_context(patch.object(guest, "user"))
runner = stack.enter_context(patch.object(guest, "run"))
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))
guest.configure({"role": "server", "providers": [], "emails": {}, "ctid": 201,
"machineId": "lxc_201", "timezone": "UTC", "domain": "usage.example.test", "tls": "acme"})
environment = (guest.ETC / "server.env").read_text()
self.assertTrue("ASPNETCORE_URLS=http://0.0.0.0:5187" in environment)
self.assertIn("FINALTOKEN_PUBLIC_ORIGIN=https://usage.example.test", environment)
self.assertFalse((guest.ETC / "Caddyfile").exists())
self.assertFalse((guest.SYSTEMD / "finaltoken-proxy.service").exists())
self.assertEqual(["finaltoken-server"], [call.args[0] for call in users.call_args_list])
self.assertFalse(any("caddy.service" in call.args[0] for call in runner.call_args_list))
def test_only_application_services_are_managed(self):
self.assertEqual(["finaltoken-server.service"], guest.units("server"))
def test_legacy_proxy_migration_preserves_keys_and_stops_only_owned_proxy(self):
for newline in (b"\n", b"\r\n"):
with self.subTest(newline=newline), tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "units").mkdir()
(root / "units/finaltoken-proxy.service").write_text("owned fixture")
original = newline.join([b"FINALTOKEN_DASHBOARD_KEY=synthetic-fixture-only", b"ASPNETCORE_URLS=http://127.0.0.1:5187", b"FINALTOKEN_PUBLIC_ORIGIN=https://usage.example.test", b""])
(root / "server.env").write_bytes(original)
(root / "server.json").write_bytes(b"operator config")
calls = []
def fake(command, **kwargs):
calls.append(command)
return subprocess.CompletedProcess(command, 0)
with patch.object(guest, "ETC", root), patch.object(guest, "SYSTEMD", root / "units"), \
patch.object(guest, "run", side_effect=fake), patch.object(guest, "healthy", return_value=True):
updated = guest.migrate_external_proxy({"role": "server", "domain": "usage.example.test"})
self.assertEqual("external", updated["network"])
self.assertTrue((root / "server.env").read_bytes() == original.replace(b"127.0.0.1:5187", b"0.0.0.0:5187"))
self.assertTrue((root / "server.env.pre-external-proxy").read_bytes() == original)
self.assertEqual(b"operator config", (root / "server.json").read_bytes())
self.assertIn(["systemctl", "disable", "--now", "finaltoken-proxy.service"], calls)
self.assertFalse(any("caddy.service" in command or "purge" in command or "remove" in command for command in calls))
def test_failed_proxy_migration_restores_listener_and_running_services(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "units").mkdir()
(root / "units/finaltoken-proxy.service").write_text("owned")
original = "ASPNETCORE_URLS=http://127.0.0.1:5187\n"
(root / "server.env").write_bytes(original.encode())
with patch.object(guest, "ETC", root), patch.object(guest, "SYSTEMD", root / "units"), \
patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 0)) as runner, \
patch.object(guest, "healthy", return_value=False), self.assertRaises(ValueError):
guest.migrate_external_proxy({"role": "server"})
self.assertEqual(original.encode(), (root / "server.env").read_bytes())
commands = [call.args[0] for call in runner.call_args_list]
self.assertIn(["systemctl", "restart", "finaltoken-proxy.service"], commands)
self.assertNotIn(["systemctl", "disable", "--now", "finaltoken-proxy.service"], commands)
def test_custom_listener_is_not_overwritten_by_migration(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
original = b"ASPNETCORE_URLS=http://192.0.2.10:6000\n"
(root / "server.env").write_bytes(original)
with patch.object(guest, "ETC", root), patch.object(guest, "run") as runner, self.assertRaises(ValueError):
guest.migrate_external_proxy({"role": "server"})
runner.assert_not_called()
self.assertEqual(original, (root / "server.env").read_bytes())
def test_proxy_stop_failure_rolls_back_listener_and_proxy_state(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "units").mkdir()
(root / "units/finaltoken-proxy.service").write_text("owned")
original = b"ASPNETCORE_URLS=http://127.0.0.1:5187\n"
(root / "server.env").write_bytes(original)
calls = []
def fake(command, **kwargs):
calls.append(command)
if command[1:3] == ["disable", "--now"]:
raise subprocess.CalledProcessError(1, command)
return subprocess.CompletedProcess(command, 0)
with patch.object(guest, "ETC", root), patch.object(guest, "SYSTEMD", root / "units"), \
patch.object(guest, "run", side_effect=fake), patch.object(guest, "healthy", return_value=True), \
self.assertRaises(subprocess.CalledProcessError):
guest.migrate_external_proxy({"role": "server"})
self.assertEqual(original, (root / "server.env").read_bytes())
self.assertIn(["systemctl", "enable", "finaltoken-proxy.service"], calls)
self.assertIn(["systemctl", "restart", "finaltoken-proxy.service"], calls)
def test_migration_keeps_intentionally_stopped_backend_stopped(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "server.env").write_bytes(b"ASPNETCORE_URLS=http://127.0.0.1:5187\n")
with patch.object(guest, "ETC", root), patch.object(guest, "SYSTEMD", root / "units"), \
patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 3)) as runner, \
patch.object(guest, "healthy") as healthy:
guest.migrate_external_proxy({"role": "server"})
healthy.assert_not_called()
self.assertFalse(any("restart" in call.args[0] or "start" in call.args[0] for call in runner.call_args_list))
def test_worker_migration_does_not_access_server_configuration(self):
with patch.object(Path, "read_bytes", side_effect=AssertionError("Worker has no server environment")):
self.assertEqual("external", guest.migrate_external_proxy({"role": "worker"})["network"])
def test_updater_registration_does_not_overwrite_an_operator_file(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "finaltoken-update"
path.write_bytes(b"operator file")
with patch.object(guest, "UPDATER", path), self.assertRaises(ValueError):
guest.install_updater()
self.assertEqual(b"operator file", path.read_bytes())
def test_codex_npm_install_creates_the_configured_launcher(self):
node, npm = shutil.which("node"), shutil.which("npm")
if not node or not npm:
@@ -269,7 +359,7 @@ class GuestTests(unittest.TestCase):
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",
"role": "server", "network": "external", "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"
@@ -284,7 +374,7 @@ class GuestTests(unittest.TestCase):
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()):
patch.object(guest, "install_updater"), 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()
@@ -307,6 +397,9 @@ class GuestTests(unittest.TestCase):
item = tarfile.TarInfo("LICENSE")
item.size = len(license_text)
stream.addfile(item, io.BytesIO(license_text))
item = tarfile.TarInfo("tools/lxc_update.py")
item.size = 1
stream.addfile(item, io.BytesIO(b"#"))
home = root / "build"
home.mkdir()
def fake_publish(name, home, command, **kwargs):
@@ -345,7 +438,7 @@ class GuestTests(unittest.TestCase):
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")):
for name, relative in (("ETC", "etc"), ("WORKER_HOME", "worker"), ("SERVER_HOME", "server"), ("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"))
@@ -365,7 +458,7 @@ class GuestTests(unittest.TestCase):
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())
self.assertFalse((guest.ETC / "Caddyfile").exists())
def test_units_use_profile_owner_and_kill_child_processes(self):
worker = guest.service_unit("worker")
+113 -163
View File
@@ -1,188 +1,138 @@
"""Real local Git/Bash updater checks. No network, Proxmox, package or service changes."""
"""In-container updater tests: real local Git; no Proxmox, package or service mutations."""
import contextlib
import io
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))
import lxc_update as updater
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):
class ContainerUpdateTests(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.temporary = tempfile.TemporaryDirectory(prefix="finaltoken-ct-update-test-")
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"]
self.source, self.etc, self.result = self.root / "repo", self.root / "etc", self.root / "result.json"
self.source.mkdir(); self.etc.mkdir()
self.env = dict(os.environ, GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1")
self.git("init", "--initial-branch=master")
for name in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE", "tools/lxc_update.py"):
path = self.source / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("synthetic source fixture\n")
for project in ("FinalToken.Core", "FinalToken.Fleet", "FinalToken.Web", "FinalToken.Worker"):
path = self.source / "src" / project
path.mkdir(parents=True)
(path / (project + ".csproj")).write_text("<Project/>\n")
(self.source / "tools/proxmox").mkdir()
shutil.copy2(HERE / "source_bundle.py", self.source / "tools/proxmox/source_bundle.py")
shutil.copy2(HERE.parent / "source_policy.py", self.source / "tools/source_policy.py")
self.publish("v1")
self.marker = {"installer": "finaltoken-proxmox-v1", "ctid": 201, "role": "server"}
(self.etc / "install.json").write_text(json.dumps(self.marker))
(self.etc / "history.json").write_bytes(b"synthetic retained history")
self.commands = []
real_run = updater.run
def run(command, **kwargs):
self.commands.append(list(map(str, command)))
if command[0] in ("apt-get", "env"):
return subprocess.CompletedProcess(command, 0)
self.assertEqual("git", command[0], "Updater must not invoke Proxmox host commands")
return real_run(command, **kwargs)
self.stack = contextlib.ExitStack()
self.addCleanup(self.stack.close)
self.stack.enter_context(patch.object(updater, "ETC", self.etc))
self.stack.enter_context(patch.object(updater, "REPOSITORY", str(self.source)))
self.stack.enter_context(patch.object(updater.sys, "platform", "linux"))
self.stack.enter_context(patch.object(updater.os, "geteuid", return_value=0, create=True))
self.stack.enter_context(patch.object(updater, "update_lock", side_effect=contextlib.nullcontext))
self.stack.enter_context(patch.object(updater, "run", side_effect=run))
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 git(self, *arguments):
return subprocess.run(["git", "-c", "user.name=Fixture", "-c", "[email protected]",
"-c", "commit.gpgsign=false", "-C", str(self.source), *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 publish(self, version, failure=False):
code = "import hashlib, json, tarfile\nfrom pathlib import Path\n"
code += "def provision(manifest, archive):\n"
code += " assert hashlib.sha256(archive.read_bytes()).hexdigest() == manifest['sourceSha256']\n"
if failure:
code += " raise ValueError('synthetic build failure')\n"
else:
code += " with tarfile.open(archive) as stream: names = stream.getnames()\n"
code += f" Path({str(self.result)!r}).write_text(json.dumps(dict(version={version!r}, manifest=manifest, files=names)))\n"
(self.source / "tools/proxmox/guest.py").write_text(code)
self.git("add", ".")
self.git("commit", "-m", "Synthetic " + version)
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)
with contextlib.redirect_stdout(io.StringIO()):
return updater.main(list(arguments))
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_updates_here_using_fresh_source_and_current_container_identity(self):
self.assertEqual(0, self.update())
self.assertEqual("v1", json.loads(self.result.read_text())["version"])
self.publish("v2")
self.assertEqual(0, self.update())
result = json.loads(self.result.read_text())
self.assertEqual("v2", result["version"])
self.assertEqual(201, result["manifest"]["ctid"])
self.assertEqual("update", result["manifest"]["action"])
self.assertIn("tools/lxc_update.py", result["files"])
self.assertEqual(b"synthetic retained history", (self.etc / "history.json").read_bytes())
self.assertEqual(self.marker, json.loads((self.etc / "install.json").read_text()))
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_does_not_fetch_install_packages_or_acquire_lock(self):
with patch.object(updater, "update_lock") as lock:
self.assertEqual(0, self.update("--dry-run"))
lock.assert_not_called()
self.assertEqual([], self.commands)
self.assertFalse(self.result.exists())
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_non_root_foreign_or_missing_container_never_starts_update(self):
with patch.object(updater.os, "geteuid", return_value=1000), self.assertRaises(ValueError):
self.update()
(self.etc / "install.json").write_text('{"installer":"foreign"}')
with self.assertRaises(ValueError):
self.update()
(self.etc / "install.json").unlink()
with self.assertRaises(ValueError):
self.update()
self.assertEqual([], self.commands)
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_busy_update_does_not_fetch(self):
with patch.object(updater, "update_lock", side_effect=BlockingIOError), self.assertRaises(BlockingIOError):
self.update()
self.assertEqual([], self.commands)
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_download_failure_keeps_container_state(self):
with patch.object(updater, "REPOSITORY", str(self.root / "missing")), self.assertRaises(subprocess.CalledProcessError):
self.update()
self.assertFalse(self.result.exists())
self.assertEqual(b"synthetic retained history", (self.etc / "history.json").read_bytes())
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_build_failure_is_not_reported_as_success_and_preserves_state(self):
self.publish("failed", failure=True)
with self.assertRaises(ValueError):
self.update()
self.assertFalse(self.result.exists())
self.assertEqual(self.marker, json.loads((self.etc / "install.json").read_text()))
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())
def test_git_bootstrap_installs_only_inside_the_validated_container(self):
with patch.object(updater.shutil, "which", return_value=None):
self.assertEqual(0, self.update())
self.assertEqual(["apt-get", "update"], self.commands[0])
self.assertEqual(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "git", "ca-certificates"], self.commands[1])
if __name__ == "__main__":