From 0aa2fb81358e5ca48536498031f2bf32d1049b03 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 4 Nov 2026 10:28:08 +0100 Subject: [PATCH] fix(server): client address from the page's port, stricter Chronos identity, Host networking notes Review fixes on top of the public ports change (owner review 3): - Settings > Network and TLS: opened over HTTPS, the client address uses the port the page came through (a container's 8443 published as 8444 with Public HTTPS port still empty showed the wrong 8443), and a "Use " button fills that port in. Saving a Public HTTPS port other than the page's asks first, since the HTTPS redirect follows it at once and a typo would lock the panel's link out. - GetInfoAsync tells Chronos from other services by stricter rules on both the trusted and the untrusted-certificate path: any redirect, any answer that is not JSON, more than 1 MB, or an error without the X-Chronos-Api header is not Chronos. Another service's certificate is no longer offered for trust after a cross-scheme redirect, an error page or a JSON 401/403/404, and a JSON 401 over HTTP no longer reads as a wrong password. - The HTTP port typed without a scheme (TLS to a plain HTTP port) now gives the not-Chronos error instead of "the server did not answer". - The Uploader's certificate question names the address with its port. - A link-local IPv6 address with a zone index is refused instead of losing it. - In a container, the first save of the settings removes HttpPort/HttpsPort from server.json, so the start-up warning stops; the warning says so. - Guide, README, compose and template: with network type Host the mappings do nothing and CHRONOS_HTTP_PORT / CHRONOS_HTTPS_PORT move the listening ports off ones another service uses; the template overview is back to two sentences. - BRIEF, DECISIONS and CHANGELOG updated; en/it strings added. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- deploy/docker/docker-compose.yml | 5 + deploy/releases-repo/README.md | 8 +- deploy/unraid/chronos.xml | 6 +- docs/BRIEF.md | 26 +++-- docs/CHANGELOG.md | 15 ++- docs/DECISIONS.md | 9 +- i18n/en/Admin.resx | 7 ++ i18n/it/Admin.it.resx | 7 ++ src/Chronos.Protocol/Client/ChronosAddress.cs | 12 ++- src/Chronos.Protocol/Client/ChronosClient.cs | 95 +++++++++++++------ .../Admin/web/pages/settings.js | 58 +++++++++-- .../Configuration/ServerOptions.cs | 7 +- .../Configuration/ServerSettingsStore.cs | 11 ++- src/Chronos.Server/Hosting/ServerHost.cs | 3 +- .../Shell/ConnectViewModel.cs | 11 ++- .../Uploader/ServerAddressTests.cs | 4 + .../Api/ServerIdentityTests.cs | 50 +++++++++- .../Hosting/PublicPortTests.cs | 33 ++++++- 19 files changed, 303 insertions(+), 67 deletions(-) diff --git a/README.md b/README.md index b8a784c1..15ad8743 100644 --- a/README.md +++ b/README.md @@ -228,7 +228,8 @@ security problems go privately to the maintainers (`SECURITY.md`), never into a - 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. + type *Host*), where the port mappings do nothing and `CHRONOS_HTTP_PORT` / `CHRONOS_HTTPS_PORT` move the listening + ports off ones another service uses. 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 a9581d72..e2224111 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -17,6 +17,8 @@ services: # 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. + # The server then listens on the host's 8080 and 8443 itself: if another service uses either, set CHRONOS_HTTP_PORT + # or CHRONOS_HTTPS_PORT below to a free port and leave the public ports unset. ports: - "8080:8080" - "8443:8443" @@ -41,6 +43,9 @@ services: # longer change them. # CHRONOS_PUBLIC_HTTP_PORT: "8080" # CHRONOS_PUBLIC_HTTPS_PORT: "8443" + # The ports the server listens on, with network_mode: host only (on a bridge network the mapping above decides). + # CHRONOS_HTTP_PORT: "8080" + # CHRONOS_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 # (a higher job pauses the running one, which resumes afterwards). Set here, they can no longer be changed in the diff --git a/deploy/releases-repo/README.md b/deploy/releases-repo/README.md index 80652089..efd93159 100644 --- a/deploy/releases-repo/README.md +++ b/deploy/releases-repo/README.md @@ -108,6 +108,10 @@ certificate is never offered for trust. 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`. +- With host networking the port mappings do nothing: the server listens on the host's 8080 and 8443 itself, and the + container does not start when another service already uses either. Then add the variable `CHRONOS_HTTP_PORT` or + `CHRONOS_HTTPS_PORT` with a free port (compose: under `environment`; Unraid: *Add another Path, Port, Variable…* › + *Variable*, Key `CHRONOS_HTTPS_PORT`), and leave the public ports empty: clients reach the listening ports directly. - Behind a reverse proxy (`CHRONOS_TLS_MODE=proxy`), only the proxies listed in `CHRONOS_TRUSTED_PROXIES` may set `X-Forwarded-*` headers. By default that is loopback only: other machines on your network reach the HTTP port directly, so they must not choose the address the sign-in limit and the audit log see. List your proxy's own @@ -137,7 +141,9 @@ certificate is never offered for trust. 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`). 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. + server by themselves: type that address. Network type *Host* lets them find it; the server then listens on the + host's own 8080 and 8443, so when another service uses either, add the variable `CHRONOS_HTTP_PORT` or + `CHRONOS_HTTPS_PORT` first (see host networking above). 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 diff --git a/deploy/unraid/chronos.xml b/deploy/unraid/chronos.xml index f571ea1a..fb51ec6f 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. Clients connect to the Client address the admin panel shows (Settings, Network and TLS); LAN discovery reaches them only with network type Host. + 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 needs 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,8 +21,8 @@ A PostgreSQL 16 or 17 container (official "postgres" template) with a database and user for Chronos. - 8080 - 8443 + 8080 + 8443 /mnt/user/Timelapse diff --git a/docs/BRIEF.md b/docs/BRIEF.md index d86bf2bf..bf63fc6c 100644 --- a/docs/BRIEF.md +++ b/docs/BRIEF.md @@ -1501,9 +1501,11 @@ per-sequence sync actions and states; conflict resolution only for settings JSON 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 +address gets its brackets; a link-local one with a zone index is refused. An address that +answers but not as a Chronos Server (any redirect, an answer that is not JSON, an error +without Chronos's `X-Chronos-Api` header and error code, JSON of another shape, more than +1 MB, or plain HTTP on a port reached over HTTPS) 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). @@ -2132,9 +2134,12 @@ Network and TLS (amended 2026-11-04, owner review 3): HTTP port and HTTPS port ( 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 +with Copy: `https://:`, the proxy's address in TLS mode proxy, which is what users type +in Chronos and the Uploader; when the page's HTTPS port is not the saved one, a *Use * +button fills it in as the Public HTTPS port, and saving a Public HTTPS port other than the +page's asks first, as the redirect follows it at once; 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 @@ -2287,8 +2292,9 @@ conversion the tighter of the two, §14.3: amended 2026-10-26, R7), `CHRONOS_DB_NAME`, `CHRONOS_DB_USER`, `CHRONOS_DB_PASSWORD`, `CHRONOS_DB_SSLMODE=prefer`, `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 +variables change them, which network type Host needs when another service uses 8080 or +8443; the admin panel shows them read-only and a `server.json` value is ignored with a +warning and removed at the next save), `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; @@ -2562,7 +2568,9 @@ the default), so the admin panel's Settings › Logs chooses them; a value given template locks its setting; TZ also sets the time zone of the schedules; amended 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 +enter the same host port there when it changes and that network type Host ignores the mapping (the +server then listens on 8080 and 8443 itself; the user guide says to add `CHRONOS_HTTP_PORT` / +`CHRONOS_HTTPS_PORT` when another service uses either); 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 diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index c5f95bee..8f2a7567 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -10,7 +10,10 @@ commits follow Conventional Commits (release notes are generated from them by `C (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. + a *Client address* with Copy: exactly what to type in Chronos and in the Uploader. Opened over HTTPS, the client + address uses the port the page came through, and when the saved one differs a *Use …* button fills it in as the + Public HTTPS port. Saving a Public HTTPS port other than that one asks first, since the panel's link follows it at + once. - 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. @@ -18,13 +21,16 @@ commits follow Conventional Commits (release notes are generated from them by `C 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. + that certificate is now never offered (redirects of any kind, error pages, JSON errors without Chronos's header and + oversized answers included). The HTTP port typed without a scheme (`192.168.1.20:8087`) gives the same message + instead of *The server did not answer*. The Uploader's certificate question names the address with its port. +- A link-local IPv6 address with a zone (`fe80::1%12`) is refused as an invalid address instead of losing its zone. ### 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. + in `server.json` is ignored, with a warning in the log, and removed at the next save of the settings. - 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 @@ -35,6 +41,9 @@ commits follow Conventional Commits (release notes are generated from them by `C 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`). +- Network type *Host* (for LAN discovery) ignores the port mappings: the server listens on the host's 8080 and 8443. + If another service uses either, add the variable `CHRONOS_HTTP_PORT` or `CHRONOS_HTTPS_PORT` with a free port first, + and leave the public ports empty. ## [0.1.0-rc.8] — 2026-11-03 diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 376a1397..65bc2d9a 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -615,7 +615,12 @@ One line per decision: date · decision · alternative · reason. | 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 | The admin panel's client address is computed in the browser: `https://` + `location.hostname` (IPv6 in brackets) + `:` + the port the page came through when the browser speaks HTTPS to the server itself, else (plain HTTP, only from the server's own machine) the public HTTPS port or HTTPS port (no port when 443); `location.origin` in TLS mode proxy. When the page's HTTPS port is not the saved one (a container's 8443 published as 8444, Public HTTPS port still empty), a *Use 8444* button next to Public HTTPS port fills it in. 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 | `ChronosClient.GetInfoAsync` throws `NotChronosServerException` when `server/info` is not Chronos's: any 3xx (Chronos never redirects it), any answer that is not JSON whatever its status, more than 1 MB, JSON without a Chronos `ServerInfo` (name, version, API version, lists, limits), or an error without the `X-Chronos-Api` header every Chronos response carries and a Chronos error code. A busy answer (408, 429, 502-504) with JSON or no body cannot tell. On an untrusted certificate it reads `server/info` once more with certificate checks off, no token, no cookies and no redirects, under the same rules, 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. | +| 2026-11-04 | Saving a public HTTPS port (or clearing it to the listening one) other than both the saved one and the port this page came through over HTTPS asks first (*Send clients to port 8445?*); the server does not check it. | Server-side warning in the log | The HTTPS redirect follows the saved port at once, so a typo would send the panel's link to a dead port or another service's sign-in page; only the browser knows which port really reached the server. Saving other settings never asks. | +| 2026-11-04 | `GetInfoAsync`: when TLS fails on an HTTPS address and no certificate was refused (the port speaks plain HTTP: the HTTP port typed without a scheme, `192.168.30.23:8087`), it reads `server/info` over `http://` on the same authority, without credentials; any answer gives `NotChronosServerException` (check the port, the client address), no answer rethrows (unreachable). | Report it as unreachable | The server did answer; the useful advice is the port and the panel's client address. | +| 2026-11-04 | In a container, the first save of the settings removes `HttpPort` and `HttpsPort` from `server.json` (also when nothing else changed); the start-up warning says so. | Remove them at load | Load only reads; the panel cannot edit locked ports, so without this the warning came back at every start. | +| 2026-11-04 | Host networking: the guide, README and compose comments say the port mappings do nothing there, the server listens on the host's 8080/8443 and `CHRONOS_HTTP_PORT` / `CHRONOS_HTTPS_PORT` move it off ports another service uses (public ports empty). No template entries for them. | Advanced template entries *Listening HTTP/HTTPS port* | On Bridge such an entry would unmap the template's ports; Host users add a variable, which Unraid offers on every container. | +| 2026-11-04 | `ChronosAddress` refuses a link-local IPv6 address with a zone index (`fe80::1%12`): *Invalid address*. | Keep the zone as `%25` | `Uri` and the connection would drop the zone, failing later with a less clear error; the LAN address or name works. | diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index 931d756d..7f5b9f2e 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -840,6 +840,11 @@ Photos the running job processes at once; jobs run one at a time The PEM file was not found; enter its full path on the server.long Used only in Own certificate mode + This page came through port {0}. The panel's link and LAN discovery move to the new port at once; if it is wrong, open the panel on port {0} to fix it.long + Save port + Save {0} as the Public HTTPS port; clients and the HTTPS redirect use it at once + Back to the form, nothing saved + Send clients to port {0}? High Low Normal @@ -871,6 +876,8 @@ Days a client stays signed in without being used Abandoned after (h) Hours after which unfinished uploads are discarded + Use {0} + This page came through port {0}, so clients reach the server there: fill it in as the Public HTTPS port, then save, and discovery and the HTTPS redirect follow Sign out Sign out of the admin panel Switch between light and dark diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index fe6cae3f..f1d75487 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -833,6 +833,11 @@ Foto che l'attività in corso elabora insieme; le attività girano una alla volta File PEM non trovato; inserisci il percorso completo sul server. Usato solo in modalità Certificato proprio + Questa pagina è arrivata dalla porta {0}. Il collegamento al pannello e il rilevamento LAN passano subito alla nuova porta; se è sbagliata, apri il pannello sulla porta {0} per correggerla. + Salva porta + Salva {0} come porta HTTPS pubblica; i client e il reindirizzamento HTTPS la usano subito + Torna al modulo senza salvare + Mandare i client alla porta {0}? Alta Bassa Normale @@ -864,6 +869,8 @@ Giorni in cui un client resta connesso senza essere usato Abbandono dopo (h) Ore dopo le quali i caricamenti incompleti vengono scartati + Usa {0} + Questa pagina è arrivata dalla porta {0}, quindi i client raggiungono il server lì: inseriscila come porta HTTPS pubblica e salva, così il rilevamento LAN e il reindirizzamento HTTPS la seguono Esci Esci dal pannello di amministrazione Alterna tema chiaro e scuro diff --git a/src/Chronos.Protocol/Client/ChronosAddress.cs b/src/Chronos.Protocol/Client/ChronosAddress.cs index 63564310..929b6133 100644 --- a/src/Chronos.Protocol/Client/ChronosAddress.cs +++ b/src/Chronos.Protocol/Client/ChronosAddress.cs @@ -7,7 +7,8 @@ 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. +/// is 443, a reverse proxy); a port typed is always kept. A bare IPv6 address gets its brackets; one with a zone index +/// ("fe80::1%12") is refused, as the request could not keep the zone. /// public static class ChronosAddress { @@ -24,10 +25,17 @@ public static class ChronosAddress 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 + "]"; + if (!trimmed.StartsWith('[') && IPAddress.TryParse(trimmed, out var ip) && ip.AddressFamily == AddressFamily.InterNetworkV6) + { + if (ip.ScopeId != 0) return false; + 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; + // A link-local address with its zone ("fe80::1%12"): the zone would not survive into the request, so it is refused. + if (parsed.HostNameType == UriHostNameType.IPv6 && (parsed.DnsSafeHost.Contains('%', StringComparison.Ordinal) + || IPAddress.TryParse(parsed.DnsSafeHost, out var host) && host.ScopeId != 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 += "/"; diff --git a/src/Chronos.Protocol/Client/ChronosClient.cs b/src/Chronos.Protocol/Client/ChronosClient.cs index e5a2ebf2..d2010c47 100644 --- a/src/Chronos.Protocol/Client/ChronosClient.cs +++ b/src/Chronos.Protocol/Client/ChronosClient.cs @@ -66,71 +66,112 @@ public sealed class ChronosClient : IDisposable /// /// 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. + /// review 3): a redirect, a page that is not JSON, JSON of another shape, or an error Chronos did not write. 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. An HTTPS address whose port answers plain HTTP (the HTTP port typed + /// without a scheme) is not Chronos either. Nothing is trusted here. /// public async Task GetInfoAsync(CancellationToken ct = default) { - ServerInfo info; + HttpResponseMessage response; try { - info = await GetAsync(InfoPath, ProtocolJson.Default.ServerInfo, ct).ConfigureAwait(false); + response = await SendRawAsync(new HttpRequestMessage(HttpMethod.Get, InfoPath), ct).ConfigureAwait(false); } catch (UntrustedCertificateException) when (_ownsHandler) { - if (await AnswersAsChronosAsync(ct).ConfigureAwait(false) == false) throw new NotChronosServerException(BaseAddress); + if (await ProbeAsync(BaseAddress, ct).ConfigureAwait(false) is { Chronos: false }) throw new NotChronosServerException(BaseAddress); throw; } - catch (ChronosApiException api) when (!api.IsTransient && (int)api.Status < 500 && !IsChronosError(api.Error)) + catch (HttpRequestException tls) when (_ownsHandler && tls.HttpRequestError == HttpRequestError.SecureConnectionError + && BaseAddress.Scheme == Uri.UriSchemeHttps) { - throw new NotChronosServerException(BaseAddress, api); + // The same authority over plain HTTP: any answer means the port is not Chronos's HTTPS port. + var plain = new UriBuilder(BaseAddress) { Scheme = Uri.UriSchemeHttp, Port = BaseAddress.Port }.Uri; + if (await ProbeAsync(plain, ct).ConfigureAwait(false) is { Answered: true }) throw new NotChronosServerException(BaseAddress, tls); + throw; } - catch (Exception ex) when (ex is JsonException or NotSupportedException) + using (response) { - throw new NotChronosServerException(BaseAddress, ex); + var answer = await IdentifyAsync(response, ct).ConfigureAwait(false); + if (answer.Info is { } info) return info; + if (answer.Chronos == false) throw new NotChronosServerException(BaseAddress); + // Chronos's own error, or busy: as any other request reports it. + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + throw new NotChronosServerException(BaseAddress); } - return IsChronos(info) ? info : throw new NotChronosServerException(BaseAddress); } private const string InfoPath = "api/v1/server/info"; + /// More than a server info ever holds: a larger answer is something else. + private const int MaxInfoBytes = 1 << 20; + /// 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); + /// What a server/info answer is: Chronos's (with its info when it succeeded), something else, or unknown (busy). + private readonly record struct Identity(bool? Chronos, ServerInfo? Info = null, bool Answered = true); /// - /// 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). + /// Tells a server/info answer of Chronos from any other. Chronos answers it anonymously with its JSON and never + /// redirects; every response of its carries , so an error is Chronos's only with that + /// header and an error body of its own. A busy answer (408, 429, 502-504) with JSON or no body cannot tell; any answer + /// that is not JSON, or is larger than , is something else. /// - private async Task AnswersAsChronosAsync(CancellationToken ct) + private static async Task IdentifyAsync(HttpResponseMessage response, CancellationToken ct) + { + if ((int)response.StatusCode is >= 300 and < 400) return new(false); + var type = response.Content.Headers.ContentType?.MediaType; + var json = type is not null && (type.Equals("application/json", StringComparison.OrdinalIgnoreCase) || type.EndsWith("+json", StringComparison.OrdinalIgnoreCase)); + if (ChronosApiException.IsTransientStatus(response.StatusCode)) return new(json || type is null ? null : false); + if (!json || response.Content.Headers.ContentLength > MaxInfoBytes) return new(false); + try + { + await response.Content.LoadIntoBufferAsync(MaxInfoBytes, ct).ConfigureAwait(false); + if (response.IsSuccessStatusCode) + { + var info = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ServerInfo, ct).ConfigureAwait(false); + return IsChronos(info) ? new(true, info) : new(false); + } + if (!response.Headers.Contains(ApiVersion.Header)) return new(false); + var error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError, ct).ConfigureAwait(false); + return new(error is { Code.Length: > 0 } && !error.Code.StartsWith("http_", StringComparison.Ordinal)); + } + catch (Exception ex) when (ex is JsonException or NotSupportedException or HttpRequestException) + { + // Not JSON after all, or more than a server info. + return new(false); + } + } + + /// + /// The info at read without checking the certificate, by a client of its own that holds no + /// token and follows no redirect; is false when nothing answered (no connection, TLS + /// refused, timeout). + /// + private static async Task ProbeAsync(Uri address, CancellationToken ct) { using var handler = new SocketsHttpHandler { SslOptions = { RemoteCertificateValidationCallback = static (_, _, _, _) => true }, ConnectTimeout = TimeSpan.FromSeconds(10), AutomaticDecompression = DecompressionMethods.None, + AllowAutoRedirect = false, + UseCookies = false, }; - using var http = new HttpClient(handler) { BaseAddress = BaseAddress, Timeout = TimeSpan.FromSeconds(20), MaxResponseContentBufferSize = 1 << 20 }; + using var http = new HttpClient(handler) { BaseAddress = address, Timeout = TimeSpan.FromSeconds(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; + using var response = await http.GetAsync(InfoPath, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + return await IdentifyAsync(response, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is HttpRequestException or IOException || (ex is OperationCanceledException && !ct.IsCancellationRequested)) { - return null; + return new(null, Answered: false); } } diff --git a/src/Chronos.Server/Admin/web/pages/settings.js b/src/Chronos.Server/Admin/web/pages/settings.js index 7c3fe674..f533da65 100644 --- a/src/Chronos.Server/Admin/web/pages/settings.js +++ b/src/Chronos.Server/Admin/web/pages/settings.js @@ -7,9 +7,11 @@ // 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). +// in Chronos: this host as the browser reached it, on the HTTPS port this page came through (else the public HTTPS port; +// the proxy's address in TLS mode proxy). When that port is not the saved one, a button fills it in; saving a public HTTPS +// port other than the page's asks first, as the HTTPS redirect follows it at once. 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 { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, confirmDialog, PROXY_WARNING } from "../ui.js"; import { kindLabel } from "../jobs.js"; import { icons } from "../icons.js"; @@ -60,6 +62,15 @@ export async function render(root, { api, info, setMeta, actions }) { : 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)}"`); + // This page came through another HTTPS port than the one saved (a container's 8443 published as 8444, Public HTTPS port + // still empty): a button fills it in, so the redirect, discovery and the client address follow. + const publicHttps = () => { + const page = pagePort(); + if (page === null || page === savedHttps() || locked("publicHttpsPort")) return publicPort("publicHttpsPort", settings.publicHttpsPort, settings.httpsPort); + return field("publicHttpsPort", ` + `); + }; function draw() { root.innerHTML = ` @@ -88,7 +99,7 @@ export async function render(root, { api, info, setMeta, actions }) { ${listening("httpPort", settings.httpPort)} ${listening("httpsPort", settings.httpsPort)} ${publicPort("publicHttpPort", settings.publicHttpPort, settings.httpPort)} - ${publicPort("publicHttpsPort", settings.publicHttpsPort, settings.httpsPort)} + ${publicHttps()} ${field("clientAddress", ` `)} ${field("tlsMode", `