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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-04 09:53:49 +01:00
1 parent 9b24cf74fc
commit 369e754bec
33 files changed
+862 -82

No files matched your search

+2 -2
View File
@@ -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()
+6 -13
View File
@@ -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) :
/// <summary>Server addresses as typed in the address field.</summary>
public static class ServerAddress
{
/// <summary>Accepts "nas.local:8443" (https assumed) or a full http(s) URL; the result is the API base, ending with "/".</summary>
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;
}
/// <summary>
/// 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 "/" (<see cref="ChronosAddress"/>, shared with the uploader).
/// </summary>
public static bool TryParse(string? text, out Uri uri) => ChronosAddress.TryParse(text, out uri);
/// <summary>The address as shown in the field: the base URL without its trailing slash.</summary>
public static string Display(Uri uri) => uri.ToString().TrimEnd('/');
+8 -3
View File
@@ -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();
}
/// <summary>One sentence for a failed step (BRIEF §0.2 rule 6).</summary>
public static string ErrorText(ConnectError error) => Loc.L("Server.Error." + error);
/// <summary>
/// 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).
/// </summary>
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);
/// <summary>The trust-on-first-use question with the fingerprint split over two lines.</summary>
public static ConfirmRequest TrustRequest(string server, string fingerprint) => new()
+11 -1
View File
@@ -10,6 +10,13 @@ namespace Chronos.Protocol;
/// <see cref="Parallelism"/> is how many photos the running job processes at once (jobs run one at a time), and
/// <see cref="PriorityQueue"/> with <see cref="JobPriorities"/> the priority queue (owner review 1); both apply at once, as
/// do <see cref="Logs"/> (owner review 2, R11; a request without them keeps them as they are).
/// <see cref="PublicHttpPort"/> and <see cref="PublicHttpsPort"/> (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). <see cref="InContainer"/> (responses only) says the
/// server runs in a container, whose listening ports the template fixes: they are then locked, named in
/// <see cref="Locked"/> with the variable <c>DOTNET_RUNNING_IN_CONTAINER</c> 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.
/// </summary>
public sealed record ServerSettingsDto(
string ServerName,
@@ -32,7 +39,10 @@ public sealed record ServerSettingsDto(
IReadOnlyList<string> Locked,
IReadOnlyDictionary<string, string> LockedBy,
bool RestartRequired,
bool ProxyWarning);
bool ProxyWarning,
int? PublicHttpPort = null,
int? PublicHttpsPort = null,
bool InContainer = false);
/// <summary>
/// The log settings of <see cref="ServerSettingsDto"/> (owner review 2, R11): the least severe level of the files and of the
@@ -0,0 +1,49 @@
using System.Net;
using System.Net.Sockets;
namespace Chronos.Protocol.Client;
/// <summary>
/// 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 <see cref="DefaultPort"/>, 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.
/// </summary>
public static class ChronosAddress
{
/// <summary>The HTTPS port of Chronos Server (<c>CHRONOS_HTTPS_PORT</c>'s default).</summary>
public const int DefaultPort = 8443;
/// <summary>The API base for <paramref name="text"/>, ending with "/", without query or fragment; false when it is not an http(s) address.</summary>
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;
}
/// <summary>True when the authority of <paramref name="url"/> (scheme included) names a port, the scheme's default too.</summary>
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;
}
}
@@ -10,10 +10,25 @@ public sealed class ChronosApiException(HttpStatusCode status, ApiError error)
public ApiError Error { get; } = error;
/// <summary>True for errors worth retrying (server busy, gateway, timeout).</summary>
public bool IsTransient => Status is HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests
public bool IsTransient => IsTransientStatus(Status);
/// <summary>Statuses worth retrying (server busy, gateway, timeout).</summary>
public static bool IsTransientStatus(HttpStatusCode status) => status is HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests
or HttpStatusCode.BadGateway or HttpStatusCode.ServiceUnavailable or HttpStatusCode.GatewayTimeout;
}
/// <summary>
/// The address answers, but not as a Chronos Server (owner review 3): its <c>server/info</c> 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.
/// </summary>
public sealed class NotChronosServerException(Uri address, Exception? inner = null)
: Exception($"No Chronos server answers at {address}", inner)
{
/// <summary>The API base that was asked.</summary>
public Uri Address { get; } = address;
}
/// <summary>The server presented a certificate whose fingerprint is not trusted yet (trust-on-first-use, BRIEF §12.7).</summary>
public sealed class UntrustedCertificateException(string fingerprint)
: Exception("Server certificate is not trusted: " + fingerprint)
+74 -2
View File
@@ -20,11 +20,15 @@ public sealed class ChronosClient : IDisposable
{
private readonly HttpClient _http;
private readonly CertificatePinning _pinning;
/// <summary>The client made its own handler, so TLS goes through <see cref="_pinning"/> (tests pass theirs).</summary>
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 ----------------
/// <summary>Reads server info; throws <see cref="UntrustedCertificateException"/> when the TLS certificate needs confirmation.</summary>
public Task<ServerInfo> GetInfoAsync(CancellationToken ct = default) => GetAsync("api/v1/server/info", ProtocolJson.Default.ServerInfo, ct);
/// <summary>
/// Reads server info; throws <see cref="UntrustedCertificateException"/> when the TLS certificate of a Chronos Server
/// needs confirmation, and <see cref="NotChronosServerException"/> 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.
/// </summary>
public async Task<ServerInfo> 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";
/// <summary>What every Chronos Server's info holds; JSON of another shape reads as nulls and zeros.</summary>
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 };
/// <summary>An error body Chronos wrote (<see cref="EnsureSuccessAsync"/> codes any other reply <c>http_&lt;status&gt;</c>).</summary>
private static bool IsChronosError(ApiError error) => error.Code is { Length: > 0 } code && !code.StartsWith("http_", StringComparison.Ordinal);
/// <summary>
/// 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).
/// </summary>
private async Task<bool?> 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 ----------------
+48 -3
View File
@@ -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, `<select class="input" name="${name}" ${lock(name)}>${values.concat(values.includes(value) ? [] : [value])
.map((v) => `<option value="${attr(v)}" ${v === value ? "selected" : ""}>${escapeHtml(t(label(v)))}</option>`).join("")}</select>`);
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)}`, `<input class="input narrow num" type="number" name="${name}" value="${attr(value)}" disabled data-i18n-title="Admin.Settings.ContainerPort.Tip">`)
: 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 }) {
<section class="panel" aria-labelledby="network-title">
<div class="panel-head"><h2 id="network-title" data-i18n="Admin.Settings.Network"></h2>
${settings.proxyWarning ? PROXY_WARNING : ""}</div>
${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", `<span class="inline"><input class="input mono" id="client-address" readonly dir="ltr" value="${attr(clientAddress())}" data-i18n-title="Admin.Settings.ClientAddress.Tip">
<button class="btn icon" type="button" id="copy-address" data-i18n-title="Admin.Settings.CopyAddress.Tip">${icons.copy}</button></span>`)}
${field("tlsMode", `<select class="input" name="tlsMode" ${lock("tlsMode")}>${["auto", "pem", "proxy"].map((m) =>
`<option value="${m}" ${m === settings.tlsMode ? "selected" : ""}>${escapeHtml(t(`Admin.Settings.Tls.${cap(m)}`))}</option>`).join("")}</select>`)}
${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,
@@ -125,13 +125,34 @@ public sealed class ServerOptions
/// <summary>
/// Port clients reach the HTTP listener on, when it differs from <see cref="HttpPort"/> (a container port published
/// as another host port); advertised by LAN discovery. Null: <see cref="HttpPort"/>.
/// as another host port); advertised by LAN discovery. Null: <see cref="HttpPort"/>. Set in the admin panel or by
/// <c>CHRONOS_PUBLIC_HTTP_PORT</c>, which locks it (owner review 3); a saved value applies at once.
/// </summary>
public int? PublicHttpPort { get; set; }
/// <summary>Port clients reach the HTTPS listener on (admin redirect, LAN discovery). Null: <see cref="HttpsPort"/>.</summary>
/// <summary>
/// Port clients reach the HTTPS listener on (admin redirect, LAN discovery, the client address the admin panel shows).
/// Null: <see cref="HttpsPort"/>. Set like <see cref="PublicHttpPort"/>, by <c>CHRONOS_PUBLIC_HTTPS_PORT</c>.
/// </summary>
public int? PublicHttpsPort { get; set; }
/// <summary>The variable the .NET container images set to <c>true</c>: the server runs in a container.</summary>
public const string ContainerVariable = "DOTNET_RUNNING_IN_CONTAINER";
/// <summary>
/// The server runs in a container (<see cref="ContainerVariable"/>; 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
/// <c>server.json</c> holds for them is ignored (<see cref="IgnoredSavedPorts"/>), and only <c>CHRONOS_HTTP_PORT</c> /
/// <c>CHRONOS_HTTPS_PORT</c> change them (owner review 3). The ports clients use are <see cref="PublicHttpPort"/> and
/// <see cref="PublicHttpsPort"/>.
/// </summary>
[JsonIgnore]
public bool InContainer { get; set; }
/// <summary>In a container, <c>server.json</c> held listening ports, which were ignored: the start says so.</summary>
[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<string>();
var lockedBy = new Dictionary<string, string>(StringComparer.Ordinal);
@@ -14,7 +14,8 @@ namespace Chronos.Server.Configuration;
/// The admin panel's view of the configuration (BRIEF §14.8 Settings). Saving writes <c>/data/server.json</c> (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 <see cref="ServerLogging"/>
/// (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
/// (<c>SchedulerHost.AuditRetentionAsync</c>, <c>SchedulerHost.ApplyAuditRetentionAsync</c>).
@@ -43,14 +44,22 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
/// <summary>Validates and saves; returns the error code and the offending setting, or null on success.</summary>
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);
/// <summary>The variable that fixes every locked setting (for one a test locks directly, the variable that would).</summary>
private static Dictionary<string, string> 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);
/// <summary>The listening ports, which a container's template maps (owner review 3).</summary>
private static readonly string[] ContainerPorts = [nameof(ServerOptions.HttpPort), nameof(ServerOptions.HttpsPort)];
/// <summary>Settings the panel cannot change: those environment variables fix and, in a container, its listening ports.</summary>
private static List<string> LockedSettings(ServerOptions o) =>
[.. o.Locked.Concat(o.InContainer ? ContainerPorts : []).Distinct(StringComparer.Ordinal)];
/// <summary>
/// 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 <see cref="ServerOptions.ContainerVariable"/>.
/// </summary>
private static Dictionary<string, string> 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);
/// <summary>A public port as a request sets it: null keeps <paramref name="current"/>, 0 clears it (the listening port applies).</summary>
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)
/// <summary>
/// The first setting of <paramref name="r"/> 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.
/// </summary>
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<TlsMode>(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));
+6
View File
@@ -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;
+5 -13
View File
@@ -1,21 +1,13 @@
using Chronos.Protocol.Client;
namespace Chronos.Uploader.Server;
/// <summary>Server addresses as typed in the sign-in form.</summary>
public static class ServerAddress
{
/// <summary>
/// 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 "/" (<see cref="ChronosAddress"/>, shared with the desktop client).
/// </summary>
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);
}
@@ -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,
@@ -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;