From 480b73d899b6f3907ef86817128f6b845d7b28ec Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Sun, 15 Nov 2026 16:38:19 +0100 Subject: [PATCH] web: allow direct IP dashboard and worker access Remove fixed-host and HTTPS-only deployment requirements so the dashboard works at the container IP on HTTP port 5187. Validate browser mutations against the actual request host and retain access keys and CSRF protection. Ignore legacy public-origin settings and make Proxmox setup hostname-free. Update D14 and regression coverage for version 1.2.3. Refs #25 --- .agents/mind/architecture.md | 2 +- .agents/mind/gotchas.md | 4 +- .agents/mind/index.md | 4 +- Directory.Build.props | 2 +- README.md | 3 +- docs/decisions.md | 9 ++- docs/proxmox.md | 31 +++++----- docs/publication.md | 3 +- docs/requirements.md | 4 +- docs/web-dashboard.md | 22 ++++--- src/FinalToken.Fleet/Contracts.cs | 8 +++ src/FinalToken.Web/Program.cs | 23 ++++--- src/FinalToken.Worker/Program.cs | 5 +- tests/FinalToken.Fleet.Tests/OriginTests.cs | 33 ++++++++++ tools/lxc_update.py | 2 +- tools/proxmox/guest.py | 17 +++++- tools/proxmox/host.py | 13 ++-- tools/proxmox/test_installer.py | 35 +++++++++-- tools/test_web_dashboard.py | 67 +++++++++++++++++++-- 19 files changed, 218 insertions(+), 69 deletions(-) create mode 100644 tests/FinalToken.Fleet.Tests/OriginTests.cs diff --git a/.agents/mind/architecture.md b/.agents/mind/architecture.md index 1b97b2e..0ba1139 100644 --- a/.agents/mind/architecture.md +++ b/.agents/mind/architecture.md @@ -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 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] Proxmox host creates the CT only. HTTP :5187 works directly by IP; HTTPS/proxy is optional, with no fixed host allowlist (D14). `finaltoken-update` fetches/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. diff --git a/.agents/mind/gotchas.md b/.agents/mind/gotchas.md index e20f249..cb8c6b6 100644 --- a/.agents/mind/gotchas.md +++ b/.agents/mind/gotchas.md @@ -15,8 +15,10 @@ - [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. +- [2026-11-15] Do not assume a proxy or host-driven updates for LXC deployments. Direct IP HTTP is supported; use the in-container updater. An optional TLS proxy preserves the browser's Host/Origin. - [2026-11-15] A build-owned source/output cannot supply code later executed as root. Capture updater bytes from the verified archive before build handoff and atomically install them in the root-owned release, excluding build-supplied updater files. - [2026-11-15] Container shells can omit `/usr/local/sbin`. Register the updater in `/usr/local/bin`, print an absolute-path fallback, and test real shell lookup with sbin excluded. +- [2026-11-15] A legacy `FINALTOKEN_PUBLIC_ORIGIN=https://usage.example.com` caused HTTP 400 for IP access. Ignore this old setting; compare browser mutation Origin to actual request Host and derive Secure cookies from TLS or its validated HTTPS Origin. Health checks must not hide regressions with a forged Host. + ## Archive diff --git a/.agents/mind/index.md b/.agents/mind/index.md index 00b1f85..7bd787e 100644 --- a/.agents/mind/index.md +++ b/.agents/mind/index.md @@ -2,7 +2,7 @@ > Always-loaded. Everything else is on-demand. Update TOC when files change. ## Current Focus -- [2026-11-15] User report confirms Debian 13 NativeAOT server publish and legacy proxy disable. 1.2.2 fixes updater discovery; external proxy and official provider flows still need live verification. +- [2026-11-15] 1.2.3 removes fixed hostname/HTTPS requirements for direct IP access. Debian 13 native build/update was user-exercised; this IP correction and official provider flows still need live verification. ## 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` — 13 entries — CLI login, updater trust/PATH boundaries, publication checks and Avalonia tooltips. +- `gotchas.md` — 14 entries — CLI login, IP/Origin and updater boundaries, publication checks and Avalonia tooltips. - `architecture.md` — 7 entries — Fleet analysis, attribution, migration, authentication, durability, Proxmox and publication. diff --git a/Directory.Build.props b/Directory.Build.props index 3eabeff..4276917 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 1.2.2 + 1.2.3 net10.0 14 enable diff --git a/README.md b/README.md index 688dc0d..5a09efa 100644 --- a/README.md +++ b/README.md @@ -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 creates a server-only LXC behind your existing HTTPS proxy. Run `finaltoken-update` inside +It creates a server-only LXC at `http://:5187`, with no hostname or proxy required. +Run `finaltoken-update` inside the container for updates; no Proxmox-host checkout is needed afterwards. ## Requirements diff --git a/docs/decisions.md b/docs/decisions.md index e8c2d64..50dac24 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -322,14 +322,17 @@ worker per OS user, following the developer's direction in - Account ids, expected emails and machine/profile bindings are configured by the operator. The server has a dashboard access key and distinct per-machine keys. Browser sessions are - HttpOnly, SameSite cookies with CSRF checks; remote access uses HTTPS. A worker cannot select + HttpOnly, SameSite cookies with CSRF checks. Direct IP or hostname access supports HTTP and + HTTPS without a fixed-host allowlist. Browser mutations compare Origin with the actual request + Host; HTTPS sessions use Secure cookies, including through a proxy preserving Host/Origin. + HTTP transport is unencrypted. A worker cannot select another machine's identity or execute arbitrary remote commands. - The dashboard calls Core's D7, D12 and D13 APIs. No second forecasting implementation is added. 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. + exposes HTTP port 5187 directly at the container IP; an operator's HTTPS proxy is optional. `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 @@ -359,6 +362,8 @@ worker per OS user, following the developer's direction in **Why.** R8, and the developer's clarification that the browser authorization response must travel through FinalToken to the CLI, without being stored. D7's analysis answers whether the remaining allowance will last through the actual reset; token prices alone cannot answer it. +The developer requires direct IP access without hostname registration or a mandatory proxy +([#25](https://git.finalfactory.de/FinalFactory/FinalToken/issues/25)). **Gives up.** Automatic remote callbacks, provider-token sharing, automatic account switching, unverified identities, universal login lifetimes, and exact cross-machine attribution of old diff --git a/docs/proxmox.md b/docs/proxmox.md index ba0b0ae..aaa8800 100644 --- a/docs/proxmox.md +++ b/docs/proxmox.md @@ -1,8 +1,8 @@ # Proxmox LXC install and update 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 +Open the dashboard at **`http://:5187`**. No hostname, HTTPS or proxy is required; +FinalToken installs no Caddy or other proxy. This follows [D14](decisions.md#d14--self-hosted-dashboard-and-workers). ## Install the server @@ -12,23 +12,25 @@ 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 && \ bash /opt/finaltoken-src/tools/proxmox.sh install --role server --ctid 201 \ - --storage local-lvm --domain usage.example.com --timezone Europe/Berlin + --storage local-lvm --timezone Europe/Berlin ``` -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. +Use a free CT id and your storage and timezone. Omit `--ctid` for the next free id. +The optional legacy `--domain` argument is accepted but does not restrict dashboard access. Add `--dry-run` to validate without creating a CT. Anonymous HTTPS clone needs no Git login. -Configure your existing reverse proxy: +The installer prints the container IP URL. You can also find the address with `hostname -I` +inside the CT. HTTP transport is unencrypted. If you choose to use an HTTPS reverse proxy: - Public URL: `https://usage.example.com` (your chosen hostname). - Backend: `http://:5187`. -- Preserve the public `Host` header. Restrict backend network access to your proxy/private network. +- Preserve the public `Host` and browser `Origin` headers. - 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 dashboard key, machine keys and CSRF checks remain required. Browser mutation Origins must +match the actual request Host; no fixed hostname allowlist applies. HTTPS sessions use Secure +cookies, and direct HTTP login works. 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: @@ -97,8 +99,8 @@ root inside that LXC** to fetch the corrected updater and perform the update: ``` 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 +to `0.0.0.0:5187` and disables **only** `finaltoken-proxy.service`. Open the container IP on +HTTP port 5187. Keys, old environment settings, 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 @@ -120,12 +122,13 @@ For a worker-only CT, configure the matching machine/account/key on the existing ```bash bash tools/proxmox.sh install --ctid 202 --storage local-lvm --role worker \ - --server-url https://usage.example.com --machine-id lxc_202 \ + --server-url http://10.0.30.150:5187 --machine-id lxc_202 \ --worker-key-file /root/lxc_202.key --email you@example.com ``` 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. +is `finaltoken`; selected provider names are its profile ids. Workers connect outbound over +the configured HTTP or HTTPS URL. Use `finaltoken-update` inside worker CTs too. ## Host and container requirements @@ -139,7 +142,7 @@ when needed. This is not an offline or byte-for-byte reproducible dependency bui 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. +rules are changed. Your browser and workers must reach the CT on port 5187. 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, diff --git a/docs/publication.md b/docs/publication.md index 776dcae..cbb5b6b 100644 --- a/docs/publication.md +++ b/docs/publication.md @@ -14,8 +14,7 @@ For the Proxmox workflow, clone the published source on the host, then run its i ```bash git clone https://git.finalfactory.de/FinalFactory/FinalToken.git cd FinalToken -bash tools/proxmox.sh install --ctid 201 --storage local-lvm \ - --domain usage.example.com --email you@example.com +bash tools/proxmox.sh install --ctid 201 --storage local-lvm --email you@example.com ``` For a later update, run as root **inside the LXC**: diff --git a/docs/requirements.md b/docs/requirements.md index 61da24f..9c3c275 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -16,5 +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. + Proxmox installation uses the host only to create the CT. Updates run inside the CT. Direct IP + access works over HTTP port 5187 without a hostname or proxy; HTTPS is optional. diff --git a/docs/web-dashboard.md b/docs/web-dashboard.md index 9c72ca7..6deec87 100644 --- a/docs/web-dashboard.md +++ b/docs/web-dashboard.md @@ -8,7 +8,7 @@ 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 installer](proxmox.md). -It uses your existing HTTPS proxy and exposes private HTTP :5187; updates run inside the CT +It exposes HTTP :5187 directly at the container IP; updates run inside the CT with `finaltoken-update`. Build from the repository root: @@ -49,14 +49,15 @@ Start the server from the repository root: dotnet run --project src/FinalToken.Web -c Release --no-build ``` -By default it listens on `http://127.0.0.1:5187`. Open exactly that URL and enter the dashboard key. -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. 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. +By default it listens on `http://127.0.0.1:5187`. Set `ASPNETCORE_URLS=http://0.0.0.0:5187` +for network access, then open `http://:5187` and enter the dashboard key. The Proxmox +installer sets this listener automatically. No hostname registration, proxy or HTTPS is required. +The old `FINALTOKEN_PUBLIC_ORIGIN` setting is ignored, including placeholder values in existing CTs. +HTTP transport is unencrypted; an optional HTTPS proxy must preserve Host and browser Origin, +or you can configure HTTPS directly in Kestrel. Browser mutations still require the matching +request Host/Origin and CSRF protection. HTTP sessions work over HTTP; HTTPS sessions use Secure +cookies. No forwarded-header trust is enabled automatically. Proxies must not log request bodies +or authorization headers. Login URLs/codes are absent from server logs and disk state. Keys authorize all profiles on their configured machine; use service-account file/environment permissions and a private network/firewall. Rotate a machine key on both ends to revoke it. @@ -87,7 +88,8 @@ Set `FINALTOKEN_WORKER_KEY` to the server's key for this machine. Start from the dotnet run --project src/FinalToken.Worker -c Release --no-build -- ``` -Remote worker URLs require HTTPS. Workers only make outbound connections; no worker port is open. +Worker URLs accept HTTP or HTTPS origins, including direct IP addresses. Workers only make +outbound connections; no worker port is open. Use the OS service manager/Task Scheduler for unattended startup, under the intended user with the CLI on PATH. A Linux/LXC worker needs .NET 10 (or a future locally built NativeAOT binary), installed official CLIs, writable profile directories, outbound HTTPS and any CLI keychain diff --git a/src/FinalToken.Fleet/Contracts.cs b/src/FinalToken.Fleet/Contracts.cs index 17864b1..a6dc213 100644 --- a/src/FinalToken.Fleet/Contracts.cs +++ b/src/FinalToken.Fleet/Contracts.cs @@ -60,6 +60,14 @@ public partial class FleetJsonContext : JsonSerializerContext; public static class FleetValidation { + public static bool TryHttpOrigin(string? value, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out Uri? origin) => + Uri.TryCreate(value, UriKind.Absolute, out origin) && origin.Scheme is "http" or "https" && + origin.Host.Length > 0 && origin.UserInfo.Length == 0 && origin.AbsolutePath == "/" && + origin.Query.Length == 0 && origin.Fragment.Length == 0; + + public static bool MatchesRequestHost(Uri origin, string? host) => + !string.IsNullOrEmpty(host) && TryHttpOrigin(origin.Scheme + "://" + host, out var requestOrigin) && origin == requestOrigin; + public static bool Identifier(string? value) => value is { Length: > 0 and <= 64 } && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_'); public static void Config(ServerConfig config) diff --git a/src/FinalToken.Web/Program.cs b/src/FinalToken.Web/Program.cs index acedfcb..dbab8f8 100644 --- a/src/FinalToken.Web/Program.cs +++ b/src/FinalToken.Web/Program.cs @@ -12,10 +12,6 @@ if (dashboardKey is not { Length: >= 32 }) throw new InvalidDataException("Set F var machineKeys = config.Machines.ToDictionary(m => m.Id, m => Environment.GetEnvironmentVariable("FINALTOKEN_MACHINE_" + m.Id)); if (machineKeys.Values.Any(k => k is not { Length: >= 32 }) || machineKeys.Values.Append(dashboardKey).Distinct().Count() != machineKeys.Count + 1) throw new InvalidDataException("Set a separate random FINALTOKEN_MACHINE_ key for every machine."); -var publicOrigin = Environment.GetEnvironmentVariable("FINALTOKEN_PUBLIC_ORIGIN") ?? "http://127.0.0.1:5187"; -if (!Uri.TryCreate(publicOrigin, UriKind.Absolute, out var origin) || origin.AbsolutePath != "/" || origin.UserInfo.Length != 0 || - origin.Query.Length != 0 || origin.Fragment.Length != 0 || !(origin.Scheme == "https" || origin.Scheme == "http" && origin.IsLoopback)) - throw new InvalidDataException("Public origin must be HTTPS, or loopback HTTP for local development."); using var serverLock = StoreLock.TryAcquire(directory) ?? throw new InvalidDataException("Server data directory is already in use."); var store = new FleetStore(directory, config); var logins = new LoginCoordinator(config); @@ -43,11 +39,18 @@ app.Use(async (ctx, next) => } else { - // Pin Host and Origin. Reverse proxies terminate HTTPS and must preserve the public Host. - if (!string.Equals(ctx.Request.Host.Value, origin.Authority, StringComparison.OrdinalIgnoreCase)) { ctx.Response.StatusCode = 400; return; } - if (ctx.Request.Method != "GET" && (ctx.Request.Headers["X-FinalToken"] != "1" || - ctx.Request.Headers.Origin.Count > 0 && !ctx.Request.Headers.Origin.ToString().Equals(origin.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase))) - { ctx.Response.StatusCode = 403; return; } + // D14: accept IPs and hostnames; browser mutations must originate from the requested host. + if (ctx.Request.Method != "GET") + { + if (ctx.Request.Headers["X-FinalToken"] != "1") { ctx.Response.StatusCode = 403; return; } + if (ctx.Request.Headers.Origin.Count > 0) + { + if (!FleetValidation.TryHttpOrigin(ctx.Request.Headers.Origin.ToString(), out var browserOrigin) || + !FleetValidation.MatchesRequestHost(browserOrigin, ctx.Request.Host.Value)) + { ctx.Response.StatusCode = 403; return; } + ctx.Items["https-origin"] = browserOrigin.Scheme == "https"; + } + } if (ctx.Request.Path.StartsWithSegments("/api")) { var session = ctx.Request.Cookies["finaltoken"]; @@ -73,7 +76,7 @@ app.MapPost("/session", async (HttpContext ctx) => if (!BrowserSessions.Matches(input?.Key, dashboardKey)) return Results.Unauthorized(); sessions.Remove(ctx.Request.Cookies["finaltoken"]); var session = sessions.Create(DateTimeOffset.UtcNow); - ctx.Response.Cookies.Append("finaltoken", session.Id, new CookieOptions { HttpOnly = true, Secure = origin.Scheme == "https", SameSite = SameSiteMode.Strict, Path = "/", MaxAge = TimeSpan.FromHours(8) }); + ctx.Response.Cookies.Append("finaltoken", session.Id, new CookieOptions { HttpOnly = true, Secure = ctx.Request.IsHttps || ctx.Items["https-origin"] is true, SameSite = SameSiteMode.Strict, Path = "/", MaxAge = TimeSpan.FromHours(8) }); return Results.Json(new BrowserSession(session.Csrf), FleetJsonContext.Default.BrowserSession); }); app.MapGet("/api/session", (HttpContext ctx) => Results.Json(new BrowserSession((string)ctx.Items["csrf"]!), FleetJsonContext.Default.BrowserSession)); diff --git a/src/FinalToken.Worker/Program.cs b/src/FinalToken.Worker/Program.cs index 89e6ba9..694d4d1 100644 --- a/src/FinalToken.Worker/Program.cs +++ b/src/FinalToken.Worker/Program.cs @@ -14,9 +14,8 @@ try config.Profiles.Any(p => !FleetValidation.Identifier(p.Id) || !Enum.IsDefined(p.Provider) || string.IsNullOrWhiteSpace(p.ExpectedEmail) || !Path.IsPathFullyQualified(p.ConfigDirectory) || !Path.IsPathFullyQualified(p.DataDirectory))) throw new InvalidDataException("Invalid worker profile configuration."); - if (!Uri.TryCreate(config.ServerUrl, UriKind.Absolute, out var uri) || uri.UserInfo.Length != 0 || - !(uri.Scheme == "https" || uri.Scheme == "http" && uri.IsLoopback)) - throw new InvalidDataException("Server must use HTTPS (loopback HTTP is permitted for local checks)."); + if (!FleetValidation.TryHttpOrigin(config.ServerUrl, out var uri)) + throw new InvalidDataException("Server URL must be an HTTP or HTTPS origin without credentials or a path."); if (config.Profiles.Select(p => Path.GetFullPath(p.ConfigDirectory)).Distinct(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal).Count() != config.Profiles.Count || config.Profiles.Select(p => Path.GetFullPath(p.DataDirectory)).Distinct(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal).Count() != config.Profiles.Count) throw new InvalidDataException("Each profile requires separate config and data directories."); diff --git a/tests/FinalToken.Fleet.Tests/OriginTests.cs b/tests/FinalToken.Fleet.Tests/OriginTests.cs new file mode 100644 index 0000000..74cf2b2 --- /dev/null +++ b/tests/FinalToken.Fleet.Tests/OriginTests.cs @@ -0,0 +1,33 @@ +using FinalToken.Fleet; +using Xunit; + +namespace FinalToken.Fleet.Tests; + +public sealed class OriginTests +{ + [Theory] + [InlineData("http://10.0.30.150:5187")] + [InlineData("https://10.0.30.150")] + [InlineData("http://[2001:db8::5]:5187/")] + [InlineData("https://usage.example.test/")] + public void AcceptHttpAndHttpsOrigins(string value) => Assert.True(FleetValidation.TryHttpOrigin(value, out _)); + + [Theory] + [InlineData("ftp://10.0.30.150")] + [InlineData("http://" + "synthetic-user:synthetic-password@10.0.30.150")] + [InlineData("http://10.0.30.150/path")] + [InlineData("http://10.0.30.150/?key=value")] + [InlineData("http://10.0.30.150/#fragment")] + [InlineData("not an origin")] + [InlineData(null)] + public void RejectNonOrigins(string? value) => Assert.False(FleetValidation.TryHttpOrigin(value, out _)); + + [Theory] + [InlineData("http://10.0.30.150:5187", "10.0.30.150:5187", true)] + [InlineData("https://usage.example.test", "USAGE.EXAMPLE.TEST:443", true)] + [InlineData("http://[2001:db8::5]:5187", "[2001:db8::5]:5187", true)] + [InlineData("http://10.0.30.150:5187", "10.0.30.150:5188", false)] + [InlineData("http://evil.example.test", "10.0.30.150:5187", false)] + public void BrowserOriginMustMatchActualRequestHost(string value, string host, bool matches) => + Assert.Equal(matches, FleetValidation.MatchesRequestHost(new Uri(value), host)); +} diff --git a/tools/lxc_update.py b/tools/lxc_update.py index 618ea67..2803263 100644 --- a/tools/lxc_update.py +++ b/tools/lxc_update.py @@ -53,7 +53,7 @@ def main(argv=None): 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.") + print("Dashboard: http://:5187; no hostname or proxy required. Disable only the old FinalToken proxy.") return 0 with update_lock(): if not shutil.which("git"): diff --git a/tools/proxmox/guest.py b/tools/proxmox/guest.py index d81c482..da049f1 100644 --- a/tools/proxmox/guest.py +++ b/tools/proxmox/guest.py @@ -1,6 +1,7 @@ """Private guest provisioner, invoked by host.py inside the selected LXC. Not a host entry point.""" import argparse import hashlib +import ipaddress import json import os from pathlib import Path, PurePosixPath @@ -178,7 +179,7 @@ def configure(meta, enrollment_key=None): "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"FINALTOKEN_DASHBOARD_KEY={keys['dashboard']}\n" f"ASPNETCORE_URLS=http://0.0.0.0:5187\nFINALTOKEN_MACHINE_{meta['machineId']}={keys['worker']}\n", once=True) atomic(ETC / "dashboard-key", keys["dashboard"] + "\n", once=True) atomic(ETC / "worker-key", keys["worker"] + "\n", once=True) @@ -315,12 +316,22 @@ def migrate_external_proxy(meta): return updated +def dashboard_urls(): + try: + result = run(["hostname", "-I"], capture=True, check=False) + addresses = [ipaddress.ip_address(value) for value in result.stdout.split()] if result.returncode == 0 else [] + return [f"http://{'[' + str(ip) + ']' if ip.version == 6 else ip}:5187" + for ip in addresses if not ip.is_loopback and not ip.is_link_local] or ["http://:5187"] + except (OSError, ValueError): + return ["http://:5187"] + + 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"]}) + request = urllib.request.Request("http://127.0.0.1:5187/") with urllib.request.urlopen(request, timeout=2) as response: live = response.status == 200 except OSError: @@ -399,7 +410,7 @@ def provision(manifest, archive): json_file(marker, meta) install_updater() if meta["role"] != "worker": - print("Dashboard: https://" + meta["domain"]) + print("Dashboard: " + ", ".join(dashboard_urls())) 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.") diff --git a/tools/proxmox/host.py b/tools/proxmox/host.py index a90be4c..0add13e 100644 --- a/tools/proxmox/host.py +++ b/tools/proxmox/host.py @@ -43,8 +43,8 @@ def domain_name(value): 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") + if url.scheme not in ("http", "https") or not url.hostname or url.username is not None or url.password is not None or url.path not in ("", "/") or url.query or url.fragment: + raise ValueError("Server URL must be an HTTP or HTTPS origin") _ = url.port return value.rstrip("/") @@ -65,7 +65,7 @@ def parser(): 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") - p.add_argument("--domain", help="Dashboard DNS name; required for server/both") + p.add_argument("--domain", help="Legacy optional DNS hint; no longer used to restrict access") p.add_argument("--email", help="Expected provider email for both selected providers") p.add_argument("--claude-email") p.add_argument("--codex-email") @@ -104,9 +104,8 @@ def validate(args): 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 the public hostname configured on your existing HTTPS reverse proxy") - args.domain = domain_name(args.domain) + if args.domain: + 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") @@ -221,7 +220,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}; backend=HTTP :5187 behind your existing reverse proxy") + print("Server=" + args.server_url if role == "worker" else "Dashboard=http://:5187; no hostname or proxy required") return 0 execute(args) return 0 diff --git a/tools/proxmox/test_installer.py b/tools/proxmox/test_installer.py index 4c3557c..8401bc1 100644 --- a/tools/proxmox/test_installer.py +++ b/tools/proxmox/test_installer.py @@ -33,6 +33,14 @@ def install_args(*extra): class HostTests(unittest.TestCase): + def test_server_install_requires_no_hostname(self): + args = host.parser().parse_args(["install", "--role", "server", "--ctid", "201", "--storage", "local-lvm"]) + host.validate(args) + self.assertIsNone(args.domain) + + def test_worker_can_use_a_direct_http_ip_address(self): + self.assertEqual("http://10.0.30.150:5187", host.server_url("http://10.0.30.150:5187/")) + 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"]) @@ -61,14 +69,14 @@ class HostTests(unittest.TestCase): with self.subTest(flags=flags), self.assertRaises(ValueError): install_args(*flags) - def test_worker_only_requires_https_and_enrollment_file(self): + def test_worker_only_requires_http_origin_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)) + install_args("--role", "worker", "--server-url", "ftp://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)) @@ -178,6 +186,22 @@ class HostTests(unittest.TestCase): class GuestTests(unittest.TestCase): + def test_dashboard_urls_use_container_ips_and_bracket_ipv6(self): + with patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 0, "10.0.30.150 2001:db8::5 fe80::1 127.0.0.1")): + self.assertEqual(["http://10.0.30.150:5187", "http://[2001:db8::5]:5187"], guest.dashboard_urls()) + + def test_missing_address_command_does_not_fail_an_update(self): + with patch.object(guest, "run", side_effect=FileNotFoundError): + self.assertEqual(["http://:5187"], guest.dashboard_urls()) + + def test_health_check_uses_no_configured_hostname(self): + with patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 0)), patch.object(guest.time, "sleep"), \ + patch.object(guest.urllib.request, "urlopen") as opener: + opener.return_value.__enter__.return_value.status = 200 + self.assertTrue(guest.healthy(["finaltoken-server.service"], {"role": "server"})) + self.assertEqual("http://127.0.0.1:5187/", opener.call_args.args[0].full_url) + self.assertFalse(opener.call_args.args[0].has_header("Host")) + 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", []) @@ -194,10 +218,10 @@ class GuestTests(unittest.TestCase): 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"}) + "machineId": "lxc_201", "timezone": "UTC"}) 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.assertNotIn("FINALTOKEN_PUBLIC_ORIGIN", 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]) @@ -405,7 +429,8 @@ 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, "install_updater"), patch.object(guest, "activate") as activate, contextlib.redirect_stdout(io.StringIO()): + patch.object(guest, "install_updater"), patch.object(guest, "dashboard_urls", return_value=["http://10.0.30.150:5187"]), \ + 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() diff --git a/tools/test_web_dashboard.py b/tools/test_web_dashboard.py index 0ef91a4..c035b5a 100644 --- a/tools/test_web_dashboard.py +++ b/tools/test_web_dashboard.py @@ -3,6 +3,7 @@ import argparse import datetime as dt import getpass import http.cookiejar +from http.cookies import SimpleCookie import json import os from pathlib import Path @@ -15,6 +16,7 @@ import time import unittest import urllib.error import urllib.request +from urllib.parse import urlsplit ROOT = Path(__file__).resolve().parents[1] KEY = "synthetic-dashboard-key-for-local-tests-only-123456" @@ -32,7 +34,7 @@ def wait_for(check, timeout=30): class Fixture: - def __init__(self, port=None): + def __init__(self, port=None, public_origin=None, start_worker=True): self.temp = tempfile.TemporaryDirectory(prefix="finaltoken-web-test-") self.path = Path(self.temp.name) self.processes = [] @@ -41,6 +43,7 @@ class Fixture: sock.bind(("127.0.0.1", 0)) port = sock.getsockname()[1] self.url = f"http://127.0.0.1:{port}" + self.ready_host = urlsplit(public_origin or self.url).netloc self.jar = http.cookiejar.CookieJar() self.browser = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.jar)) self.csrf = None @@ -78,7 +81,7 @@ class Fixture: (sessions / "rollout-fixture.jsonl").write_text("\n".join(map(json.dumps, rows)) + "\n", encoding="utf-8") env = os.environ.copy() env.update(FINALTOKEN_SERVER_CONFIG=str(self.path / "server.json"), FINALTOKEN_SERVER_DATA=str(self.path / "server-data"), - FINALTOKEN_DASHBOARD_KEY=KEY, FINALTOKEN_MACHINE_a=WORKER_KEY, FINALTOKEN_PUBLIC_ORIGIN=self.url, ASPNETCORE_URLS=self.url) + FINALTOKEN_DASHBOARD_KEY=KEY, FINALTOKEN_MACHINE_a=WORKER_KEY, FINALTOKEN_PUBLIC_ORIGIN=public_origin or self.url, ASPNETCORE_URLS=self.url) self.spawn(["dotnet", str(self.path / "FinalToken.Web/FinalToken.Web.dll")], env, ROOT / "src/FinalToken.Web") wait_for(self.ready) worker_env = os.environ.copy() @@ -86,7 +89,8 @@ class Fixture: worker_env.pop("CLAUDE_CONFIG_DIR", None) worker_env.pop("CODEX_HOME", None) worker_env["FINALTOKEN_WORKER_KEY"] = WORKER_KEY - self.spawn(["dotnet", str(self.path / "FinalToken.Worker/finaltoken-worker.dll"), str(self.path / "worker.json")], worker_env, ROOT) + if start_worker: + self.spawn(["dotnet", str(self.path / "FinalToken.Worker/finaltoken-worker.dll"), str(self.path / "worker.json")], worker_env, ROOT) @staticmethod def json(path, value): @@ -99,7 +103,7 @@ class Fixture: def ready(self): try: - return urllib.request.urlopen(self.url, timeout=1).status == 200 + return urllib.request.urlopen(urllib.request.Request(self.url, headers={"Host": self.ready_host}), timeout=1).status == 200 except (OSError, urllib.error.URLError): return False @@ -147,6 +151,61 @@ class Fixture: self.temp.cleanup() +class IPAccessIntegration(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.fixture = Fixture(public_origin="https://usage.example.com", start_worker=False) + + @classmethod + def tearDownClass(cls): + cls.fixture.close() + + def request(self, path, body=None, origin=None, cookie=None, csrf=None): + f = self.fixture + authority = "10.0.30.150:" + str(urlsplit(f.url).port) + headers = {"Host": authority, "X-FinalToken": "1", "Content-Type": "application/json"} + if origin: + headers["Origin"] = origin + if cookie: + headers["Cookie"] = cookie + if csrf: + headers["X-CSRF"] = csrf + request = urllib.request.Request(f.url + path, headers=headers, + data=None if body is None else json.dumps(body).encode()) + return urllib.request.urlopen(request, timeout=10) + + def test_ip_page_and_http_login_ignore_the_legacy_fixed_hostname(self): + with self.request("/") as response: + self.assertEqual(200, response.status) + authority = "10.0.30.150:" + str(urlsplit(self.fixture.url).port) + with self.request("/session", {"key": KEY}, origin="http://" + authority) as response: + cookies = SimpleCookie(response.headers["Set-Cookie"]) + csrf = json.load(response)["csrf"] + self.assertFalse(cookies["finaltoken"]["secure"]) + self.assertTrue(cookies["finaltoken"]["httponly"]) + self.assertEqual("strict", cookies["finaltoken"]["samesite"].lower()) + cookie = "finaltoken=" + cookies["finaltoken"].value + with self.request("/api/dashboard", cookie=cookie) as response: + self.assertEqual(200, response.status) + with self.assertRaises(urllib.error.HTTPError) as error: + self.request("/api/dashboard") + self.assertEqual(401, error.exception.code) + with self.assertRaises(urllib.error.HTTPError) as error: + self.request("/api/logout", {}, origin="http://" + authority, cookie=cookie, csrf="wrong") + self.assertEqual(403, error.exception.code) + with self.assertRaises(urllib.error.HTTPError) as error: + self.request("/api/logout", {}, origin="http://evil.test", cookie=cookie, csrf=csrf) + self.assertEqual(403, error.exception.code) + with self.request("/api/logout", {}, origin="http://" + authority, cookie=cookie, csrf=csrf) as response: + self.assertEqual(204, response.status) + + def test_https_browser_origin_retains_secure_cookie_behind_a_proxy(self): + authority = "10.0.30.150:" + str(urlsplit(self.fixture.url).port) + with self.request("/session", {"key": KEY}, origin="https://" + authority) as response: + cookie = SimpleCookie(response.headers["Set-Cookie"]) + self.assertTrue(cookie["finaltoken"]["secure"]) + + class WebIntegration(unittest.TestCase): @classmethod def setUpClass(cls): -- 2.54.0