fix: owner review 3 phase 1: server ports for clients, screenshot baselines (#16)
CI / Build and test (push) Successful in 9m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m4s
CI / PostgreSQL 16 integration (push) Successful in 8m26s
CI / PostgreSQL 17 integration (push) Successful in 8m43s
CI / Docker image (push) Successful in 50s
Release / Server image (push) Successful in 1m23s

Clients could not reach a server in a container whose ports are published as other host ports: the panel showed the container's ports, the template had no public HTTP port, and a bare host meant port 443. Public ports become panel settings, the panel shows the client address, both clients default to 8443, and an address that answers as another service is named as not a Chronos server (its certificate never offered for trust). The screenshot baselines are captured on the development PC and committed; measured values are fixed while the capture runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #16.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-04 12:33:22 +01:00
1 parent 30a5b03f37
commit 255e149087
306 files changed
+2023 -206

No files matched your search

@@ -0,0 +1,57 @@
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; one with a zone index
/// ("fe80::1%12") is refused, as the request could not keep the zone.
/// </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)
{
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 += "/";
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)
+119 -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,121 @@ 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): 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.
/// </summary>
public async Task<ServerInfo> GetInfoAsync(CancellationToken ct = default)
{
HttpResponseMessage response;
try
{
response = await SendRawAsync(new HttpRequestMessage(HttpMethod.Get, InfoPath), ct).ConfigureAwait(false);
}
catch (UntrustedCertificateException) when (_ownsHandler)
{
if (await ProbeAsync(BaseAddress, ct).ConfigureAwait(false) is { Chronos: false }) throw new NotChronosServerException(BaseAddress);
throw;
}
catch (HttpRequestException tls) when (_ownsHandler && tls.HttpRequestError == HttpRequestError.SecureConnectionError
&& BaseAddress.Scheme == Uri.UriSchemeHttps)
{
// 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;
}
using (response)
{
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, already read (the body cannot be read twice), or busy: as any other request reports it.
if (answer.Error is { } error) throw new ChronosApiException(response.StatusCode, error);
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
throw new NotChronosServerException(BaseAddress);
}
}
private const string InfoPath = "api/v1/server/info";
/// <summary>More than a server info ever holds: a larger answer is something else.</summary>
private const int MaxInfoBytes = 1 << 20;
/// <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>
/// What a <c>server/info</c> answer is: Chronos's (with its info when it succeeded, or its error when it failed),
/// something else, or unknown (busy).
/// </summary>
private readonly record struct Identity(bool? Chronos, ServerInfo? Info = null, bool Answered = true, ApiError? Error = null);
/// <summary>
/// Tells a <c>server/info</c> answer of Chronos from any other. Chronos answers it anonymously with its JSON and never
/// redirects; every response of its carries <see cref="ApiVersion.Header"/>, 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 <see cref="MaxInfoBytes"/>, is something else.
/// </summary>
private static async Task<Identity> 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 error is { Code.Length: > 0 } && !error.Code.StartsWith("http_", StringComparison.Ordinal) ? new(true, Error: error) : new(false);
}
catch (Exception ex) when (ex is JsonException or NotSupportedException or HttpRequestException)
{
// Not JSON after all, or more than a server info.
return new(false);
}
}
/// <summary>
/// The info at <paramref name="address"/> read without checking the certificate, by a client of its own that holds no
/// token and follows no redirect; <see cref="Identity.Answered"/> is false when nothing answered (no connection, TLS
/// refused, timeout).
/// </summary>
private static async Task<Identity> 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 = 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, 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 new(null, Answered: false);
}
}
// ---------------- Auth ----------------