From 369e754bec22840ab42954960b5308852907d819 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 4 Nov 2026 09:53:49 +0100 Subject: [PATCH] fix(server): public ports as settings, container port lock and client address; clients default to 8443 and name non-Chronos servers The owner's Uploader could not connect: the panel showed the container's listening ports (8080/8443) as if clients used them, the public ports were only environment variables (CHRONOS_PUBLIC_HTTP_PORT not even in the Unraid template), and the clients mapped a bare host to 443, where another service answered. - Public HTTP/HTTPS ports are settings (server.json, or locked by CHRONOS_PUBLIC_*) and apply at once; ServerSettingsDto gains appended PublicHttpPort, PublicHttpsPort and InContainer members. - In a container the listening ports are fixed by the template: locked in the panel, and saved values from earlier versions are ignored with a warning. - Settings > Network and TLS shows the client address with a Copy button; the discovery tooltip says a container needs network type Host. - ChronosAddress (shared by Chronos and the Uploader): no scheme and no port is https on 8443, https:// keeps 443, a typed port is kept, IPv6 is bracketed. - GetInfoAsync throws NotChronosServerException for answers that are not a Chronos server; another service's certificate is never offered for trust and no credentials are sent to it. Both clients name the address asked. - Unraid template, compose file, user guide, README, BRIEF, DECISIONS, CHANGELOG (with an Unraid upgrade note) and ARCHITECTURE updated; en/it strings added. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 + deploy/docker/docker-compose.yml | 11 +- deploy/releases-repo/README.md | 33 ++- deploy/unraid/chronos.xml | 9 +- docs/ARCHITECTURE.md | 2 +- docs/BRIEF.md | 38 ++- docs/CHANGELOG.md | 31 +++ docs/DECISIONS.md | 8 + i18n/en/Admin.resx | 15 +- i18n/en/Server.resx | 1 + i18n/en/Uploader.resx | 1 + i18n/it/Admin.it.resx | 15 +- i18n/it/Server.it.resx | 1 + i18n/it/Uploader.it.resx | 1 + src/Chronos.App/Sections/ServerViewModel.cs | 4 +- src/Chronos.App/Server/ConnectFlow.cs | 19 +- src/Chronos.App/Server/ServerSession.cs | 11 +- src/Chronos.Protocol/Admin.cs | 12 +- src/Chronos.Protocol/Client/ChronosAddress.cs | 49 ++++ .../Client/ChronosApiException.cs | 17 +- src/Chronos.Protocol/Client/ChronosClient.cs | 76 +++++- .../Admin/web/pages/settings.js | 51 +++- .../Configuration/ServerOptions.cs | 34 ++- .../Configuration/ServerSettingsStore.cs | 69 ++++- src/Chronos.Server/Hosting/ServerHost.cs | 6 + src/Chronos.Uploader/Server/ServerAddress.cs | 18 +- src/Chronos.Uploader/Server/ServerSession.cs | 1 + .../Shell/ConnectViewModel.cs | 3 +- .../Server/ConnectFlowTests.cs | 26 ++ .../Uploader/ConnectViewModelTests.cs | 5 +- .../Uploader/ServerAddressTests.cs | 12 + .../Api/ServerIdentityTests.cs | 124 +++++++++ .../Hosting/PublicPortTests.cs | 237 ++++++++++++++++++ 33 files changed, 862 insertions(+), 82 deletions(-) create mode 100644 src/Chronos.Protocol/Client/ChronosAddress.cs create mode 100644 tests/Chronos.Server.Tests/Api/ServerIdentityTests.cs create mode 100644 tests/Chronos.Server.Tests/Hosting/PublicPortTests.cs diff --git a/README.md b/README.md index d64d577c..b8a784c1 100644 --- a/README.md +++ b/README.md @@ -225,6 +225,10 @@ security problems go privately to the maintainers (`SECURITY.md`), never into a prefixes when it copies the files to a separate releases repository: keep them verbatim. To try the template, save it on the Unraid server as a user template (`/boot/config/plugins/dockerMan/templates-user/my-chronos-server.xml`) and pick *chronos-server* in Docker › *Add container* › *Template*. +- Ports: in a container the server listens on 8080 and 8443 (read-only in the admin panel); the host ports clients use + are the *Public HTTP/HTTPS port* settings (`CHRONOS_PUBLIC_HTTP_PORT`, `CHRONOS_PUBLIC_HTTPS_PORT`). Clients type the + *Client address* of Settings › Network and TLS; LAN discovery reaches them only with host networking (Unraid network + type *Host*). The user guide (`deploy/releases-repo/README.md`) explains both. ## Repository layout diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 8f0e1e37..a9581d72 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -11,9 +11,11 @@ services: depends_on: postgres: condition: service_healthy - # Publishing a port as another host port ("18443:8443")? Set CHRONOS_PUBLIC_HTTPS_PORT (and _HTTP_PORT) below to the - # host port. LAN discovery reaches clients only with "network_mode: host"; on this bridge network clients add the - # server by its address. With host networking drop "ports", give the postgres service + # Clients connect to https://:8443, the Client address the admin panel shows (Settings › Network and TLS). + # Publishing a port as another host port ("18443:8443")? Keep the container port (after the colon) and set + # CHRONOS_PUBLIC_HTTPS_PORT and CHRONOS_PUBLIC_HTTP_PORT below, or the public ports in the admin panel, to the host + # ports. LAN discovery reaches clients only with "network_mode: host"; on this bridge network clients type the + # client address. With host networking drop "ports", give the postgres service # ports: ["127.0.0.1:5432:5432"] and set CHRONOS_DB_HOST to 127.0.0.1: the name "postgres" no longer resolves there. ports: - "8080:8080" @@ -35,6 +37,9 @@ services: # host itself, run this service with network_mode: host; the proxy then reaches Chronos over loopback. CHRONOS_TLS_MODE: auto # CHRONOS_TRUSTED_PROXIES: "172.30.0.10" + # The host ports clients use, when "ports" publishes 8080 and 8443 as others. Set here, the admin panel can no + # longer change them. + # CHRONOS_PUBLIC_HTTP_PORT: "8080" # CHRONOS_PUBLIC_HTTPS_PORT: "8443" CHRONOS_SERVER_NAME: Chronos Server # Jobs run one at a time. Photos the running job processes at once (default: half the cores), and the priority queue diff --git a/deploy/releases-repo/README.md b/deploy/releases-repo/README.md index 443602dc..80652089 100644 --- a/deploy/releases-repo/README.md +++ b/deploy/releases-repo/README.md @@ -70,9 +70,12 @@ Create the archive folder owned by `PUID:PGID` first (for example `mkdir -p :8080/admin`, sign in as `admin` with the password from `.env` and choose a new one. Chronos -clients connect to `https://:8443`; the first connection shows the server's certificate fingerprint, which the -admin panel shows under Settings so you can compare them. +Open `http://:8080/admin`, sign in as `admin` with the password from `.env` and choose a new one. Chronos and +the Uploader connect to the *Client address* the admin panel shows under Settings › Network and TLS, by default +`https://:8443` (an address typed without a port means 8443; `https://` alone means 443, a reverse proxy). +The first connection shows the server's certificate fingerprint, which the admin panel shows under Settings so you can +compare them. An address that answers but is not Chronos (another service on that port) is reported as such, and its +certificate is never offered for trust. - Image: `gitea.encke-hake.ts.net/balbosoft/chronos-server:latest`, the newest stable release (before the first one, the newest pre-release); also `:`, and `:nightly`, the development version rebuilt every night, not for @@ -95,12 +98,14 @@ admin panel shows under Settings so you can compare them. variable fixes is read-only there, and its tooltip names the variable. The compose file and Unraid template of earlier versions set `CHRONOS_LOG_LEVEL: Information`, which now fixes both levels: remove it (compose: delete the line; Unraid: edit the container and clear *Log level*) to choose them in the panel. -- Other host ports: when you publish the container's ports as other host ports (`18443:8443`), set - `CHRONOS_PUBLIC_HTTPS_PORT` (and `CHRONOS_PUBLIC_HTTP_PORT`) to the host ports, so the admin panel's redirect to HTTPS - and LAN discovery name the ports clients can reach. +- Other host ports: when you publish the container's ports as other host ports (`18443:8443`), keep the container + ports (8080 and 8443: in a container the admin panel shows them read-only) and enter the host ports as *Public HTTP + port* and *Public HTTPS port* in Settings › Network and TLS, or set `CHRONOS_PUBLIC_HTTP_PORT` and + `CHRONOS_PUBLIC_HTTPS_PORT`, which then lock them. They apply at once: the client address, the admin panel's + redirect to HTTPS and LAN discovery name the ports clients can reach. - LAN discovery (`CHRONOS_DISCOVERY`, on by default) needs host networking (`network_mode: host` in compose, Network - type *Host* on Unraid): on a bridge network its broadcasts never leave the container's network. Without it, add the - server in Chronos by its address. With `network_mode: host` the name `postgres` no longer resolves: remove the + type *Host* on Unraid): on a bridge network its broadcasts never leave the container's network. Without it, type the + client address in Chronos and in the Uploader. With `network_mode: host` the name `postgres` no longer resolves: remove the `ports` of the `chronos` service, publish PostgreSQL on loopback (`ports: ["127.0.0.1:5432:5432"]` under `postgres`) and set `CHRONOS_DB_HOST: 127.0.0.1`. - Behind a reverse proxy (`CHRONOS_TLS_MODE=proxy`), only the proxies listed in `CHRONOS_TRUSTED_PROXIES` may set @@ -126,10 +131,18 @@ admin panel shows under Settings so you can compare them. 3. Docker › *Add container* › Template `chronos-server`. Set the admin password, the database host, password and the archive share (default `/mnt/user/Timelapse`). The database host is the Unraid server's IP address (the PostgreSQL template publishes port 5432): container names resolve only when both containers are on the same custom Docker - network, not on the default *bridge*. If you change the HTTPS port, enter the same port in *Public HTTPS port*. + network, not on the default *bridge*. If you change the HTTP or HTTPS port, enter the same port in *Public HTTP port* + or *Public HTTPS port* (or later in the admin panel's Settings › Network and TLS). *Array view* is the same share under `/mnt/user0` (default `/mnt/user0/Timelapse`): the admin panel then shows the array's free space rather than the cache's. Change it with the archive share, or remove it and clear *Space path*. -4. Open the WebUI (`http://[IP]:8080/admin`). +4. Open the WebUI (`http://[IP]:8080/admin`). Clients connect to the *Client address* in Settings › Network and TLS, + `https://[IP]:`. On network type *Bridge* LAN discovery stays inside Docker, so clients do not find the + server by themselves: type that address. Network type *Host* lets them find it. + +Upgrading a container made from an earlier template, or one on `:nightly`: edit the container, set *Repository* to +`…/chronos-server:latest`, and set *Public HTTP port* and *Public HTTPS port* to the host ports the template maps (for +example 8087 and 8444), or enter them in the admin panel. The ports the panel listed as HTTP and HTTPS port are the +container's (8080 and 8443), not the ones clients use. The template file is [`unraid/chronos.xml`](unraid/chronos.xml). diff --git a/deploy/unraid/chronos.xml b/deploy/unraid/chronos.xml index 396235af..f571ea1a 100644 --- a/deploy/unraid/chronos.xml +++ b/deploy/unraid/chronos.xml @@ -9,7 +9,7 @@ false https://gitea.encke-hake.ts.net/BalboSoft/Chronos/issues https://gitea.encke-hake.ts.net/BalboSoft/Chronos - Chronos Server keeps a shared, verified archive of time-lapse photo sequences and renders them. Pair it with the official PostgreSQL 17 container. + Chronos Server keeps a shared, verified archive of time-lapse photo sequences and renders them. Pair it with the official PostgreSQL 17 container. Clients connect to the Client address the admin panel shows (Settings, Network and TLS); LAN discovery reaches them only with network type Host. MediaServer:Photos Tools: http://[IP]:[PORT:8080]/admin https://gitea.encke-hake.ts.net/BalboSoft/Chronos/raw/branch/main/deploy/unraid/chronos.xml @@ -21,9 +21,10 @@ A PostgreSQL 16 or 17 container (official "postgres" template) with a database and user for Chronos. - 8080 - 8443 - + 8080 + 8443 + + /mnt/user/Timelapse /mnt/user0/Timelapse /mnt/user/appdata/chronos diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4c77b59e..cf6d73c8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -10,7 +10,7 @@ Companion to `docs/BRIEF.md` (scope, behaviour) and `docs/ui/DESIGN.md` (looks). | `src/Chronos.Core` | net10.0 | Engine shared by every program: metadata, codecs, imaging, analysis, advisor, motion, render, video containers and managed encoders, archive format, naming, import planning, packaging, localization runtime, diagnostics, brand mark | | `src/Chronos.Core.Windows` | net10.0-windows | WIC decoders and codec inventory, Media Foundation encoders, DXGI adapters, removable devices and volume free space, DPAPI, shell launcher, window chrome, power (P/Invoke/COM only) | | `src/Chronos.Data` | net10.0 | `IDatabase`, SQLite binding, PostgreSQL wire client, migrations, repositories, the job engine, the archive engine (`Archiving`), the analysis/render engine (`Processing`) and the client sync engine (`Sync`) | -| `src/Chronos.Protocol` | net10.0 | API v1 DTOs, source-generated JSON context, typed `ChronosClient` with certificate pinning and bandwidth limiting | +| `src/Chronos.Protocol` | net10.0 | API v1 DTOs, source-generated JSON context, typed `ChronosClient` with certificate pinning and bandwidth limiting, `ChronosAddress` (how both clients read a typed server address) | | `src/Chronos.Server` | net10.0 (Web SDK) | ASP.NET Core minimal API, auth, uploads, sync, jobs, render nodes, events, embedded admin panel, Windows service host | | `src/Chronos.Ui` | net10.0-windows (WPF) | Theme (DESIGN tokens), icons, standard and custom controls, visuals (charts, filmstrip, preview, curve editor, virtualizing grid), `Loc` markup extension, MVVM helpers, notification-area icon | | `src/Chronos.App` | WPF exe `Chronos.exe` | Desktop client | diff --git a/docs/BRIEF.md b/docs/BRIEF.md index 68b91fef..d86bf2bf 100644 --- a/docs/BRIEF.md +++ b/docs/BRIEF.md @@ -1498,7 +1498,15 @@ Global job bar mirrors the active job. First connection shows the certificate fingerprint (trust-on-first-use); login modal; per-sequence sync actions and states; conflict resolution only for settings JSON (keep -mine / take server / save both). +mine / take server / save both). The address field, here and in the Uploader (§15), reads +one rule: no scheme means HTTPS, and then no port means 8443, the server's HTTPS port; +`https://` alone keeps 443 (a reverse proxy); a typed port is kept; a bare IPv6 +address gets its brackets. An address that answers but not as a Chronos Server (an HTML +page, a redirect to a sign-in page, a 4xx without a Chronos error, JSON of another shape) +fails with one sentence naming the address and the port to check; behind a certificate not +trusted yet, `server/info` is read once without checking it and without credentials, and only +a Chronos answer leads to the fingerprint question, so another service's certificate is never +offered for trust (amended 2026-11-04, owner review 3). ### 12.8 Settings @@ -2119,7 +2127,14 @@ clean-up* schedule's age limit, R10), Logs (amended 2026-10-26, R11: file level level (Trace…None, default Information), keep logs (days), file size (MB), logs total (MB), rotation (daily or hourly, UTC), keep audit (days; the *Audit log clean-up* schedule's age limit, §14.6), diagnostics logs (MB), applied without a restart)). A field an environment -variable fixes is read-only, its tooltip naming that variable (`lockedBy`, §14.3; R11). The +variable fixes is read-only, its tooltip naming that variable (`lockedBy`, §14.3; R11). +Network and TLS (amended 2026-11-04, owner review 3): HTTP port and HTTPS port (in a +container *Container HTTP/HTTPS port*, read-only: the template maps them to host ports), +*Public HTTP port* and *Public HTTPS port* (empty: the listening port, shown as placeholder; +applied at once to LAN discovery and the HTTPS redirect), and a read-only *Client address* +with Copy: `https://:`, the proxy's +address in TLS mode proxy, which is what users type in Chronos and the Uploader; the +discovery tooltip says that a container needs network type Host for it. The last group of Settings, About, is read-only: version, API version, database and uptime (the server name and the fingerprint are in the groups above); an old `#/about` link opens Settings on it (amended 2026-10-26, R4, R5). Same UI rules: tooltips only, light/dark, localised via `/api/v1/i18n`, keyboard @@ -2270,10 +2285,19 @@ it has worked in between; uploads always check the archive's own volume, §14.4, conversion the tighter of the two, §14.3: amended 2026-10-26, R7), `CHRONOS_DB=postgres|sqlite` (Linux: postgres only), `CHRONOS_DB_HOST`, `CHRONOS_DB_PORT=5432`, `CHRONOS_DB_NAME`, `CHRONOS_DB_USER`, `CHRONOS_DB_PASSWORD`, `CHRONOS_DB_SSLMODE=prefer`, -`CHRONOS_HTTP_PORT=8080`, `CHRONOS_HTTPS_PORT=8443`, `CHRONOS_TLS_MODE=auto|pem|proxy`, +`CHRONOS_HTTP_PORT=8080`, `CHRONOS_HTTPS_PORT=8443` (in a container, where +`DOTNET_RUNNING_IN_CONTAINER=true`, the listening ports are the template's: only these +variables change them, the admin panel shows them read-only and a `server.json` value is +ignored with a warning), `CHRONOS_PUBLIC_HTTP_PORT` and `CHRONOS_PUBLIC_HTTPS_PORT` (the host +ports clients use when a container's ports are published as others: LAN discovery, the HTTPS +redirect and the admin panel's client address use them; also the admin panel's *Public +HTTP/HTTPS port*, `PublicHttpPort`/`PublicHttpsPort` in `server.json`, applied at once; +amended 2026-11-04, owner review 3), `CHRONOS_TLS_MODE=auto|pem|proxy`, `CHRONOS_TLS_CERT`, `CHRONOS_TLS_KEY`, `CHRONOS_SERVER_NAME`, `CHRONOS_LANG=en`, `CHRONOS_PARALLELISM` (photos the running job processes at once; `CHRONOS_WORKERS`, its former -name, still sets it), `CHRONOS_PRIORITY_QUEUE=false`, `CHRONOS_DISCOVERY=true` (LAN UDP beacon), +name, still sets it), `CHRONOS_PRIORITY_QUEUE=false`, `CHRONOS_DISCOVERY=true` (LAN UDP beacon; it leaves a +container only with host networking, Unraid network type Host: amended 2026-11-04, owner +review 3), `CHRONOS_LOG_LEVEL` (Trace|Debug|Information|Warning|Error|Critical|None, also `info`, `warn`, `off`; default Information: sets the level of the log files and of the console and locks both in the admin panel), `CHRONOS_LOG_CONSOLE_LEVEL` (the console alone, read after @@ -2536,7 +2560,10 @@ the log variables, *Log level* `CHRONOS_LOG_LEVEL` included, and *Audit retentio `CHRONOS_AUDIT_RETENTION_DAYS` are advanced and empty by default (each description gives the default), so the admin panel's Settings › Logs chooses them; a value given in the template locks its setting; TZ also sets the time zone of the schedules; amended -2026-10-26, R10, R11), description ≤ 2 sentences. +2026-10-26, R10, R11), *Public HTTP port* `CHRONOS_PUBLIC_HTTP_PORT` and *Public HTTPS port* +`CHRONOS_PUBLIC_HTTPS_PORT`, empty by default, next to the ports, whose descriptions say to +enter the same host port there when it changes; the overview names the client address and +that LAN discovery needs network type Host (amended 2026-11-04, owner review 3), description ≤ 2 sentences. Registry and Project `https://gitea.encke-hake.ts.net/BalboSoft/Chronos`, Support `https://gitea.encke-hake.ts.net/BalboSoft/Chronos/issues`, TemplateURL `https://gitea.encke-hake.ts.net/BalboSoft/Chronos/raw/branch/main/deploy/unraid/chronos.xml`, @@ -2735,6 +2762,7 @@ questions asked and the answers; DECISIONS rows give the reasons. | 2026-10-26 | Owner review 2, R7 (naming) | §7.1, §13, §14.3 | One naming rule for import, upload and Reorganize: the sequence's camera and lens, `{n}` its place, a frame without a time at the sequence's start; template rules everywhere a template is typed or sent (no folder level scans skip, one a value such as a title gives escaped with `_`; a file template keeps the extension, tells photos apart, holds no slash; long names shortened before `.{ext}`; titles as text), held to a template only when it is given anew; `invalid_template` names the rule. | | 2026-10-26 | Owner review 2, R7 (conversion) | §5, §7, §8.1, §8.3, §8.7, §9, §12.2, §12.4, §12.5, §13, §14.3, §14.4, §14.5, §14.8, §14.9 | Convert after import on the desktop (the Archive manager's set, the Library's selection) and the admin panel (the Library's selection): JPEG with a quality, TIFF-16 or linear DNG (the archival choice, scene-referred so a RAW's highlights above white and colours outside sRGB survive), Replace or New sequence chosen at every run and never remembered, behind a dry run that lists each sequence's photos, sizes and the photos that stay as they are with why, and the free space where the conversion writes; Replace confirmed by typing; the `convert` job (stored as 19) converts exactly the photos confirmed, one sequence at a time and all or nothing, resumable through its journals and staging, never twice at once; full-resolution decodes only (the managed decoders first, never a 16-bit file from an 8-bit RAW development; the server leaves what it cannot read to a PC), what Chronos reads from a photo never changed (profiles carried, a linear DNG of sRGB values only), Exif carried, every file verified by the server's decoders; Replace swaps the files of the frames in place under a crash-safe journal, the originals going into a replaced trash entry that Undo or Restore swaps back and that Empty erases only while the archive on disk shows each conversion intact, or deleted on its own word (a tombstone, the trash, an erasure record); import still copies byte for byte and the card keeps a converted photo's copy; sync and the ingest count every encoding of a photo as one; `POST /api/v1/archive/convert` with the plan cache it shares with Reorganize, `sequenceChanged` `converted` and `created`, the audit `archive_converted`. | | 2026-10-26 | Owner review 2, R8 (phase 5a: workspace and projects, local home) | §4.4, §5, §7, §12.2, §12.3, §12.6, §12.8, §14.5, §14.6 | A sequence's home (this PC's archive) keeps its projects: Main, mirrored both ways with the sequence's settings so older clients and sync keep working, and other named projects, each a linear history of immutable versions in the portable form (positions parked by photo, SHA-256 of canonical text), stored as sidecars in `.chronos/projects/` and indexed by migration 0009 (`projects`, `project_versions`, `renders.project_id`/`project_version_id`); deletions only on the archive's word, the trash read first; Edit opens only workspace projects: *Open in workspace* (project, proxies), the `workspace-copy` job (stored as 20, desktop only, hash-verified, resumable, space checked), the working state in a folder outside the library, the project button with its state chip and menu (Save version, Sync, History with Compare and Restore, Open, New, Rename, Delete, Remove local copy), push and pull with replay and field-level merge, conflicts only when both sides changed a setting (Keep mine, Take library's, Save both, Later), renders at the home with the settings embedded; Settings › Workspace (folder, sync, kept versions). The server home is phase 5b; originals, local render, clean-up and the rest of Settings › Workspace are phase 5c. | +| 2026-11-04 | Owner review 3 (ports) | §12.7, §14.8, §14.9, §15, §19.6 | The public HTTP/HTTPS ports are server settings as well as variables (a variable locks them), applied at once; in a container the listening ports are locked to the template's; the admin panel's Network and TLS shows the container's ports, the public ports and the client address with Copy; clients read an address without scheme or port as port 8443 and report an address that answers as something else, never offering its certificate for trust; the Unraid template and compose gain *Public HTTP port*. | ## Appendix A — `CLAUDE.md` content (create verbatim in Phase 0, keep updated) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 90bde739..c5f95bee 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -5,6 +5,37 @@ commits follow Conventional Commits (release notes are generated from them by `C ## [Unreleased] +### Fixed +- Chronos and the Uploader could not reach a server in a container whose ports are published as other host ports + (owner review 3). The admin panel's Settings › Network and TLS listed the container's ports (8080, 8443) as if + clients used them. In a container it now shows them read-only as *Container HTTP port* and *Container HTTPS port*, + followed by *Public HTTP port* and *Public HTTPS port* (the host ports; empty: the same as the listening ports) and + a *Client address* with Copy: exactly what to type in Chronos and in the Uploader. +- An address typed without a port (`192.168.1.20`, `nas.local`) now means port 8443, as the placeholder shows; + `https://name` alone still means 443 (a reverse proxy), and a typed port is kept. Addresses saved earlier keep their + port. +- An address that answers but is not a Chronos Server (another service on that port: a web page, a redirect to its + sign-in page, a 404 or 401, JSON of another kind) now says *No Chronos server answers at …; check the port*, naming + the address with its port. Before, JSON of another kind passed as a server (the Uploader then sent it the + password), a 401 read as a wrong password, and another service's self-signed certificate was offered for trust; + that certificate is now never offered. + +### Changed +- The public ports are server settings: edited in the admin panel and applied at once to LAN discovery and the + redirect to HTTPS, or set by `CHRONOS_PUBLIC_HTTP_PORT` / `CHRONOS_PUBLIC_HTTPS_PORT`, which lock them. In a + container the listening ports change only through `CHRONOS_HTTP_PORT` / `CHRONOS_HTTPS_PORT`; a port saved for them + in `server.json` is ignored, with a warning in the log. +- The Unraid template and the compose file have *Public HTTP port* (`CHRONOS_PUBLIC_HTTP_PORT`) next to *Public HTTPS + port*; the port descriptions say to enter the same host port there. LAN discovery's tooltip, the template and the + user guide say that discovery leaves a container only with network type *Host*: on *Bridge*, type the client + address. + +### Upgrade note for Unraid +- Edit the container: set *Repository* from `…/chronos-server:nightly` to `…/chronos-server:latest`, and set *Public + HTTP port* and *Public HTTPS port* to the host ports the template maps (for example 8087 and 8444), or, after the + update, enter them in the admin panel's Settings › Network and TLS. Then connect Chronos and the Uploader to the + *Client address* shown there (for example `https://192.168.1.20:8444`). + ## [0.1.0-rc.8] — 2026-11-03 ### Added diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 2dd7a509..376a1397 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -611,3 +611,11 @@ One line per decision: date · decision · alternative · reason. | 2026-11-03 | Workspace texts: the workspace's strings live in the existing Editor, Tooltips, Settings and Errors areas; the home is called "the library" (the server home will name its server), Main is shown in the UI language (it: Principale), and versions carry the bare PC name (`Environment.MachineName`; History strips `chronos@`, `server@`, `workspace@` and `Chronos on`). (Owner review 2, R8.) | A new Workspace area | No new resource files to translate; the wording matches the rest of the desktop. | | 2026-11-03 | `ProjectMenuViewModel` reaches the window only through `IWorkspaceUi` (dialogs, `ShowDialogWhenFree`, confirmations, toasts, opening and closing a project). A conflict found by an automatic sync waits for the open dialog and is asked once. (Owner review 2, R8.) | Depend on the shell; replace the open dialog | Its logic is tested without a window, and a background prompt never hides what the user is doing. | | 2026-11-03 | Leases: `LeaseFile.TryAcquire` and `AcquireAsync` take `createDirectory` (default true); the copy's clean-up passes false. `WorkspaceSync.OpenAsync` reads the working state and the media under the project's lease; a lease still busy after the wait is `Errors.Workspace.Busy`. (Owner review 2, R8, fix rounds 1, 2 and 5.) | Always create the folder; read without the lease | A clean-up must never make a removed project folder again, and the editor never reads a half-written working state. | +| 2026-11-04 | Public ports are settings: `PublicHttpPort`/`PublicHttpsPort` in `server.json`, edited in Settings › Network and TLS, locked by `CHRONOS_PUBLIC_HTTP(S)_PORT`, applied at once by setting the shared `ServerOptions` that LAN discovery and the admin redirect read at every use. | Variables only | The owner read the container ports in the panel as the ports to use; the host ports must be settable where the ports are shown, and nothing caches them. | +| 2026-11-04 | `ServerSettingsDto` gains `PublicHttpPort`, `PublicHttpsPort` and `InContainer`, appended as optional positional members. In a request a null public port keeps the saved value and 0 clears it; responses send null when unset. | null clears | A client or script of the earlier shape sends no public ports: with null as "clear" every save from it would drop them, or be refused as `setting_locked` when a variable fixes them. | +| 2026-11-04 | In a container (`DOTNET_RUNNING_IN_CONTAINER=true`, read in `ServerOptions.Load`; tests set `ServerOptions.InContainer`) the listening ports are locked (listed in `Locked`, `lockedBy` `DOTNET_RUNNING_IN_CONTAINER` unless a `CHRONOS_HTTP(S)_PORT` sets them) and a `server.json` value for them is ignored with a warning at start; the variables still change them. | Keep honouring server.json | The template publishes the default container ports: a port saved from the panel before would leave the container unreachable after a restart. Host networking users who need other ports set the variables. | +| 2026-11-04 | Listening ports are validated only when a request changes them. | Always validate | A value the panel cannot change (a container's, the test server's 0) must never block saving the other settings. | +| 2026-11-04 | The admin panel's client address is computed in the browser from the saved settings: `https://` + `location.hostname` (IPv6 in brackets) + `:` + public HTTPS port or HTTPS port (no port when 443); `location.origin` in TLS mode proxy. No other page shows a pairing code or a connect hint, so it appears only in Settings › Network and TLS. | Server-side address | Only the browser knows the host name the LAN uses for the server (an IP, a NAS name); the server sees its container address. | +| 2026-11-04 | One address rule for both clients, `Chronos.Protocol.Client.ChronosAddress` (both apps reference Chronos.Protocol, which builds on Linux): no scheme and no port means https on 8443, `https://host` keeps 443, a typed port is kept, a bare IPv6 address is bracketed. Saved addresses carry their scheme, so they keep their port. | A copy per app | The placeholder and the error text say `nas.local:8443`; "192.168.30.23" meant port 443. | +| 2026-11-04 | `ChronosClient.GetInfoAsync` throws `NotChronosServerException` for an HTML or redirected page, JSON without a Chronos `ServerInfo` (name, version, API version, lists, limits), or a 4xx without a Chronos error; on an untrusted certificate it reads `server/info` once more with certificate checks off and no token, and only a Chronos answer leads to the fingerprint question. Nothing is trusted or stored by that read. | Ask about the fingerprint first | Before, `{}` was accepted as a server (the Uploader then sent the password to it), a 401 read as a wrong password, and the self-signed certificate of another service on port 8443 was offered for trust. | +| 2026-11-04 | The not-Chronos error names the normalised address (port included) in new keys `Server.Error.NotChronosAt` and `Uploader.Connect.Error.NotChronosAt`; the old keys stay as they are. | Add {0} to the old keys | The 36 other cultures translate the old keys without the placeholder; changing it would fail the i18n check until they are translated again. | diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index 4cd9a4c6..931d756d 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -786,16 +786,23 @@ A sequence has at most 50 tags.long Rated {0} out of 5; choose it again to clear the rating About + Address copied. Keep audit (days) Age limit of the Audit log clean-up schedule: older audit entries are deleted; 0: kept forever Chunk size (MiB) Size of each upload chunk; smaller chunks resume faster on poor links + Client address + Type this in Chronos and in the Uploader to connect to this server Console level Least severe level written to the console, the container's log + Container HTTP port + Container HTTPS port + Port inside the container, fixed by its template; the host maps it to the port clients use, which goes in the public port below + Copy the client address Diagnostics logs (MB) How much of the end of each log file the diagnostics zip includes LAN discovery - Announce this server on the local network so clients find it + Announce this server on the local network so clients find it; a container needs network type Host (in Bridge mode the announcements stay inside Docker: type the client address) Fingerprint SHA-256 of the certificate; clients ask the user to compare it once HTTP port @@ -840,8 +847,12 @@ On: a job of a higher level pauses the running one without asking, and that one resumes by itself afterwards. Off: jobs wait their turn Not via proxy TLS mode is Reverse proxy, but this page did not come through a trusted proxy over HTTPS. Open it through your proxy, or add the proxy's address to CHRONOS_TRUSTED_PROXIES. + Public HTTP port + Host port clients use for HTTP when it differs from the HTTP port, as a container maps it; empty: the HTTP port + Public HTTPS port + Host port clients use for HTTPS when it differs from the HTTPS port, as a container maps it; empty: the HTTPS port Restart required - Saved ports, TLS or chunk size apply after a restart + Saved listening ports, TLS or chunk size apply after a restart Daily Hourly Server diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index 2928180e..e2c6c48f 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -75,6 +75,7 @@ The last administrator cannot be removed or disabled.long This method is not allowed here.long A new folder would lie inside the folder of another sequence.long + No Chronos server answers at {0}; check the port (the admin panel's Settings › Network and TLS shows the client address).long The archive's volume lacks the space the conversion needs.long Not found.long That address is not a Chronos Server.long diff --git a/i18n/en/Uploader.resx b/i18n/en/Uploader.resx index 75166fa3..320070df 100644 --- a/i18n/en/Uploader.resx +++ b/i18n/en/Uploader.resx @@ -24,6 +24,7 @@ The server reported an error.long Enter an address such as https://nas.local:8443.long This address is not a Chronos Server.long + No Chronos server answers at {0}; check the port (the admin panel's Settings › Network and TLS shows the client address).long The server did not answer.long The server certificate was not trusted.long Found diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index 67301743..fe6cae3f 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -779,16 +779,23 @@ Una sequenza ha al massimo 50 tag.long Voto {0} su 5; sceglilo di nuovo per togliere il voto Informazioni + Indirizzo copiato. Conserva controllo (giorni) Limite di età della pianificazione Pulizia registro controllo: le voci più vecchie vengono eliminate; 0: conservate per sempre Dimensione blocco (MiB) Dimensione di ogni blocco di caricamento; blocchi piccoli riprendono prima su linee lente + Indirizzo client + Da inserire in Chronos e nell'Uploader per collegarsi a questo server Livello console Livello minimo scritto nella console, il log del container + Porta HTTP interna + Porta HTTPS interna + Porta dentro il container, fissata dal suo template; l'host la mappa sulla porta usata dai client, da inserire come porta pubblica qui sotto + Copia l'indirizzo client Log diagnostica (MB) Quanta parte finale di ogni file di log include lo zip di diagnostica Rilevamento LAN - Annuncia questo server nella rete locale così che i client lo trovino + Annuncia questo server nella rete locale così che i client lo trovino; in un container serve il tipo di rete Host (in Bridge gli annunci restano dentro Docker: inserisci l'indirizzo client) Impronta SHA-256 del certificato; i client chiedono all'utente di confrontarlo una volta Porta HTTP @@ -833,8 +840,12 @@ Attiva: un'attività di livello più alto mette in pausa quella in corso senza chiedere, e quella riprende da sola dopo. Disattiva: le attività aspettano il loro turno Senza proxy La modalità TLS è Reverse proxy, ma questa pagina non è arrivata da un proxy attendibile in HTTPS. Aprila tramite il proxy o aggiungi l'indirizzo del proxy a CHRONOS_TRUSTED_PROXIES. + Porta HTTP pubblica + Porta dell'host che i client usano per HTTP quando è diversa dalla porta HTTP, come la mappa un container; vuota: la porta HTTP + Porta HTTPS pubblica + Porta dell'host che i client usano per HTTPS quando è diversa dalla porta HTTPS, come la mappa un container; vuota: la porta HTTPS Riavvio richiesto - Porte, TLS o dimensione blocchi salvati valgono dopo un riavvio + Porte di ascolto, TLS o dimensione blocchi salvati valgono dopo un riavvio Giornaliera Oraria Server diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index df711ae3..6af7104a 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -73,6 +73,7 @@ L'ultimo amministratore non può essere rimosso o disattivato. Metodo non consentito qui. Una nuova cartella finirebbe dentro la cartella di un'altra sequenza. + Nessun server Chronos risponde a {0}; controlla la porta (l'indirizzo client è nel pannello di amministrazione, Impostazioni › Rete e TLS). Il volume dell'archivio non ha lo spazio che serve alla conversione. Non trovato. Questo indirizzo non è un Chronos Server. diff --git a/i18n/it/Uploader.it.resx b/i18n/it/Uploader.it.resx index 75b4655b..c32430fd 100644 --- a/i18n/it/Uploader.it.resx +++ b/i18n/it/Uploader.it.resx @@ -22,6 +22,7 @@ Il server ha segnalato un errore. Inserisci un indirizzo come https://nas.local:8443. Questo indirizzo non è un Chronos Server. + Nessun server Chronos risponde a {0}; controlla la porta (l'indirizzo client è nel pannello di amministrazione, Impostazioni › Rete e TLS). Il server non ha risposto. Il certificato del server non è stato accettato. Trovati diff --git a/src/Chronos.App/Sections/ServerViewModel.cs b/src/Chronos.App/Sections/ServerViewModel.cs index 3ac07603..640a6b0b 100644 --- a/src/Chronos.App/Sections/ServerViewModel.cs +++ b/src/Chronos.App/Sections/ServerViewModel.cs @@ -212,7 +212,7 @@ public sealed class ServerViewModel : SectionViewModel Shell.Settings.Encoders.CollectionChanged += OnEncodersChanged; Sync.Attach(); await _session.RestoreAsync(); - if (_session.Flow.Error is not ConnectError.None and var error && !_session.IsConnected) ErrorText = ServerSession.ErrorText(error); + if (_session.Flow.Error is not ConnectError.None and var error && !_session.IsConnected) ErrorText = ServerSession.ErrorText(error, _session.Flow.Address); } public override void Dispose() @@ -253,7 +253,7 @@ public sealed class ServerViewModel : SectionViewModel Address = ServerAddress.Display(Session.SavedAddress); return; } - if (Session.Flow.Error is not ConnectError.None and var error) ErrorText = ServerSession.ErrorText(error); + if (Session.Flow.Error is not ConnectError.None and var error) ErrorText = ServerSession.ErrorText(error, Session.Flow.Address); } private async Task SignOutAsync() diff --git a/src/Chronos.App/Server/ConnectFlow.cs b/src/Chronos.App/Server/ConnectFlow.cs index ec9eda82..a20d7d70 100644 --- a/src/Chronos.App/Server/ConnectFlow.cs +++ b/src/Chronos.App/Server/ConnectFlow.cs @@ -269,6 +269,7 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) : internal static ConnectError? Classify(Exception ex, CancellationToken ct) => ex switch { UntrustedCertificateException => ConnectError.Untrusted, + NotChronosServerException => ConnectError.NotChronos, ChronosApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => ConnectError.BadCredentials, ChronosApiException { Status: HttpStatusCode.NotFound } => ConnectError.NotChronos, ChronosApiException api when api.IsTransient => ConnectError.Unreachable, @@ -283,19 +284,11 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) : /// Server addresses as typed in the address field. public static class ServerAddress { - /// Accepts "nas.local:8443" (https assumed) or a full http(s) URL; the result is the API base, ending with "/". - public static bool TryParse(string? text, out Uri uri) - { - uri = null!; - if (string.IsNullOrWhiteSpace(text)) return false; - var trimmed = text.Trim(); - if (!trimmed.Contains("://", StringComparison.Ordinal)) trimmed = "https://" + trimmed; - if (!Uri.TryCreate(trimmed, UriKind.Absolute, out var parsed) || parsed.Scheme is not ("https" or "http") || parsed.Host.Length == 0) return false; - var builder = new UriBuilder(parsed) { Query = string.Empty, Fragment = string.Empty }; - if (!builder.Path.EndsWith('/')) builder.Path += "/"; - uri = builder.Uri; - return true; - } + /// + /// Accepts "nas.local" (https on port 8443 assumed), "nas.local:9443" or a full http(s) URL, which keeps its scheme's + /// port; the result is the API base, ending with "/" (, shared with the uploader). + /// + public static bool TryParse(string? text, out Uri uri) => ChronosAddress.TryParse(text, out uri); /// The address as shown in the field: the base URL without its trailing slash. public static string Display(Uri uri) => uri.ToString().TrimEnd('/'); diff --git a/src/Chronos.App/Server/ServerSession.cs b/src/Chronos.App/Server/ServerSession.cs index 633d61e0..34d0786c 100644 --- a/src/Chronos.App/Server/ServerSession.cs +++ b/src/Chronos.App/Server/ServerSession.cs @@ -150,7 +150,7 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable { var result = await _flow.SignInAsync(user, password, attempt.Token); // An answer the flow dropped (the form was cancelled meanwhile) carries no error of its own. - return result == ConnectStep.Connected ? null : ErrorText(_flow.Error is ConnectError.None ? ConnectError.Failed : _flow.Error); + return result == ConnectStep.Connected ? null : ErrorText(_flow.Error is ConnectError.None ? ConnectError.Failed : _flow.Error, _flow.Address); }); if (signedIn && IsConnected) { @@ -198,8 +198,13 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable _flow.Dispose(); } - /// One sentence for a failed step (BRIEF §0.2 rule 6). - public static string ErrorText(ConnectError error) => Loc.L("Server.Error." + error); + /// + /// One sentence for a failed step (BRIEF §0.2 rule 6). An address that answers as something else is named, with where + /// to read the right one (owner review 3). + /// + public static string ErrorText(ConnectError error, Uri? address = null) => error == ConnectError.NotChronos && address is not null + ? Loc.L("Server.Error.NotChronosAt", Formatting.LeftToRight(ServerAddress.Display(address))) + : Loc.L("Server.Error." + error); /// The trust-on-first-use question with the fingerprint split over two lines. public static ConfirmRequest TrustRequest(string server, string fingerprint) => new() diff --git a/src/Chronos.Protocol/Admin.cs b/src/Chronos.Protocol/Admin.cs index 0f591f91..4b7d5141 100644 --- a/src/Chronos.Protocol/Admin.cs +++ b/src/Chronos.Protocol/Admin.cs @@ -10,6 +10,13 @@ namespace Chronos.Protocol; /// is how many photos the running job processes at once (jobs run one at a time), and /// with the priority queue (owner review 1); both apply at once, as /// do (owner review 2, R11; a request without them keeps them as they are). +/// and (owner review 3) are the ports clients reach the server +/// on when the host publishes the listening ports as others (a container): null in a response when they are the +/// listening ports; in a request, null keeps them as they are (a client that predates them) and 0 clears them. They +/// apply at once (LAN discovery, the admin panel's HTTPS redirect). (responses only) says the +/// server runs in a container, whose listening ports the template fixes: they are then locked, named in +/// with the variable DOTNET_RUNNING_IN_CONTAINER unless one of their own fixes them. The +/// members added since are last and optional, so clients and panels of the shape before them keep working. /// public sealed record ServerSettingsDto( string ServerName, @@ -32,7 +39,10 @@ public sealed record ServerSettingsDto( IReadOnlyList Locked, IReadOnlyDictionary LockedBy, bool RestartRequired, - bool ProxyWarning); + bool ProxyWarning, + int? PublicHttpPort = null, + int? PublicHttpsPort = null, + bool InContainer = false); /// /// The log settings of (owner review 2, R11): the least severe level of the files and of the diff --git a/src/Chronos.Protocol/Client/ChronosAddress.cs b/src/Chronos.Protocol/Client/ChronosAddress.cs new file mode 100644 index 00000000..63564310 --- /dev/null +++ b/src/Chronos.Protocol/Client/ChronosAddress.cs @@ -0,0 +1,49 @@ +using System.Net; +using System.Net.Sockets; + +namespace Chronos.Protocol.Client; + +/// +/// Server addresses as a user types them, shared by the desktop client and the uploader (owner review 3). An address +/// without a scheme is HTTPS and, without a port, on , the port Chronos Server listens on, as +/// the placeholder "nas.local:8443" shows; one typed with its scheme keeps that scheme's port ("https://chronos.example.com" +/// is 443, a reverse proxy); a port typed is always kept. A bare IPv6 address gets its brackets. +/// +public static class ChronosAddress +{ + /// The HTTPS port of Chronos Server (CHRONOS_HTTPS_PORT's default). + public const int DefaultPort = 8443; + + /// The API base for , ending with "/", without query or fragment; false when it is not an http(s) address. + public static bool TryParse(string? text, out Uri uri) + { + uri = null!; + if (string.IsNullOrWhiteSpace(text)) return false; + var trimmed = text.Trim(); + var schemeTyped = trimmed.Contains("://", StringComparison.Ordinal); + if (!schemeTyped) + { + // "fd00::5" alone: an address cannot hold its colons unbracketed ("[fd00::5]:9443" parses as an IP too, already bracketed). + if (!trimmed.StartsWith('[') && IPAddress.TryParse(trimmed, out var ip) && ip.AddressFamily == AddressFamily.InterNetworkV6) trimmed = "[" + trimmed + "]"; + trimmed = "https://" + trimmed; + } + if (!Uri.TryCreate(trimmed, UriKind.Absolute, out var parsed) || parsed.Scheme is not ("https" or "http") || parsed.Host.Length == 0) return false; + var builder = new UriBuilder(parsed) { Query = string.Empty, Fragment = string.Empty }; + if (!schemeTyped && !HasPort(trimmed)) builder.Port = DefaultPort; + if (!builder.Path.EndsWith('/')) builder.Path += "/"; + uri = builder.Uri; + return true; + } + + /// True when the authority of (scheme included) names a port, the scheme's default too. + private static bool HasPort(string url) + { + var start = url.IndexOf("://", StringComparison.Ordinal) + 3; + var end = url.IndexOfAny(['/', '?', '#'], start); + var authority = end < 0 ? url[start..] : url[start..end]; + authority = authority[(authority.LastIndexOf('@') + 1)..]; + // "[fd00::5]:9443": the colons inside the brackets belong to the address. + var host = authority.StartsWith('[') ? authority.IndexOf(']', StringComparison.Ordinal) : -1; + return authority.IndexOf(':', host + 1) >= 0; + } +} diff --git a/src/Chronos.Protocol/Client/ChronosApiException.cs b/src/Chronos.Protocol/Client/ChronosApiException.cs index ce6a2c5b..70c4d032 100644 --- a/src/Chronos.Protocol/Client/ChronosApiException.cs +++ b/src/Chronos.Protocol/Client/ChronosApiException.cs @@ -10,10 +10,25 @@ public sealed class ChronosApiException(HttpStatusCode status, ApiError error) public ApiError Error { get; } = error; /// True for errors worth retrying (server busy, gateway, timeout). - public bool IsTransient => Status is HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests + public bool IsTransient => IsTransientStatus(Status); + + /// Statuses worth retrying (server busy, gateway, timeout). + public static bool IsTransientStatus(HttpStatusCode status) => status is HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests or HttpStatusCode.BadGateway or HttpStatusCode.ServiceUnavailable or HttpStatusCode.GatewayTimeout; } +/// +/// The address answers, but not as a Chronos Server (owner review 3): its server/info is an HTML page, a redirect +/// to a sign-in page, a 4xx that is not a Chronos error, JSON of another shape, or, behind a certificate nobody trusted +/// yet, any of those. Usually the wrong port of a host that runs other services. +/// +public sealed class NotChronosServerException(Uri address, Exception? inner = null) + : Exception($"No Chronos server answers at {address}", inner) +{ + /// The API base that was asked. + public Uri Address { get; } = address; +} + /// The server presented a certificate whose fingerprint is not trusted yet (trust-on-first-use, BRIEF §12.7). public sealed class UntrustedCertificateException(string fingerprint) : Exception("Server certificate is not trusted: " + fingerprint) diff --git a/src/Chronos.Protocol/Client/ChronosClient.cs b/src/Chronos.Protocol/Client/ChronosClient.cs index 6eba815b..e5a2ebf2 100644 --- a/src/Chronos.Protocol/Client/ChronosClient.cs +++ b/src/Chronos.Protocol/Client/ChronosClient.cs @@ -20,11 +20,15 @@ public sealed class ChronosClient : IDisposable { private readonly HttpClient _http; private readonly CertificatePinning _pinning; + + /// The client made its own handler, so TLS goes through (tests pass theirs). + private readonly bool _ownsHandler; private string? _token; public ChronosClient(Uri baseAddress, CertificatePinning pinning, string clientName, HttpMessageHandler? handler = null) { _pinning = pinning; + _ownsHandler = handler is null; ClientName = clientName; BaseAddress = baseAddress; var socketsHandler = handler ?? new SocketsHttpHandler @@ -59,8 +63,76 @@ public sealed class ChronosClient : IDisposable // ---------------- Server ---------------- - /// Reads server info; throws when the TLS certificate needs confirmation. - public Task GetInfoAsync(CancellationToken ct = default) => GetAsync("api/v1/server/info", ProtocolJson.Default.ServerInfo, ct); + /// + /// Reads server info; throws when the TLS certificate of a Chronos Server + /// needs confirmation, and when the address answers as something else (owner + /// review 3). Behind a certificate that is not trusted yet, the info is first read once more without checking the + /// certificate and without credentials: only an answer that is Chronos's leads to the fingerprint question, so the + /// certificate of another service on the host is never offered for trust. Nothing is trusted here. + /// + public async Task GetInfoAsync(CancellationToken ct = default) + { + ServerInfo info; + try + { + info = await GetAsync(InfoPath, ProtocolJson.Default.ServerInfo, ct).ConfigureAwait(false); + } + catch (UntrustedCertificateException) when (_ownsHandler) + { + if (await AnswersAsChronosAsync(ct).ConfigureAwait(false) == false) throw new NotChronosServerException(BaseAddress); + throw; + } + catch (ChronosApiException api) when (!api.IsTransient && (int)api.Status < 500 && !IsChronosError(api.Error)) + { + throw new NotChronosServerException(BaseAddress, api); + } + catch (Exception ex) when (ex is JsonException or NotSupportedException) + { + throw new NotChronosServerException(BaseAddress, ex); + } + return IsChronos(info) ? info : throw new NotChronosServerException(BaseAddress); + } + + private const string InfoPath = "api/v1/server/info"; + + /// What every Chronos Server's info holds; JSON of another shape reads as nulls and zeros. + private static bool IsChronos(ServerInfo? info) => + info is { Name.Length: > 0, Version.Length: > 0, ApiVersion: > 0, Capabilities: not null, Formats: not null, Limits: not null }; + + /// An error body Chronos wrote ( codes any other reply http_<status>). + private static bool IsChronosError(ApiError error) => error.Code is { Length: > 0 } code && !code.StartsWith("http_", StringComparison.Ordinal); + + /// + /// The info read without checking the certificate, by a client of its own that holds no token: true when it is + /// Chronos's, false when the address answers as something else, null when it cannot tell (no answer, busy). + /// + private async Task AnswersAsChronosAsync(CancellationToken ct) + { + using var handler = new SocketsHttpHandler + { + SslOptions = { RemoteCertificateValidationCallback = static (_, _, _, _) => true }, + ConnectTimeout = TimeSpan.FromSeconds(10), + AutomaticDecompression = DecompressionMethods.None, + }; + using var http = new HttpClient(handler) { BaseAddress = BaseAddress, Timeout = TimeSpan.FromSeconds(20), MaxResponseContentBufferSize = 1 << 20 }; + http.DefaultRequestHeaders.Add(ApiVersion.Header, ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture)); + try + { + using var response = await http.GetAsync(InfoPath, ct).ConfigureAwait(false); + if (response.IsSuccessStatusCode) return IsChronos(await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ServerInfo, ct).ConfigureAwait(false)); + if ((int)response.StatusCode is < 400 or >= 500 || ChronosApiException.IsTransientStatus(response.StatusCode)) return null; + var error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError, ct).ConfigureAwait(false); + return error is not null && IsChronosError(error); + } + catch (Exception ex) when (ex is JsonException or NotSupportedException) + { + return false; + } + catch (Exception ex) when (ex is HttpRequestException or IOException || (ex is OperationCanceledException && !ct.IsCancellationRequested)) + { + return null; + } + } // ---------------- Auth ---------------- diff --git a/src/Chronos.Server/Admin/web/pages/settings.js b/src/Chronos.Server/Admin/web/pages/settings.js index a13f1019..7c3fe674 100644 --- a/src/Chronos.Server/Admin/web/pages/settings.js +++ b/src/Chronos.Server/Admin/web/pages/settings.js @@ -4,10 +4,14 @@ // Audit log clean-up schedule's age limit (0 while it is off), and saving a new one sets it. Jobs run one at a time // (owner review 1): the parallelism (photos at once) and the priority queue apply at once, as do the log levels, // retention, size limits and rotation (owner review 2, R11). About (version, API, database, uptime) is the last group, -// read-only (owner review 2); #/about opens here on it. +// read-only (owner review 2); #/about opens here on it. Network (owner review 3): the public ports are the host ports +// clients use when they differ from the listening ones (a container publishes 8443 as another port) and apply at once; +// in a container the listening ports are the container's, read-only. Client address is what to type in the Uploader and +// in Chronos: this host as the browser reached it, on the public HTTPS port (the proxy's address in TLS mode proxy). import { t, applyStrings, languages } from "../i18n.js"; import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, PROXY_WARNING } from "../ui.js"; import { kindLabel } from "../jobs.js"; +import { icons } from "../icons.js"; /** Levels of the priority queue, highest first. */ const LEVELS = ["high", "normal", "low"]; @@ -50,6 +54,12 @@ export async function render(root, { api, info, setMeta, actions }) { const choice = (name, value, values, label) => field(name, ``); const level = (name, value) => choice(name, value, LOG_LEVELS, (l) => `Admin.Settings.Level.${cap(l)}`); + // A container's listening port is the template's Target, mapped to a host port: shown, never edited here. + const listening = (name, value) => settings.inContainer + ? field(`container${cap(name)}`, ``) + : number(name, value, 'min="1" max="65535"'); + // Empty: the listening port, which the placeholder shows. + const publicPort = (name, value, port) => number(name, value ?? "", `min="1" max="65535" placeholder="${attr(port)}"`); function draw() { root.innerHTML = ` @@ -75,8 +85,12 @@ export async function render(root, { api, info, setMeta, actions }) {

${settings.proxyWarning ? PROXY_WARNING : ""}
- ${number("httpPort", settings.httpPort, 'min="1" max="65535"')} - ${number("httpsPort", settings.httpsPort, 'min="1" max="65535"')} + ${listening("httpPort", settings.httpPort)} + ${listening("httpsPort", settings.httpsPort)} + ${publicPort("publicHttpPort", settings.publicHttpPort, settings.httpPort)} + ${publicPort("publicHttpsPort", settings.publicHttpsPort, settings.httpsPort)} + ${field("clientAddress", ` + `)} ${field("tlsMode", ``)} ${text("tlsCert", settings.tlsCert, 'dir="ltr" spellcheck="false"')} @@ -109,6 +123,16 @@ export async function render(root, { api, info, setMeta, actions }) { form.addEventListener("submit", save); form.elements.tlsMode.addEventListener("change", () => pemFiles(form)); pemFiles(form); + const address = root.querySelector("#client-address"); + root.querySelector("#copy-address").addEventListener("click", async () => { + try { + await navigator.clipboard.writeText(address.value); + toast(t("Admin.Settings.AddressCopied")); + } catch { + address.focus(); + address.select(); + } + }); // The levels matter only while the priority queue is on. form.elements.priorityQueue.addEventListener("change", () => { root.querySelector(".priorities").hidden = !form.elements.priorityQueue.checked; }); } @@ -140,6 +164,17 @@ export async function render(root, { api, info, setMeta, actions }) { return dashboard ? formatDuration(dashboard.uptimeSeconds + (Date.now() - dashboard.at) / 1000) : "—"; } + /** + * What clients type to reach this server, as saved: the host name the browser used (an IPv6 address in brackets) on + * the public HTTPS port, else the HTTPS port; behind a reverse proxy, the proxy's address this page came through. + */ + function clientAddress() { + if (settings.tlsMode === "proxy") return location.origin; + const host = location.hostname.includes(":") && !location.hostname.startsWith("[") ? `[${location.hostname}]` : location.hostname; + const port = settings.publicHttpsPort ?? settings.httpsPort; + return port === 443 ? `https://${host}` : `https://${host}:${port}`; + } + /** The certificate and key files are used only in Own certificate mode; elsewhere they are off and say so. */ function pemFiles(form) { const pem = form.elements.tlsMode.value === "pem"; @@ -157,6 +192,13 @@ export async function render(root, { api, info, setMeta, actions }) { form.querySelectorAll("[aria-invalid]").forEach(clearInvalid); const data = new FormData(form); const value = (name, fallback) => (form.elements[name]?.disabled ? fallback : data.get(name)); + // Text a number field cannot read is sent as -1, which the server refuses, so it is marked rather than cleared. + const publicValue = (name) => { + const input = form.elements[name]; + if (input.disabled) return settings[name]; + if (input.validity.badInput) return -1; + return input.value.trim() === "" ? 0 : Number(input.value); + }; const request = { ...settings, serverName: String(value("serverName", settings.serverName)).trim(), @@ -167,6 +209,9 @@ export async function render(root, { api, info, setMeta, actions }) { discovery: form.elements.discovery.disabled ? settings.discovery : form.elements.discovery.checked, httpPort: Number(value("httpPort", settings.httpPort)), httpsPort: Number(value("httpsPort", settings.httpsPort)), + // Empty clears a public port (0); a locked one is sent as it is. + publicHttpPort: publicValue("publicHttpPort"), + publicHttpsPort: publicValue("publicHttpsPort"), tlsMode: String(value("tlsMode", settings.tlsMode)), tlsCert: String(value("tlsCert", settings.tlsCert ?? "")).trim() || null, tlsKey: String(value("tlsKey", settings.tlsKey ?? "")).trim() || null, diff --git a/src/Chronos.Server/Configuration/ServerOptions.cs b/src/Chronos.Server/Configuration/ServerOptions.cs index 248bde7d..472e0b9e 100644 --- a/src/Chronos.Server/Configuration/ServerOptions.cs +++ b/src/Chronos.Server/Configuration/ServerOptions.cs @@ -125,13 +125,34 @@ public sealed class ServerOptions /// /// Port clients reach the HTTP listener on, when it differs from (a container port published - /// as another host port); advertised by LAN discovery. Null: . + /// as another host port); advertised by LAN discovery. Null: . Set in the admin panel or by + /// CHRONOS_PUBLIC_HTTP_PORT, which locks it (owner review 3); a saved value applies at once. /// public int? PublicHttpPort { get; set; } - /// Port clients reach the HTTPS listener on (admin redirect, LAN discovery). Null: . + /// + /// Port clients reach the HTTPS listener on (admin redirect, LAN discovery, the client address the admin panel shows). + /// Null: . Set like , by CHRONOS_PUBLIC_HTTPS_PORT. + /// public int? PublicHttpsPort { get; set; } + /// The variable the .NET container images set to true: the server runs in a container. + public const string ContainerVariable = "DOTNET_RUNNING_IN_CONTAINER"; + + /// + /// The server runs in a container (; tests set it directly). Its listening ports are then + /// the container's, which the template publishes as host ports: the admin panel shows them read-only, a value + /// server.json holds for them is ignored (), and only CHRONOS_HTTP_PORT / + /// CHRONOS_HTTPS_PORT change them (owner review 3). The ports clients use are and + /// . + /// + [JsonIgnore] + public bool InContainer { get; set; } + + /// In a container, server.json held listening ports, which were ignored: the start says so. + [JsonIgnore] + public bool IgnoredSavedPorts { get; private set; } + public TlsMode TlsMode { get; set; } = TlsMode.Auto; public string? TlsCert { get; set; } public string? TlsKey { get; set; } @@ -301,6 +322,15 @@ public sealed class ServerOptions } } options.DataPath = dataPath; + options.InContainer = string.Equals(Env(ContainerVariable), "true", StringComparison.OrdinalIgnoreCase); + if (options.InContainer) + { + // The template maps the default container ports; a port saved before owner review 3 would leave them unmapped. + var defaults = new ServerOptions(); + options.IgnoredSavedPorts = options.HttpPort != defaults.HttpPort || options.HttpsPort != defaults.HttpsPort; + options.HttpPort = defaults.HttpPort; + options.HttpsPort = defaults.HttpsPort; + } var locked = new List(); var lockedBy = new Dictionary(StringComparer.Ordinal); diff --git a/src/Chronos.Server/Configuration/ServerSettingsStore.cs b/src/Chronos.Server/Configuration/ServerSettingsStore.cs index af8161b4..94c563ad 100644 --- a/src/Chronos.Server/Configuration/ServerSettingsStore.cs +++ b/src/Chronos.Server/Configuration/ServerSettingsStore.cs @@ -14,7 +14,8 @@ namespace Chronos.Server.Configuration; /// The admin panel's view of the configuration (BRIEF §14.8 Settings). Saving writes /data/server.json (only the /// edited keys; secrets and environment values are never written) and applies what can change while running, the /// parallelism and the priority queue included (owner review 1), and the log settings through -/// (owner review 2, R11); ports, TLS and chunk size wait for a restart. Job history is what the housekeeping system +/// (owner review 2, R11), and the public ports clients use (owner review 3); the listening ports, TLS and chunk size wait for +/// a restart. In a container the listening ports are locked: the template maps them. Job history is what the housekeeping system /// schedule is reset to (owner review 2, R10): the schedule's own value applies. The audit retention kept here is what the /// audit clean-up schedule is reset to; the endpoint shows that schedule's age limit in its place and puts a new one there /// (SchedulerHost.AuditRetentionAsync, SchedulerHost.ApplyAuditRetentionAsync). @@ -43,14 +44,22 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log /// Validates and saves; returns the error code and the offending setting, or null on success. public (string Code, string Setting)? Save(ServerSettingsDto request) { - // A panel without the log group keeps the log settings as they are. - if (request.Logs is null) request = request with { Logs = Current().Logs }; - if (Validate(request) is { } invalid) return ("invalid_setting", invalid); + var before = Current(); + // A panel without the log group keeps the log settings as they are, and a client without the public ports keeps + // them too (owner review 3: null keeps a public port, 0 clears it). + request = request with + { + Logs = request.Logs ?? before.Logs, + PublicHttpPort = Public(request.PublicHttpPort, before.PublicHttpPort), + PublicHttpsPort = Public(request.PublicHttpsPort, before.PublicHttpsPort), + }; + if (Validate(request, before) is { } invalid) return ("invalid_setting", invalid); lock (_gate) { var current = _saved ?? Snapshot(options, restartRequired: false); var changes = Changes(current, request); - if (changes.FirstOrDefault(c => options.Locked.Contains(c.Name)) is { Name: { } locked }) return ("setting_locked", locked); + var fixedSettings = LockedSettings(options); + if (changes.FirstOrDefault(c => fixedSettings.Contains(c.Name)) is { Name: { } locked }) return ("setting_locked", locked); if (changes.Count == 0) return null; var file = File.Exists(options.SettingsFile) ? JsonNode.Parse(File.ReadAllText(options.SettingsFile)) as JsonObject ?? [] : []; @@ -79,6 +88,9 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log options.LogRotation = Rotation(logs.Rotation); options.AuditRetentionDays = logs.AuditRetentionDays; options.DiagnosticsLogMb = logs.DiagnosticsLogMb; + // Read by LAN discovery and the admin redirect at every use: they apply at once. + options.PublicHttpPort = request.PublicHttpPort; + options.PublicHttpsPort = request.PublicHttpsPort; logging.Apply(options); var restart = request.HttpPort != options.HttpPort || request.HttpsPort != options.HttpsPort || !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase) @@ -89,10 +101,11 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log ServerName = request.ServerName.Trim(), JobPriorities = Priorities(PriorityQueue(options)), Logs = Logs(options), - Locked = [.. options.Locked], + Locked = fixedSettings, LockedBy = LockedBy(options), RestartRequired = restart, ProxyWarning = false, + InContainer = options.InContainer, }; return null; } @@ -101,11 +114,31 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new( o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Parallelism, o.PriorityQueue, Priorities(PriorityQueue(o)), o.Discovery, o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours, - Logs(o), [.. o.Locked], LockedBy(o), restartRequired, ProxyWarning: false); + Logs(o), LockedSettings(o), LockedBy(o), restartRequired, ProxyWarning: false, o.PublicHttpPort, o.PublicHttpsPort, o.InContainer); - /// The variable that fixes every locked setting (for one a test locks directly, the variable that would). - private static Dictionary LockedBy(ServerOptions o) => o.Locked.Distinct(StringComparer.Ordinal).ToDictionary(s => s, - s => o.LockedBy.TryGetValue(s, out var variable) ? variable : ServerOptions.VariableOf(s) ?? s, StringComparer.Ordinal); + /// The listening ports, which a container's template maps (owner review 3). + private static readonly string[] ContainerPorts = [nameof(ServerOptions.HttpPort), nameof(ServerOptions.HttpsPort)]; + + /// Settings the panel cannot change: those environment variables fix and, in a container, its listening ports. + private static List LockedSettings(ServerOptions o) => + [.. o.Locked.Concat(o.InContainer ? ContainerPorts : []).Distinct(StringComparer.Ordinal)]; + + /// + /// The variable that fixes every locked setting (for one a test locks directly, the variable that would); a container's + /// port that no variable of its own sets is fixed by . + /// + private static Dictionary LockedBy(ServerOptions o) => LockedSettings(o).ToDictionary(s => s, + s => o.LockedBy.TryGetValue(s, out var variable) ? variable + : o.InContainer && ContainerPorts.Contains(s) ? ServerOptions.ContainerVariable + : ServerOptions.VariableOf(s) ?? s, StringComparer.Ordinal); + + /// A public port as a request sets it: null keeps , 0 clears it (the listening port applies). + private static int? Public(int? requested, int? current) => requested switch + { + null => current, + 0 => null, + _ => requested, + }; private static LogSettingsDto Logs(ServerOptions o) => new(ServerLogging.Wire(o.LogLevel), ServerLogging.Wire(o.ConsoleLogLevel), o.LogRetentionDays, o.LogMaxFileMb, o.LogMaxTotalMb, ServerLogging.Wire(o.LogRotation), o.AuditRetentionDays, o.DiagnosticsLogMb); @@ -131,11 +164,18 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log return levels; } - private static string? Validate(ServerSettingsDto r) + /// + /// The first setting of out of range, or null. Listening ports are checked only when they change, + /// so a value the panel cannot change (a container's, the test server's 0) never blocks saving the others. + /// + private static string? Validate(ServerSettingsDto r, ServerSettingsDto current) { if (string.IsNullOrWhiteSpace(r.ServerName) || r.ServerName.Trim().Length > 60) return nameof(ServerOptions.ServerName); - if (r.HttpPort is < 1 or > 65535) return nameof(ServerOptions.HttpPort); - if (r.HttpsPort is < 1 or > 65535 || r.HttpsPort == r.HttpPort) return nameof(ServerOptions.HttpsPort); + var portsChanged = r.HttpPort != current.HttpPort || r.HttpsPort != current.HttpsPort; + if (portsChanged && r.HttpPort is < 1 or > 65535) return nameof(ServerOptions.HttpPort); + if (portsChanged && (r.HttpsPort is < 1 or > 65535 || r.HttpsPort == r.HttpPort)) return nameof(ServerOptions.HttpsPort); + if (r.PublicHttpPort is < 1 or > 65535) return nameof(ServerOptions.PublicHttpPort); + if (r.PublicHttpsPort is < 1 or > 65535) return nameof(ServerOptions.PublicHttpsPort); if (!Enum.TryParse(r.TlsMode, ignoreCase: true, out var tls) || !Enum.IsDefined(tls)) return nameof(ServerOptions.TlsMode); if (tls == TlsMode.Pem && (string.IsNullOrWhiteSpace(r.TlsCert) || !File.Exists(r.TlsCert))) return nameof(ServerOptions.TlsCert); if (tls == TlsMode.Pem && (string.IsNullOrWhiteSpace(r.TlsKey) || !File.Exists(r.TlsKey))) return nameof(ServerOptions.TlsKey); @@ -166,6 +206,9 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log Add(nameof(ServerOptions.ServerName), a.ServerName, b.ServerName.Trim(), v => JsonValue.Create(v)); Add(nameof(ServerOptions.HttpPort), a.HttpPort, b.HttpPort, v => JsonValue.Create(v)); Add(nameof(ServerOptions.HttpsPort), a.HttpsPort, b.HttpsPort, v => JsonValue.Create(v)); + // A cleared public port is stored as null, so server.json no longer sets it. + Add(nameof(ServerOptions.PublicHttpPort), a.PublicHttpPort, b.PublicHttpPort, v => v is { } port ? JsonValue.Create(port) : null); + Add(nameof(ServerOptions.PublicHttpsPort), a.PublicHttpsPort, b.PublicHttpsPort, v => v is { } port ? JsonValue.Create(port) : null); Add(nameof(ServerOptions.TlsMode), a.TlsMode.ToLowerInvariant(), b.TlsMode.ToLowerInvariant(), v => JsonValue.Create(v)); Add(nameof(ServerOptions.TlsCert), a.TlsCert, b.TlsCert, v => v is null ? null : JsonValue.Create(v)); Add(nameof(ServerOptions.TlsKey), a.TlsKey, b.TlsKey, v => v is null ? null : JsonValue.Create(v)); diff --git a/src/Chronos.Server/Hosting/ServerHost.cs b/src/Chronos.Server/Hosting/ServerHost.cs index 85999f64..c5727ea2 100644 --- a/src/Chronos.Server/Hosting/ServerHost.cs +++ b/src/Chronos.Server/Hosting/ServerHost.cs @@ -94,6 +94,12 @@ public static class ServerHost app.Logger.LogWarning("CHRONOS_WORKERS is the former name of CHRONOS_PARALLELISM: jobs now run one at a time, and the value is how many " + "photos the running job processes at once. Rename the variable."); } + if (options.IgnoredSavedPorts) + { + app.Logger.LogWarning("server.json sets HttpPort or HttpsPort, which a container ignores: it listens on {Http} and {Https}, the ports the " + + "template maps. Set CHRONOS_HTTP_PORT or CHRONOS_HTTPS_PORT to change them, and the public ports to the host ports clients use.", + options.HttpPort, options.HttpsPort); + } app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Chronos Server stopping")); app.Lifetime.ApplicationStopped.Register(() => database.DisposeAsync().AsTask().GetAwaiter().GetResult()); return app; diff --git a/src/Chronos.Uploader/Server/ServerAddress.cs b/src/Chronos.Uploader/Server/ServerAddress.cs index 0ddeb787..26a2a00c 100644 --- a/src/Chronos.Uploader/Server/ServerAddress.cs +++ b/src/Chronos.Uploader/Server/ServerAddress.cs @@ -1,21 +1,13 @@ +using Chronos.Protocol.Client; + namespace Chronos.Uploader.Server; /// Server addresses as typed in the sign-in form. public static class ServerAddress { /// - /// Accepts "nas.local:8443" (https assumed) or a full http(s) URL; the result is the API base, ending with "/". + /// Accepts "nas.local" (https on port 8443 assumed), "nas.local:9443" or a full http(s) URL, which keeps its scheme's + /// port; the result is the API base, ending with "/" (, shared with the desktop client). /// - public static bool TryParse(string? text, out Uri uri) - { - uri = null!; - if (string.IsNullOrWhiteSpace(text)) return false; - var trimmed = text.Trim(); - if (!trimmed.Contains("://", StringComparison.Ordinal)) trimmed = "https://" + trimmed; - if (!Uri.TryCreate(trimmed, UriKind.Absolute, out var parsed) || parsed.Scheme is not ("https" or "http") || parsed.Host.Length == 0) return false; - var builder = new UriBuilder(parsed) { Query = string.Empty, Fragment = string.Empty }; - if (!builder.Path.EndsWith('/')) builder.Path += "/"; - uri = builder.Uri; - return true; - } + public static bool TryParse(string? text, out Uri uri) => ChronosAddress.TryParse(text, out uri); } diff --git a/src/Chronos.Uploader/Server/ServerSession.cs b/src/Chronos.Uploader/Server/ServerSession.cs index c01f5909..2e95925d 100644 --- a/src/Chronos.Uploader/Server/ServerSession.cs +++ b/src/Chronos.Uploader/Server/ServerSession.cs @@ -439,6 +439,7 @@ public sealed class ServerSession : IServerSession, IUploadTransport, IDisposabl private static SignInResult Classify(Exception ex, CancellationToken ct) => ex switch { UntrustedCertificateException => SignInResult.Untrusted, + NotChronosServerException => SignInResult.NotChronos, ChronosApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => SignInResult.BadCredentials, ChronosApiException { Status: HttpStatusCode.NotFound } => SignInResult.NotChronos, ChronosApiException api when api.IsTransient => SignInResult.Unreachable, diff --git a/src/Chronos.Uploader/Shell/ConnectViewModel.cs b/src/Chronos.Uploader/Shell/ConnectViewModel.cs index 8f28a9a0..ab0ee016 100644 --- a/src/Chronos.Uploader/Shell/ConnectViewModel.cs +++ b/src/Chronos.Uploader/Shell/ConnectViewModel.cs @@ -173,7 +173,8 @@ public sealed class ConnectViewModel : ObservableObject, INotifyDataErrorInfo AddressError = result switch { SignInResult.InvalidAddress => Loc.L("Uploader.Connect.Error.InvalidAddress"), - SignInResult.NotChronos => Loc.L("Uploader.Connect.Error.NotChronos"), + // The address as it was asked, port included: "192.168.1.20" went to port 8443 (owner review 3). + SignInResult.NotChronos => Loc.L("Uploader.Connect.Error.NotChronosAt", "‪" + (ServerAddress.TryParse(Address, out var asked) ? Display(asked.ToString()) : Address.Trim()) + "‬"), _ => null, }; PasswordError = result == SignInResult.BadCredentials ? Loc.L("Uploader.Connect.Error.BadCredentials") : null; diff --git a/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs b/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs index 630b328b..1e492f39 100644 --- a/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs +++ b/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs @@ -80,6 +80,7 @@ public sealed class ConnectFlowTests [Case("ftp://nas.local", ConnectError.InvalidAddress)] [Case("down.local", ConnectError.Unreachable)] [Case("web.local", ConnectError.NotChronos)] + [Case("other.local", ConnectError.NotChronos)] public async Task ProbeFailuresAreClassified(string address, ConnectError error) { using var flow = new ConnectFlow(new FakeServer(), new MemoryTrust()); @@ -141,9 +142,32 @@ public sealed class ConnectFlowTests Assert.Equal(1, changes); } + [Test] + public async Task AnotherServiceOnThePortIsNamedWithTheAddressAsked() + { + // Owner review 3: "192.168.30.23" goes to port 8443, where the owner's NAS runs another service. + var server = new FakeServer { SelfSigned = true }; + var trust = new MemoryTrust(); + using var flow = new ConnectFlow(server, trust); + Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("other.local")); + Assert.Equal(ConnectError.NotChronos, flow.Error); + Assert.Null(flow.PendingFingerprint); + Assert.Empty(trust.Fingerprints); + Assert.Equal(Chronos.Core.Localization.Loc.L("Server.Error.NotChronosAt", Chronos.App.Infrastructure.Formatting.LeftToRight("https://other.local:8443")), + ServerSession.ErrorText(flow.Error, flow.Address)); + Assert.Contains("https://other.local:8443", ServerSession.ErrorText(flow.Error, flow.Address)); + // Without the address, and for other errors, the sentence stays as it was. + Assert.Equal(Chronos.Core.Localization.Loc.L("Server.Error.NotChronos"), ServerSession.ErrorText(ConnectError.NotChronos)); + Assert.Equal(Chronos.Core.Localization.Loc.L("Server.Error.Unreachable"), ServerSession.ErrorText(ConnectError.Unreachable, flow.Address)); + } + [Test] public void AddressesAreNormalised() { + Assert.True(ServerAddress.TryParse("nas.local", out var bare)); + Assert.Equal("https://nas.local:8443/", bare.ToString()); + Assert.True(ServerAddress.TryParse("https://chronos.example.com", out var proxied)); + Assert.Equal("https://chronos.example.com/", proxied.ToString()); Assert.True(ServerAddress.TryParse("nas.local:8443", out var a)); Assert.Equal("https://nas.local:8443/", a.ToString()); Assert.True(ServerAddress.TryParse(" http://10.0.0.5:8080/chronos?x=1 ", out var b)); @@ -228,6 +252,8 @@ public sealed class ConnectFlowTests { if (BaseAddress.Host == "down.local") throw new HttpRequestException("No such host"); if (BaseAddress.Host == "web.local") throw new ChronosApiException(HttpStatusCode.NotFound, new ApiError("http_404", "Not Found")); + // What ChronosClient reports for another service on the port: its page, its sign-in redirect, its certificate. + if (BaseAddress.Host == "other.local") throw new NotChronosServerException(BaseAddress); if (server.SelfSigned && !trusted.Contains(Fingerprint)) throw new UntrustedCertificateException(Fingerprint); } diff --git a/tests/Chronos.App.Tests/Uploader/ConnectViewModelTests.cs b/tests/Chronos.App.Tests/Uploader/ConnectViewModelTests.cs index 2e8e8445..f011edd5 100644 --- a/tests/Chronos.App.Tests/Uploader/ConnectViewModelTests.cs +++ b/tests/Chronos.App.Tests/Uploader/ConnectViewModelTests.cs @@ -56,10 +56,13 @@ public sealed class ConnectViewModelTests public void AServerThatIsNotChronosMarksTheServerField() { var form = Form(new FakeSession(SignInResult.NotChronos)); + // Owner review 3: the address as it was asked, port included, so the user sees which port answered. + form.Address = "192.168.30.23"; form.SignInCommand.Execute(null); - Assert.Equal(Loc.L("Uploader.Connect.Error.NotChronos"), form.AddressError); + Assert.Equal(Loc.L("Uploader.Connect.Error.NotChronosAt", "‪https://192.168.30.23:8443‬"), form.AddressError); + Assert.Contains("https://192.168.30.23:8443", form.AddressToolTip); Assert.Null(form.ErrorText); } diff --git a/tests/Chronos.App.Tests/Uploader/ServerAddressTests.cs b/tests/Chronos.App.Tests/Uploader/ServerAddressTests.cs index e96b3eb4..d9135eda 100644 --- a/tests/Chronos.App.Tests/Uploader/ServerAddressTests.cs +++ b/tests/Chronos.App.Tests/Uploader/ServerAddressTests.cs @@ -10,6 +10,18 @@ public sealed class ServerAddressTests [Case("https://nas.local:8443", "https://nas.local:8443/")] [Case(" http://192.168.1.20:8080/chronos ", "http://192.168.1.20:8080/chronos/")] [Case("https://nas.local/?x=1#y", "https://nas.local/")] + // Owner review 3: no scheme and no port is Chronos's HTTPS port, as the placeholder shows. + [Case("192.168.30.23", "https://192.168.30.23:8443/")] + [Case("nas.local", "https://nas.local:8443/")] + [Case("nas.local/chronos", "https://nas.local:8443/chronos/")] + [Case("192.168.30.23:8444", "https://192.168.30.23:8444/")] + [Case("nas.local:443", "https://nas.local/")] + [Case("https://chronos.example.com", "https://chronos.example.com/")] + [Case("http://nas.local", "http://nas.local/")] + [Case("fd00::5", "https://[fd00::5]:8443/")] + [Case("[fd00::5]", "https://[fd00::5]:8443/")] + [Case("[fd00::5]:9443", "https://[fd00::5]:9443/")] + [Case("https://[fd00::5]", "https://[fd00::5]/")] public void ServerAddressesBecomeApiBases(string typed, string expected) { Assert.True(ServerAddress.TryParse(typed, out var uri)); diff --git a/tests/Chronos.Server.Tests/Api/ServerIdentityTests.cs b/tests/Chronos.Server.Tests/Api/ServerIdentityTests.cs new file mode 100644 index 00000000..83587436 --- /dev/null +++ b/tests/Chronos.Server.Tests/Api/ServerIdentityTests.cs @@ -0,0 +1,124 @@ +using System.Net; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Chronos.Protocol; +using Chronos.Protocol.Client; +using Chronos.Testing; + +namespace Chronos.Server.Tests.Api; + +/// +/// What a client makes of the address it was given (owner review 3): the owner's NAS answers on 8443 with another service, +/// which redirects to its sign-in page behind a self-signed certificate of its own. +/// +[Category("server")] +public sealed class ServerIdentityTests(TestContext context) +{ + [Test] + public async Task AnAddressThatAnswersAsSomethingElseIsNotAChronosServer() + { + await using var other = await OtherService.StartAsync(context); + foreach (var path in new[] { "html/", "redirect/", "empty/", "json/", "unauthorized/", "missing/" }) + { + var address = new Uri(other.Http, path); + using var client = new ChronosClient(address, new CertificatePinning([]), "tests"); + var error = await Assert.ThrowsAsync(() => client.GetInfoAsync(context.Cancellation)); + Assert.Equal(address, error.Address, path); + } + } + + [Test] + public async Task TheCertificateOfAnotherServiceIsNeverOfferedForTrust() + { + await using var other = await OtherService.StartAsync(context); + var pinning = new CertificatePinning([]); + using var client = new ChronosClient(new Uri(other.Https, "redirect/"), pinning, "tests"); + await Assert.ThrowsAsync(() => client.GetInfoAsync(context.Cancellation)); + // Nothing was trusted, and the next request still refuses the certificate. + await Assert.ThrowsAsync(() => client.MeAsync(context.Cancellation)); + Assert.Equal(0, other.Authorized, "no request carried credentials"); + } + + [Test] + public async Task AChronosServerBehindAnUnknownCertificateStillAsksForTrust() + { + await using var server = await TestServer.StartAsync(context, o => o.ServerName = "Studio NAS"); + var https = Assert.NotNull(server.HttpsBase); + using var unknown = new ChronosClient(https, new CertificatePinning([]), "tests"); + var untrusted = await Assert.ThrowsAsync(() => unknown.GetInfoAsync(context.Cancellation)); + using var info = await server.Client.GetAsync("/api/v1/server/info"); + Assert.Equal((await info.ReadAsync(ProtocolJson.Default.ServerInfo)).TlsFingerprint, untrusted.Fingerprint); + + using var trusted = new ChronosClient(https, new CertificatePinning([untrusted.Fingerprint]), "tests"); + Assert.Equal("Studio NAS", (await trusted.GetInfoAsync(context.Cancellation)).Name); + // Plain HTTP to the same server is Chronos too. + using var plain = new ChronosClient(server.HttpBase, new CertificatePinning([]), "tests"); + Assert.Equal("Studio NAS", (await plain.GetInfoAsync(context.Cancellation)).Name); + } + + /// A web service that is not Chronos, on HTTP and on HTTPS with a self-signed certificate of its own. + private sealed class OtherService : IAsyncDisposable + { + private readonly WebApplication _app; + private int _authorized; + + private OtherService(WebApplication app) + { + _app = app; + var addresses = app.Services.GetRequiredService().Features.Get()!.Addresses.Select(a => new Uri(a)).ToList(); + Http = new Uri(addresses.First(a => a.Scheme == "http"), "/"); + Https = new Uri(addresses.First(a => a.Scheme == "https"), "/"); + } + + public Uri Http { get; } + public Uri Https { get; } + + /// Requests that carried an Authorization header. + public int Authorized => Volatile.Read(ref _authorized); + + public static async Task StartAsync(TestContext context) + { + using var key = RSA.Create(2048); + var request = new CertificateRequest("CN=other-service", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + using var created = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + var certificate = X509CertificateLoader.LoadPkcs12(created.Export(X509ContentType.Pfx), null); + + var builder = WebApplication.CreateSlimBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.ConfigureKestrel(k => + { + k.Listen(IPAddress.Loopback, 0); + k.Listen(IPAddress.Loopback, 0, l => l.UseHttps(certificate)); + }); + var app = builder.Build(); + OtherService? service = null; + app.Use(async (http, next) => + { + if (http.Request.Headers.Authorization.Count > 0 && service is not null) Interlocked.Increment(ref service._authorized); + await next(http); + }); + app.MapGet("/html/api/v1/server/info", () => Results.Content("NAS", "text/html")); + app.MapGet("/redirect/api/v1/server/info", () => Results.Redirect("/login")); + app.MapGet("/login", () => Results.Content("
Sign in
", "text/html")); + app.MapGet("/empty/api/v1/server/info", () => Results.Content("{}", "application/json")); + app.MapGet("/json/api/v1/server/info", () => Results.Content("""{"status":"ok","name":"router"}""", "application/json")); + app.MapGet("/unauthorized/api/v1/server/info", () => Results.StatusCode(StatusCodes.Status401Unauthorized)); + await app.StartAsync(context.Cancellation); + service = new OtherService(app); + return service; + } + + public async ValueTask DisposeAsync() + { + await _app.StopAsync(); + await _app.DisposeAsync(); + } + } +} diff --git a/tests/Chronos.Server.Tests/Hosting/PublicPortTests.cs b/tests/Chronos.Server.Tests/Hosting/PublicPortTests.cs new file mode 100644 index 00000000..cd79dc62 --- /dev/null +++ b/tests/Chronos.Server.Tests/Hosting/PublicPortTests.cs @@ -0,0 +1,237 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Chronos.Protocol; +using Chronos.Server.Configuration; +using Chronos.Server.Hosting; +using Chronos.Testing; + +namespace Chronos.Server.Tests.Hosting; + +/// +/// The ports clients use and the ports the server listens on (owner review 3): a container publishes 8080 and 8443 as +/// other host ports, and only the public ports tell clients, LAN discovery and the HTTPS redirect which ones. +/// +[Category("server")] +public sealed class PublicPortTests(TestContext context) +{ + [Test] + public async Task PublicPortsAreSavedAndApplyWithoutARestart() + { + await using var server = await TestServer.StartAsync(context); + var admin = await server.AdminAsync(); + var settings = await SettingsAsync(admin); + Assert.Equal(((int?)null, (int?)null, false), (settings.PublicHttpPort, settings.PublicHttpsPort, settings.InContainer)); + + // The test server listens on ports the system chose (0), which no request may set. + var edited = settings with { HttpPort = 18080, HttpsPort = 18443, PublicHttpPort = 8087, PublicHttpsPort = 8444 }; + using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited, ProtocolJson.Default.ServerSettingsDto)) + { + var answer = await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto); + Assert.Equal(((int?)8087, (int?)8444), (answer.PublicHttpPort, answer.PublicHttpsPort)); + } + Assert.Equal(((int?)8087, (int?)8444), (server.Options.PublicHttpPort, server.Options.PublicHttpsPort)); + + // At once: the beacon and the redirect to HTTPS name the host ports. + var beacon = server.Services.GetRequiredService().CreateBeacon(); + Assert.Equal((8087, 8444), (beacon.HttpPort, beacon.HttpsPort)); + var kestrel = server.Services.GetRequiredService(); + Assert.Equal("https://192.168.30.23:8444/admin/", AdminPanel.HttpsLocation(AdminRequest(), server.Options, kestrel)); + + // Stored for the next start. + var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject(); + Assert.Equal((8087, 8444), (file["PublicHttpPort"]!.GetValue(), file["PublicHttpsPort"]!.GetValue())); + var restarted = ServerOptions.Load(new Dictionary { ["CHRONOS_DATA_PATH"] = server.Options.DataPath, ["CHRONOS_DB"] = "postgres" }); + Assert.Equal(((int?)8087, (int?)8444), (restarted.PublicHttpPort, restarted.PublicHttpsPort)); + + // A client of the shape before them sends no public ports: they stay as they are. + var older = JsonSerializer.SerializeToNode(edited with { ServerName = "Older client" }, ProtocolJson.Default.ServerSettingsDto)!.AsObject(); + Assert.True(older.Remove("publicHttpPort") && older.Remove("publicHttpsPort") && older.Remove("inContainer")); + using (var content = new StringContent(older.ToJsonString(), Encoding.UTF8, "application/json")) + using (var saved = await admin.PutAsync("/api/v1/server/settings", content)) + Assert.Equal(((int?)8087, (int?)8444), ((await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).PublicHttpPort, server.Options.PublicHttpsPort)); + Assert.Equal("Older client", server.Options.ServerName); + + // 0 clears one: the listening port applies again, at once. + using (var cleared = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { PublicHttpsPort = 0 }, ProtocolJson.Default.ServerSettingsDto)) + Assert.Null((await cleared.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).PublicHttpsPort); + Assert.Null(server.Options.PublicHttpsPort); + var listening = Assert.NotNull(server.HttpsBase).Port; + Assert.Equal(listening, server.Services.GetRequiredService().CreateBeacon().HttpsPort); + Assert.Equal($"https://192.168.30.23:{listening}/admin/", AdminPanel.HttpsLocation(AdminRequest(), server.Options, kestrel)); + file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject(); + Assert.True(file.ContainsKey("PublicHttpsPort") && file["PublicHttpsPort"] is null, "a cleared port no longer sets it"); + Assert.Null(ServerOptions.Load(new Dictionary { ["CHRONOS_DATA_PATH"] = server.Options.DataPath, ["CHRONOS_DB"] = "postgres" }).PublicHttpsPort); + + foreach (var (invalid, setting) in new (ServerSettingsDto, string)[] + { + (edited with { PublicHttpPort = 70000 }, "PublicHttpPort"), + (edited with { PublicHttpsPort = -1 }, "PublicHttpsPort"), + }) + { + using var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", invalid, ProtocolJson.Default.ServerSettingsDto); + Assert.Equal(setting, (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_setting")).Details); + } + Assert.Equal((int?)8087, server.Options.PublicHttpPort); + } + + [Test] + public async Task AVariableLocksItsPublicPort() + { + await using var server = await TestServer.StartAsync(context, o => + { + o.PublicHttpsPort = 8444; + o.Locked = [nameof(ServerOptions.PublicHttpsPort)]; + o.LockedBy = new Dictionary { [nameof(ServerOptions.PublicHttpsPort)] = "CHRONOS_PUBLIC_HTTPS_PORT" }; + }); + var admin = await server.AdminAsync(); + var settings = await SettingsAsync(admin); + Assert.Equal(((int?)8444, "CHRONOS_PUBLIC_HTTPS_PORT"), (settings.PublicHttpsPort, settings.LockedBy["PublicHttpsPort"])); + + var edited = settings with { HttpPort = 18080, HttpsPort = 18443 }; + using (var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { PublicHttpsPort = 9444 }, ProtocolJson.Default.ServerSettingsDto)) + Assert.Equal("PublicHttpsPort", (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details); + using (var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { PublicHttpsPort = 0 }, ProtocolJson.Default.ServerSettingsDto)) + Assert.Equal("PublicHttpsPort", (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details); + // The other public port, and a request that leaves the locked one as it is, still save. + using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { PublicHttpPort = 8087 }, ProtocolJson.Default.ServerSettingsDto)) + await saved.ExpectAsync(HttpStatusCode.OK); + Assert.Equal(((int?)8087, (int?)8444), (server.Options.PublicHttpPort, server.Options.PublicHttpsPort)); + + // The variables lock their settings at start, with an empty one taken as unset. + var root = context.CreateTempDirectory("public-locked"); + var loaded = ServerOptions.Load(new Dictionary + { + ["CHRONOS_DATA_PATH"] = root, + ["CHRONOS_DB"] = "postgres", + ["CHRONOS_PUBLIC_HTTPS_PORT"] = "8444", + ["CHRONOS_PUBLIC_HTTP_PORT"] = "", + }); + Assert.SequenceEqual(["Database", "PublicHttpsPort"], loaded.Locked); + Assert.Equal("CHRONOS_PUBLIC_HTTPS_PORT", loaded.LockedBy["PublicHttpsPort"]); + } + + [Test] + public async Task InAContainerTheListeningPortsAreTheTemplates() + { + await using var server = await TestServer.StartAsync(context, o => o.InContainer = true); + var admin = await server.AdminAsync(); + var settings = await SettingsAsync(admin); + Assert.True(settings.InContainer); + Assert.Contains("HttpPort", settings.Locked); + Assert.Contains("HttpsPort", settings.Locked); + Assert.Equal(("DOTNET_RUNNING_IN_CONTAINER", "DOTNET_RUNNING_IN_CONTAINER"), (settings.LockedBy["HttpPort"], settings.LockedBy["HttpsPort"])); + + using (var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", settings with { HttpPort = 8087, HttpsPort = 8444 }, ProtocolJson.Default.ServerSettingsDto)) + Assert.Equal("HttpPort", (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details); + // The ports stay as they are, which is valid whatever they are; the host ports go in the public ones. + using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", settings with { PublicHttpPort = 8087, PublicHttpsPort = 8444 }, + ProtocolJson.Default.ServerSettingsDto)) + Assert.False((await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).RestartRequired); + Assert.Equal((8087, 8444), (server.Options.PublicHttpPort!.Value, server.Options.PublicHttpsPort!.Value)); + var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject(); + Assert.False(file.ContainsKey("HttpPort") || file.ContainsKey("HttpsPort"), "the container's ports are never written"); + } + + [Test] + public void AContainerIgnoresListeningPortsSavedEarlier() + { + var root = context.CreateTempDirectory("container"); + File.WriteAllText(Path.Combine(root, "server.json"), """{ "HttpPort": 8087, "HttpsPort": 8444, "PublicHttpsPort": 8444 }"""); + Dictionary Env(params (string Name, string Value)[] more) + { + var env = new Dictionary { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" }; + foreach (var (name, value) in more) env[name] = value; + return env; + } + + // Outside a container the saved ports apply, as before. + var host = ServerOptions.Load(Env()); + Assert.Equal((8087, 8444, false, false), (host.HttpPort, host.HttpsPort, host.InContainer, host.IgnoredSavedPorts)); + + var container = ServerOptions.Load(Env((ServerOptions.ContainerVariable, "true"))); + Assert.Equal((8080, 8443, true, true), (container.HttpPort, container.HttpsPort, container.InContainer, container.IgnoredSavedPorts)); + Assert.Equal((int?)8444, container.PublicHttpsPort); + + // A variable still sets a container's port. + var variable = ServerOptions.Load(Env((ServerOptions.ContainerVariable, "true"), ("CHRONOS_HTTPS_PORT", "9443"))); + Assert.Equal((8080, 9443), (variable.HttpPort, variable.HttpsPort)); + Assert.Equal("CHRONOS_HTTPS_PORT", variable.LockedBy["HttpsPort"]); + + Assert.False(ServerOptions.Load(Env((ServerOptions.ContainerVariable, "false"))).InContainer); + } + + [Test] + public async Task ASettingsAnswerStaysReadableInTheShapeBeforePublicPorts() + { + await using var server = await TestServer.StartAsync(context, o => o.PublicHttpsPort = 8444); + var admin = await server.AdminAsync(); + using var read = await admin.GetAsync("/api/v1/server/settings"); + var json = await read.Content.ReadAsStringAsync(); + var older = Assert.NotNull(JsonSerializer.Deserialize(json, new JsonSerializerOptions(JsonSerializerDefaults.Web))); + var current = Assert.NotNull(JsonSerializer.Deserialize(json, ProtocolJson.Default.ServerSettingsDto)); + Assert.Equal((current.ServerName, current.HttpsPort, current.Parallelism, current.Logs.FileLevel), (older.ServerName, older.HttpsPort, older.Parallelism, older.Logs.FileLevel)); + Assert.Equal((int?)8444, current.PublicHttpsPort); + + // And the shape before them deserialises into the current one, the new members at their defaults. + var old = JsonSerializer.Serialize(older, new JsonSerializerOptions(JsonSerializerDefaults.Web)); + var parsed = Assert.NotNull(JsonSerializer.Deserialize(old, ProtocolJson.Default.ServerSettingsDto)); + Assert.Equal(((int?)null, (int?)null, false), (parsed.PublicHttpPort, parsed.PublicHttpsPort, parsed.InContainer)); + } + + [Test] + public async Task ThePanelShowsThePublicPortsAndTheClientAddress() + { + await using var server = await TestServer.StartAsync(context); + var page = await server.Client.GetStringAsync("/admin/pages/settings.js"); + foreach (var part in new[] { "publicPort(\"publicHttpPort\"", "publicPort(\"publicHttpsPort\"", "field(\"clientAddress\"", "id=\"copy-address\"", + "Admin.Settings.ContainerPort.Tip", "settings.publicHttpsPort ?? settings.httpsPort", "location.origin", "navigator.clipboard.writeText" }) + Assert.Contains(part, page); + } + + private static async Task SettingsAsync(HttpClient admin) + { + using var read = await admin.GetAsync("/api/v1/server/settings"); + return await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto); + } + + /// Plain HTTP to the panel from another machine, as the owner's browser sends it. + private static DefaultHttpContext AdminRequest() + { + var request = new DefaultHttpContext(); + request.Connection.RemoteIpAddress = IPAddress.Parse("192.168.30.50"); + request.Request.Scheme = "http"; + request.Request.Host = new HostString("192.168.30.23", 8087); + request.Request.Path = "/admin/"; + return request; + } + + /// as it was before owner review 3. + private sealed record SettingsBeforePublicPorts( + string ServerName, + int HttpPort, + int HttpsPort, + string TlsMode, + string? TlsCert, + string? TlsKey, + string Language, + int Parallelism, + bool PriorityQueue, + IReadOnlyList JobPriorities, + bool Discovery, + long MaxUploadBytes, + int ChunkSizeBytes, + int JobHistoryDays, + int TokenLifetimeDays, + int UploadRetentionHours, + LogSettingsDto Logs, + IReadOnlyList Locked, + IReadOnlyDictionary LockedBy, + bool RestartRequired, + bool ProxyWarning); +}