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:
1 parent
9b24cf74fc
commit
369e754bec
33 files changed
+862
-82
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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_<status></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 ----------------
|
||||
|
||||
|
||||
Reference in new issue
Block a user