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
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:
1 parent
30a5b03f37
commit
255e149087
306 files changed
+2023
-206
No files matched your search
@@ -98,7 +98,7 @@ public static class ImportPlans
|
||||
plan.Items.Count(i => i.ExistingFrameId is not null),
|
||||
plan.Items.Count(i => i.Action == ImportAction.SkipImported),
|
||||
plan.Problems.Count,
|
||||
plan.AvailableBytes is { } free ? free - plan.CopyBytes : null,
|
||||
Infrastructure.AppClock.ShownFree(plan.AvailableBytes) is { } free ? free - plan.CopyBytes : null,
|
||||
Estimate(plan.CopyBytes, verify));
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -3,15 +3,31 @@ namespace Chronos.App.Infrastructure;
|
||||
/// <summary>
|
||||
/// Today's date for screens that lay themselves out around it (the Library timeline's years, the months of the
|
||||
/// Archive heatmap). <c>--capture</c> freezes it at the sample's moment, so the screenshots draw the same pixels on
|
||||
/// any day and the pixel diff against their baselines stays meaningful.
|
||||
/// any day and the pixel diff against their baselines stays meaningful. While frozen, what the screens measure on this
|
||||
/// machine (free space, a server's latency, when a comparison ran) is shown as fixed sample values too.
|
||||
/// </summary>
|
||||
public static class AppClock
|
||||
{
|
||||
private static DateTimeOffset? _frozen;
|
||||
|
||||
/// <summary>Free space every volume shows while frozen.</summary>
|
||||
public const long FrozenFreeBytes = 1_200_000_000_000;
|
||||
|
||||
/// <summary>The local date: the frozen moment's while frozen, the computer's otherwise.</summary>
|
||||
public static DateTime Today => (_frozen?.ToLocalTime().DateTime ?? DateTime.Now).Date;
|
||||
|
||||
/// <summary>True while frozen (screenshots).</summary>
|
||||
public static bool IsFrozen => _frozen is not null;
|
||||
|
||||
/// <summary>When something happened, as shown: the frozen moment while frozen.</summary>
|
||||
public static DateTimeOffset Shown(DateTimeOffset moment) => _frozen ?? moment;
|
||||
|
||||
/// <summary>A measured duration as shown: <paramref name="sample"/> while frozen.</summary>
|
||||
public static TimeSpan Shown(TimeSpan measured, TimeSpan sample) => _frozen is null ? measured : sample;
|
||||
|
||||
/// <summary>Measured free bytes as shown: <see cref="FrozenFreeBytes"/> while frozen (unknown stays unknown).</summary>
|
||||
public static long? ShownFree(long? measured) => _frozen is null || measured is null ? measured : FrozenFreeBytes;
|
||||
|
||||
/// <summary>Stops the clock at <paramref name="moment"/> for the rest of the process (screenshots only).</summary>
|
||||
public static void Freeze(DateTimeOffset moment) => _frozen = moment;
|
||||
}
|
||||
@@ -110,7 +110,7 @@ public static class ArchiveLocations
|
||||
var root = Path.GetPathRoot(Path.GetFullPath(path));
|
||||
if (string.IsNullOrEmpty(root)) return null;
|
||||
var drive = new DriveInfo(root);
|
||||
return drive.IsReady ? drive.AvailableFreeSpace : null;
|
||||
return AppClock.ShownFree(drive.IsReady ? drive.AvailableFreeSpace : null);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
||||
{
|
||||
|
||||
@@ -107,7 +107,8 @@ public sealed class ServerViewModel : SectionViewModel
|
||||
{
|
||||
if (!IsConnected || Session.Flow.Info is not { } info) return null;
|
||||
var parts = new List<string> { info.Name, Loc.L("Server.Version", info.Version) };
|
||||
if (Session.Flow.Latency is { } latency) parts.Add(Loc.L("Server.Latency", Math.Max(1, (int)Math.Round(latency.TotalMilliseconds))));
|
||||
if (Session.Flow.Latency is { } measured && AppClock.Shown(measured, TimeSpan.FromMilliseconds(12)) is var latency)
|
||||
parts.Add(Loc.L("Server.Latency", Math.Max(1, (int)Math.Round(latency.TotalMilliseconds))));
|
||||
return string.Join(Loc.Separator, parts);
|
||||
}
|
||||
}
|
||||
@@ -212,7 +213,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 +254,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()
|
||||
|
||||
@@ -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('/');
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -153,7 +153,8 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
|
||||
/// <summary>"Last sync 10:15 · manifest diff 0.4 s"; null before the first comparison.</summary>
|
||||
public string? LastSyncText => Host.Agent?.Snapshot is { } s
|
||||
? Loc.L("Server.Sync.Last", Formatting.TimeOfDay(s.RefreshedAt), s.Duration.TotalSeconds.ToString("0.0", Loc.Culture))
|
||||
? Loc.L("Server.Sync.Last", Formatting.TimeOfDay(AppClock.Shown(s.RefreshedAt)),
|
||||
AppClock.Shown(s.Duration, TimeSpan.FromSeconds(0.4)).TotalSeconds.ToString("0.0", Loc.Culture))
|
||||
: null;
|
||||
|
||||
/// <summary>"Server archive 9.4 TB · 412 sequences".</summary>
|
||||
|
||||
@@ -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,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)
|
||||
|
||||
@@ -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 ----------------
|
||||
|
||||
|
||||
@@ -4,10 +4,16 @@
|
||||
// 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 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";
|
||||
|
||||
/** Levels of the priority queue, highest first. */
|
||||
const LEVELS = ["high", "normal", "low"];
|
||||
@@ -50,6 +56,21 @@ 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)}"`);
|
||||
// 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", `<span class="inline"><input class="input narrow num" type="number" name="publicHttpsPort" value="${attr(settings.publicHttpsPort ?? "")}"
|
||||
min="1" max="65535" placeholder="${attr(settings.httpsPort)}" data-i18n-title="Admin.Settings.PublicHttpsPort.Tip">
|
||||
<button class="btn small" type="button" id="use-page-port" title="${attr(t("Admin.Settings.UsePagePort.Tip", page))}">${escapeHtml(t("Admin.Settings.UsePagePort", page))}</button></span>`);
|
||||
};
|
||||
|
||||
function draw() {
|
||||
root.innerHTML = `
|
||||
@@ -75,8 +96,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)}
|
||||
${publicHttps()}
|
||||
${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 +134,21 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
form.addEventListener("submit", save);
|
||||
form.elements.tlsMode.addEventListener("change", () => pemFiles(form));
|
||||
pemFiles(form);
|
||||
root.querySelector("#use-page-port")?.addEventListener("click", (e) => {
|
||||
form.elements.publicHttpsPort.value = String(pagePort());
|
||||
e.currentTarget.remove();
|
||||
form.elements.publicHttpsPort.focus();
|
||||
});
|
||||
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 +180,29 @@ 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: the host name the browser used (an IPv6 address in brackets) on the port
|
||||
* this page came through over HTTPS, which reaches the server whatever is saved; over plain HTTP (this machine), 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 = pagePort() ?? savedHttps();
|
||||
return port === 443 ? `https://${host}` : `https://${host}:${port}`;
|
||||
}
|
||||
|
||||
/** The HTTPS port clients are told to use, as saved: the public one, else the one the server listens on. */
|
||||
function savedHttps() {
|
||||
return settings.publicHttpsPort ?? settings.httpsPort;
|
||||
}
|
||||
|
||||
/** The port this page came through when the browser speaks HTTPS to the server itself (not through a proxy), else null. */
|
||||
function pagePort() {
|
||||
if (location.protocol !== "https:" || settings.tlsMode === "proxy") return null;
|
||||
return Number(location.port || 443);
|
||||
}
|
||||
|
||||
/** 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 +220,29 @@ 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);
|
||||
};
|
||||
// A new public HTTPS port other than the one this page came through moves the HTTPS redirect away from it at once: a
|
||||
// typo would send the panel's link to a port where nothing, or another service, answers. Asked once before saving.
|
||||
const nextPublic = publicValue("publicHttpsPort");
|
||||
const page = pagePort();
|
||||
const nextHttps = nextPublic === 0 || nextPublic == null ? settings.httpsPort : nextPublic;
|
||||
if (page !== null && nextPublic !== -1 && nextHttps !== savedHttps() && nextHttps !== page && !await confirmDialog({
|
||||
title: t("Admin.Settings.PortChangeTitle", nextHttps),
|
||||
body: t("Admin.Settings.PortChangeBody", page),
|
||||
confirm: t("Admin.Settings.PortChangeConfirm"),
|
||||
confirmTip: t("Admin.Settings.PortChangeConfirm.Tip", nextHttps),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Settings.PortChangeKeep.Tip"),
|
||||
})) {
|
||||
form.elements.publicHttpsPort.focus();
|
||||
return;
|
||||
}
|
||||
const request = {
|
||||
...settings,
|
||||
serverName: String(value("serverName", settings.serverName)).trim(),
|
||||
@@ -167,6 +253,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: nextPublic,
|
||||
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,37 @@ 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, and the next save of
|
||||
/// the settings removes them from the file (<see cref="ServerSettingsStore.Save"/>).
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public bool IgnoredSavedPorts { get; internal set; }
|
||||
|
||||
public TlsMode TlsMode { get; set; } = TlsMode.Auto;
|
||||
public string? TlsCert { get; set; }
|
||||
public string? TlsKey { get; set; }
|
||||
@@ -301,6 +325,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,22 +44,39 @@ 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);
|
||||
if (changes.Count == 0) return null;
|
||||
var fixedSettings = LockedSettings(options);
|
||||
if (changes.FirstOrDefault(c => fixedSettings.Contains(c.Name)) is { Name: { } locked }) return ("setting_locked", locked);
|
||||
// In a container the listening ports are the template's: ports an earlier version saved are dropped at the first
|
||||
// save, so the start stops warning about them (owner review 3).
|
||||
var dropPorts = options.InContainer && options.IgnoredSavedPorts;
|
||||
if (changes.Count == 0 && !dropPorts) return null;
|
||||
|
||||
var file = File.Exists(options.SettingsFile) ? JsonNode.Parse(File.ReadAllText(options.SettingsFile)) as JsonObject ?? [] : [];
|
||||
foreach (var (name, value) in changes) file[name] = value;
|
||||
// The former name of the parallelism (jobs run at once before owner review 1) would set it again at the next start.
|
||||
if (changes.Any(c => c.Name == nameof(ServerOptions.Parallelism))) file.Remove("Workers");
|
||||
if (options.InContainer)
|
||||
{
|
||||
file.Remove(nameof(ServerOptions.HttpPort));
|
||||
file.Remove(nameof(ServerOptions.HttpsPort));
|
||||
}
|
||||
Directory.CreateDirectory(options.DataPath);
|
||||
AtomicFile.WriteAllText(options.SettingsFile, file.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
|
||||
if (dropPorts) options.IgnoredSavedPorts = false;
|
||||
|
||||
options.ServerName = request.ServerName.Trim();
|
||||
options.Discovery = request.Discovery;
|
||||
@@ -79,6 +97,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 +110,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 +123,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 +173,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 +215,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));
|
||||
|
||||
@@ -94,6 +94,13 @@ 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. Saving the settings in the admin panel removes the saved values. Set the Public HTTP and HTTPS ports to the host "
|
||||
+ "ports clients use; with network type Host, add the variable CHRONOS_HTTP_PORT or CHRONOS_HTTPS_PORT to listen on other ports.",
|
||||
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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -161,19 +161,25 @@ public sealed class ConnectViewModel : ObservableObject, INotifyDataErrorInfo
|
||||
{
|
||||
var (result, fingerprint) = await _session.SignInAsync(Address, Username.Trim(), Password, CancellationToken.None);
|
||||
if (result != SignInResult.Untrusted || fingerprint is null) return result;
|
||||
if (!_dialogs.ConfirmTrust(Display(Address), fingerprint)) return SignInResult.Untrusted;
|
||||
if (!_dialogs.ConfirmTrust(Asked(), fingerprint)) return SignInResult.Untrusted;
|
||||
_session.Trust(fingerprint);
|
||||
(result, _) = await _session.SignInAsync(Address, Username.Trim(), Password, CancellationToken.None);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The address as it is asked, port included: "192.168.1.20" goes to port 8443 (owner review 3), which the trust question
|
||||
/// and the not-Chronos error both name.
|
||||
/// </summary>
|
||||
private string Asked() => ServerAddress.TryParse(Address, out var asked) ? Display(asked.ToString()) : Address.Trim();
|
||||
|
||||
/// <summary>Puts each failure where it belongs: on the field it is about, or in the sentence under the form.</summary>
|
||||
private void ShowResult(SignInResult? result)
|
||||
{
|
||||
AddressError = result switch
|
||||
{
|
||||
SignInResult.InvalidAddress => Loc.L("Uploader.Connect.Error.InvalidAddress"),
|
||||
SignInResult.NotChronos => Loc.L("Uploader.Connect.Error.NotChronos"),
|
||||
SignInResult.NotChronos => Loc.L("Uploader.Connect.Error.NotChronosAt", "" + Asked() + ""),
|
||||
_ => null,
|
||||
};
|
||||
PasswordError = result == SignInResult.BadCredentials ? Loc.L("Uploader.Connect.Error.BadCredentials") : null;
|
||||
|
||||
Reference in new issue
Block a user