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>
No files matched your search
@@ -80,6 +80,7 @@ public sealed class ConnectFlowTests
|
||||
[Case("ftp://nas.local", ConnectError.InvalidAddress)]
|
||||
[Case("down.local", ConnectError.Unreachable)]
|
||||
[Case("web.local", ConnectError.NotChronos)]
|
||||
[Case("other.local", ConnectError.NotChronos)]
|
||||
public async Task ProbeFailuresAreClassified(string address, ConnectError error)
|
||||
{
|
||||
using var flow = new ConnectFlow(new FakeServer(), new MemoryTrust());
|
||||
@@ -141,9 +142,32 @@ public sealed class ConnectFlowTests
|
||||
Assert.Equal(1, changes);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnotherServiceOnThePortIsNamedWithTheAddressAsked()
|
||||
{
|
||||
// Owner review 3: "192.168.30.23" goes to port 8443, where the owner's NAS runs another service.
|
||||
var server = new FakeServer { SelfSigned = true };
|
||||
var trust = new MemoryTrust();
|
||||
using var flow = new ConnectFlow(server, trust);
|
||||
Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("other.local"));
|
||||
Assert.Equal(ConnectError.NotChronos, flow.Error);
|
||||
Assert.Null(flow.PendingFingerprint);
|
||||
Assert.Empty(trust.Fingerprints);
|
||||
Assert.Equal(Chronos.Core.Localization.Loc.L("Server.Error.NotChronosAt", Chronos.App.Infrastructure.Formatting.LeftToRight("https://other.local:8443")),
|
||||
ServerSession.ErrorText(flow.Error, flow.Address));
|
||||
Assert.Contains("https://other.local:8443", ServerSession.ErrorText(flow.Error, flow.Address));
|
||||
// Without the address, and for other errors, the sentence stays as it was.
|
||||
Assert.Equal(Chronos.Core.Localization.Loc.L("Server.Error.NotChronos"), ServerSession.ErrorText(ConnectError.NotChronos));
|
||||
Assert.Equal(Chronos.Core.Localization.Loc.L("Server.Error.Unreachable"), ServerSession.ErrorText(ConnectError.Unreachable, flow.Address));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AddressesAreNormalised()
|
||||
{
|
||||
Assert.True(ServerAddress.TryParse("nas.local", out var bare));
|
||||
Assert.Equal("https://nas.local:8443/", bare.ToString());
|
||||
Assert.True(ServerAddress.TryParse("https://chronos.example.com", out var proxied));
|
||||
Assert.Equal("https://chronos.example.com/", proxied.ToString());
|
||||
Assert.True(ServerAddress.TryParse("nas.local:8443", out var a));
|
||||
Assert.Equal("https://nas.local:8443/", a.ToString());
|
||||
Assert.True(ServerAddress.TryParse(" http://10.0.0.5:8080/chronos?x=1 ", out var b));
|
||||
@@ -228,6 +252,8 @@ public sealed class ConnectFlowTests
|
||||
{
|
||||
if (BaseAddress.Host == "down.local") throw new HttpRequestException("No such host");
|
||||
if (BaseAddress.Host == "web.local") throw new ChronosApiException(HttpStatusCode.NotFound, new ApiError("http_404", "Not Found"));
|
||||
// What ChronosClient reports for another service on the port: its page, its sign-in redirect, its certificate.
|
||||
if (BaseAddress.Host == "other.local") throw new NotChronosServerException(BaseAddress);
|
||||
if (server.SelfSigned && !trusted.Contains(Fingerprint)) throw new UntrustedCertificateException(Fingerprint);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,10 +56,13 @@ public sealed class ConnectViewModelTests
|
||||
public void AServerThatIsNotChronosMarksTheServerField()
|
||||
{
|
||||
var form = Form(new FakeSession(SignInResult.NotChronos));
|
||||
// Owner review 3: the address as it was asked, port included, so the user sees which port answered.
|
||||
form.Address = "192.168.30.23";
|
||||
|
||||
form.SignInCommand.Execute(null);
|
||||
|
||||
Assert.Equal(Loc.L("Uploader.Connect.Error.NotChronos"), form.AddressError);
|
||||
Assert.Equal(Loc.L("Uploader.Connect.Error.NotChronosAt", "https://192.168.30.23:8443"), form.AddressError);
|
||||
Assert.Contains("https://192.168.30.23:8443", form.AddressToolTip);
|
||||
Assert.Null(form.ErrorText);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,18 @@ public sealed class ServerAddressTests
|
||||
[Case("https://nas.local:8443", "https://nas.local:8443/")]
|
||||
[Case(" http://192.168.1.20:8080/chronos ", "http://192.168.1.20:8080/chronos/")]
|
||||
[Case("https://nas.local/?x=1#y", "https://nas.local/")]
|
||||
// Owner review 3: no scheme and no port is Chronos's HTTPS port, as the placeholder shows.
|
||||
[Case("192.168.30.23", "https://192.168.30.23:8443/")]
|
||||
[Case("nas.local", "https://nas.local:8443/")]
|
||||
[Case("nas.local/chronos", "https://nas.local:8443/chronos/")]
|
||||
[Case("192.168.30.23:8444", "https://192.168.30.23:8444/")]
|
||||
[Case("nas.local:443", "https://nas.local/")]
|
||||
[Case("https://chronos.example.com", "https://chronos.example.com/")]
|
||||
[Case("http://nas.local", "http://nas.local/")]
|
||||
[Case("fd00::5", "https://[fd00::5]:8443/")]
|
||||
[Case("[fd00::5]", "https://[fd00::5]:8443/")]
|
||||
[Case("[fd00::5]:9443", "https://[fd00::5]:9443/")]
|
||||
[Case("https://[fd00::5]", "https://[fd00::5]/")]
|
||||
public void ServerAddressesBecomeApiBases(string typed, string expected)
|
||||
{
|
||||
Assert.True(ServerAddress.TryParse(typed, out var uri));
|
||||
@@ -21,5 +33,9 @@ public sealed class ServerAddressTests
|
||||
[Case(" ")]
|
||||
[Case("ftp://nas.local")]
|
||||
[Case("https://")]
|
||||
// A zone index cannot reach the request: refused rather than dropped.
|
||||
[Case("fe80::1%12")]
|
||||
[Case("[fe80::1%12]:8443")]
|
||||
[Case("https://[fe80::1%2512]")]
|
||||
public void InvalidServerAddressesAreRejected(string typed) => Assert.False(ServerAddress.TryParse(typed, out _));
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Api;
|
||||
|
||||
/// <summary>
|
||||
/// What a client makes of the address it was given (owner review 3): the owner's NAS answers on 8443 with another service,
|
||||
/// which redirects to its sign-in page behind a self-signed certificate of its own.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class ServerIdentityTests(TestContext context)
|
||||
{
|
||||
/// <summary>Answers of another service, each under its own path.</summary>
|
||||
private static readonly string[] OtherAnswers =
|
||||
[
|
||||
"html/", "redirect/", "away/", "empty/", "json/", "unauthorized/", "missing/", "text/", "failed/", "gateway/", "json401/", "json403/",
|
||||
"json404/", "huge/", "hugejson/",
|
||||
];
|
||||
|
||||
[Test]
|
||||
public async Task AnAddressThatAnswersAsSomethingElseIsNotAChronosServer()
|
||||
{
|
||||
await using var other = await OtherService.StartAsync(context);
|
||||
// Over HTTP, and over HTTPS behind the service's own certificate, which nobody trusted.
|
||||
foreach (var address in new[] { other.Http, other.Https }.SelectMany(root => OtherAnswers.Select(path => new Uri(root, path))))
|
||||
{
|
||||
using var client = new ChronosClient(address, new CertificatePinning([]), "tests");
|
||||
var error = await Assert.ThrowsAsync<NotChronosServerException>(() => client.GetInfoAsync(context.Cancellation), address.ToString());
|
||||
Assert.Equal(address, error.Address, address.ToString());
|
||||
}
|
||||
Assert.Equal(0, other.Authorized, "no request carried credentials");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheHttpPortTypedWithoutASchemeIsNotAChronosServer()
|
||||
{
|
||||
// "192.168.30.23:8087", the port of the panel's link: HTTPS to a port that answers plain HTTP.
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
Assert.True(ChronosAddress.TryParse($"127.0.0.1:{server.HttpBase.Port}", out var typed));
|
||||
using var client = new ChronosClient(typed, new CertificatePinning([]), "tests");
|
||||
var error = await Assert.ThrowsAsync<NotChronosServerException>(() => client.GetInfoAsync(context.Cancellation));
|
||||
Assert.Equal(typed, error.Address);
|
||||
|
||||
await using var other = await OtherService.StartAsync(context);
|
||||
using var otherClient = new ChronosClient(new UriBuilder(other.Http) { Scheme = "https", Port = other.Http.Port }.Uri, new CertificatePinning([]), "tests");
|
||||
await Assert.ThrowsAsync<NotChronosServerException>(() => otherClient.GetInfoAsync(context.Cancellation));
|
||||
|
||||
// A port where nothing answers is still unreachable, not another service.
|
||||
var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var closed = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
listener.Stop();
|
||||
using var nobody = new ChronosClient(new Uri($"https://127.0.0.1:{closed}/"), new CertificatePinning([]), "tests");
|
||||
await Assert.ThrowsAsync<HttpRequestException>(() => nobody.GetInfoAsync(context.Cancellation));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheCertificateOfAnotherServiceIsNeverOfferedForTrust()
|
||||
{
|
||||
await using var other = await OtherService.StartAsync(context);
|
||||
var pinning = new CertificatePinning([]);
|
||||
using var client = new ChronosClient(new Uri(other.Https, "redirect/"), pinning, "tests");
|
||||
await Assert.ThrowsAsync<NotChronosServerException>(() => client.GetInfoAsync(context.Cancellation));
|
||||
// Nothing was trusted, and the next request still refuses the certificate.
|
||||
await Assert.ThrowsAsync<UntrustedCertificateException>(() => client.MeAsync(context.Cancellation));
|
||||
Assert.Equal(0, other.Authorized, "no request carried credentials");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AChronosErrorFromTheInfoIsReportedAsThatError()
|
||||
{
|
||||
// Chronos's own error (its header and code) is read once to tell it from other services: it must still come back
|
||||
// as the server's error, and an unknown certificate still asks for trust.
|
||||
await using var other = await OtherService.StartAsync(context);
|
||||
foreach (var (path, status, code) in new[] { ("chronos500/", HttpStatusCode.InternalServerError, "internal"), ("chronos400/", HttpStatusCode.BadRequest, "bad_request") })
|
||||
{
|
||||
using var plain = new ChronosClient(new Uri(other.Http, path), new CertificatePinning([]), "tests");
|
||||
var error = await Assert.ThrowsAsync<ChronosApiException>(() => plain.GetInfoAsync(context.Cancellation), path);
|
||||
Assert.Equal(status, error.Status, path);
|
||||
Assert.Equal(code, error.Error.Code, path);
|
||||
|
||||
using var untrusted = new ChronosClient(new Uri(other.Https, path), new CertificatePinning([]), "tests");
|
||||
await Assert.ThrowsAsync<UntrustedCertificateException>(() => untrusted.GetInfoAsync(context.Cancellation), path);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AChronosServerBehindAnUnknownCertificateStillAsksForTrust()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.ServerName = "Studio NAS");
|
||||
var https = Assert.NotNull(server.HttpsBase);
|
||||
using var unknown = new ChronosClient(https, new CertificatePinning([]), "tests");
|
||||
var untrusted = await Assert.ThrowsAsync<UntrustedCertificateException>(() => unknown.GetInfoAsync(context.Cancellation));
|
||||
using var info = await server.Client.GetAsync("/api/v1/server/info");
|
||||
Assert.Equal((await info.ReadAsync(ProtocolJson.Default.ServerInfo)).TlsFingerprint, untrusted.Fingerprint);
|
||||
|
||||
using var trusted = new ChronosClient(https, new CertificatePinning([untrusted.Fingerprint]), "tests");
|
||||
Assert.Equal("Studio NAS", (await trusted.GetInfoAsync(context.Cancellation)).Name);
|
||||
// Plain HTTP to the same server is Chronos too.
|
||||
using var plain = new ChronosClient(server.HttpBase, new CertificatePinning([]), "tests");
|
||||
Assert.Equal("Studio NAS", (await plain.GetInfoAsync(context.Cancellation)).Name);
|
||||
}
|
||||
|
||||
/// <summary>A web service that is not Chronos, on HTTP and on HTTPS with a self-signed certificate of its own.</summary>
|
||||
private sealed class OtherService : IAsyncDisposable
|
||||
{
|
||||
private readonly WebApplication _app;
|
||||
private int _authorized;
|
||||
|
||||
private OtherService(WebApplication app)
|
||||
{
|
||||
_app = app;
|
||||
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Select(a => new Uri(a)).ToList();
|
||||
Http = new Uri(addresses.First(a => a.Scheme == "http"), "/");
|
||||
Https = new Uri(addresses.First(a => a.Scheme == "https"), "/");
|
||||
}
|
||||
|
||||
public Uri Http { get; }
|
||||
public Uri Https { get; }
|
||||
|
||||
/// <summary>Requests that carried an Authorization header.</summary>
|
||||
public int Authorized => Volatile.Read(ref _authorized);
|
||||
|
||||
public static async Task<OtherService> StartAsync(TestContext context)
|
||||
{
|
||||
using var key = RSA.Create(2048);
|
||||
var request = new CertificateRequest("CN=other-service", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
using var created = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
|
||||
var certificate = X509CertificateLoader.LoadPkcs12(created.Export(X509ContentType.Pfx), null);
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder();
|
||||
builder.Logging.ClearProviders();
|
||||
builder.WebHost.ConfigureKestrel(k =>
|
||||
{
|
||||
k.Listen(IPAddress.Loopback, 0);
|
||||
k.Listen(IPAddress.Loopback, 0, l => l.UseHttps(certificate));
|
||||
});
|
||||
var app = builder.Build();
|
||||
OtherService? service = null;
|
||||
app.Use(async (http, next) =>
|
||||
{
|
||||
if (http.Request.Headers.Authorization.Count > 0 && service is not null) Interlocked.Increment(ref service._authorized);
|
||||
await next(http);
|
||||
});
|
||||
app.MapGet("/html/api/v1/server/info", () => Results.Content("<!doctype html><title>NAS</title>", "text/html"));
|
||||
app.MapGet("/redirect/api/v1/server/info", () => Results.Redirect("/login"));
|
||||
app.MapGet("/login", () => Results.Content("<!doctype html><form>Sign in</form>", "text/html"));
|
||||
app.MapGet("/empty/api/v1/server/info", () => Results.Content("{}", "application/json"));
|
||||
app.MapGet("/json/api/v1/server/info", () => Results.Content("""{"status":"ok","name":"router"}""", "application/json"));
|
||||
app.MapGet("/unauthorized/api/v1/server/info", () => Results.StatusCode(StatusCodes.Status401Unauthorized));
|
||||
// An absolute redirect to plain HTTP, which a client never follows from HTTPS.
|
||||
app.MapGet("/away/api/v1/server/info", (HttpContext http) => Results.Redirect($"http://{http.Request.Host}/login"));
|
||||
app.MapGet("/text/api/v1/server/info", () => Results.Text("ok"));
|
||||
app.MapGet("/failed/api/v1/server/info", () => Results.Content("<!doctype html><title>Error</title>", "text/html", statusCode: StatusCodes.Status500InternalServerError));
|
||||
app.MapGet("/gateway/api/v1/server/info", () => Results.Content("<!doctype html><title>Bad gateway</title>", "text/html", statusCode: StatusCodes.Status502BadGateway));
|
||||
// Errors in JSON with a code of their own, as many web services write them.
|
||||
foreach (var (path, status) in new[] { ("json401", 401), ("json403", 403), ("json404", 404) })
|
||||
app.MapGet($"/{path}/api/v1/server/info", () => Results.Content("""{"code":"denied","message":"Sign in"}""", "application/json", statusCode: status));
|
||||
// Errors as Chronos writes them: its header and a code of its own.
|
||||
foreach (var (path, status, code) in new[] { ("chronos500", 500, "internal"), ("chronos400", 400, "bad_request") })
|
||||
app.MapGet($"/{path}/api/v1/server/info", (HttpContext http) =>
|
||||
{
|
||||
http.Response.Headers[ApiVersion.Header] = "1";
|
||||
return Results.Content($$"""{"code":"{{code}}","message":"Failed"}""", "application/json", statusCode: status);
|
||||
});
|
||||
// More than a server info ever holds.
|
||||
app.MapGet("/huge/api/v1/server/info", () => Results.Content("<!doctype html>" + new string('x', 2 << 20), "text/html"));
|
||||
app.MapGet("/hugejson/api/v1/server/info", () => Results.Content("{\"name\":\"" + new string('x', 2 << 20) + "\"}", "application/json"));
|
||||
await app.StartAsync(context.Cancellation);
|
||||
service = new OtherService(app);
|
||||
return service;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _app.StopAsync();
|
||||
await _app.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Hosting;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// The ports clients use and the ports the server listens on (owner review 3): a container publishes 8080 and 8443 as
|
||||
/// other host ports, and only the public ports tell clients, LAN discovery and the HTTPS redirect which ones.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class PublicPortTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task PublicPortsAreSavedAndApplyWithoutARestart()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var admin = await server.AdminAsync();
|
||||
var settings = await SettingsAsync(admin);
|
||||
Assert.Equal(((int?)null, (int?)null, false), (settings.PublicHttpPort, settings.PublicHttpsPort, settings.InContainer));
|
||||
|
||||
// The test server listens on ports the system chose (0), which no request may set.
|
||||
var edited = settings with { HttpPort = 18080, HttpsPort = 18443, PublicHttpPort = 8087, PublicHttpsPort = 8444 };
|
||||
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited, ProtocolJson.Default.ServerSettingsDto))
|
||||
{
|
||||
var answer = await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
|
||||
Assert.Equal(((int?)8087, (int?)8444), (answer.PublicHttpPort, answer.PublicHttpsPort));
|
||||
}
|
||||
Assert.Equal(((int?)8087, (int?)8444), (server.Options.PublicHttpPort, server.Options.PublicHttpsPort));
|
||||
|
||||
// At once: the beacon and the redirect to HTTPS name the host ports.
|
||||
var beacon = server.Services.GetRequiredService<DiscoveryBeaconService>().CreateBeacon();
|
||||
Assert.Equal((8087, 8444), (beacon.HttpPort, beacon.HttpsPort));
|
||||
var kestrel = server.Services.GetRequiredService<IServer>();
|
||||
Assert.Equal("https://192.168.30.23:8444/admin/", AdminPanel.HttpsLocation(AdminRequest(), server.Options, kestrel));
|
||||
|
||||
// Stored for the next start.
|
||||
var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject();
|
||||
Assert.Equal((8087, 8444), (file["PublicHttpPort"]!.GetValue<int>(), file["PublicHttpsPort"]!.GetValue<int>()));
|
||||
var restarted = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = server.Options.DataPath, ["CHRONOS_DB"] = "postgres" });
|
||||
Assert.Equal(((int?)8087, (int?)8444), (restarted.PublicHttpPort, restarted.PublicHttpsPort));
|
||||
|
||||
// A client of the shape before them sends no public ports: they stay as they are.
|
||||
var older = JsonSerializer.SerializeToNode(edited with { ServerName = "Older client" }, ProtocolJson.Default.ServerSettingsDto)!.AsObject();
|
||||
Assert.True(older.Remove("publicHttpPort") && older.Remove("publicHttpsPort") && older.Remove("inContainer"));
|
||||
using (var content = new StringContent(older.ToJsonString(), Encoding.UTF8, "application/json"))
|
||||
using (var saved = await admin.PutAsync("/api/v1/server/settings", content))
|
||||
Assert.Equal(((int?)8087, (int?)8444), ((await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).PublicHttpPort, server.Options.PublicHttpsPort));
|
||||
Assert.Equal("Older client", server.Options.ServerName);
|
||||
|
||||
// 0 clears one: the listening port applies again, at once.
|
||||
using (var cleared = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { PublicHttpsPort = 0 }, ProtocolJson.Default.ServerSettingsDto))
|
||||
Assert.Null((await cleared.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).PublicHttpsPort);
|
||||
Assert.Null(server.Options.PublicHttpsPort);
|
||||
var listening = Assert.NotNull(server.HttpsBase).Port;
|
||||
Assert.Equal(listening, server.Services.GetRequiredService<DiscoveryBeaconService>().CreateBeacon().HttpsPort);
|
||||
Assert.Equal($"https://192.168.30.23:{listening}/admin/", AdminPanel.HttpsLocation(AdminRequest(), server.Options, kestrel));
|
||||
file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject();
|
||||
Assert.True(file.ContainsKey("PublicHttpsPort") && file["PublicHttpsPort"] is null, "a cleared port no longer sets it");
|
||||
Assert.Null(ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = server.Options.DataPath, ["CHRONOS_DB"] = "postgres" }).PublicHttpsPort);
|
||||
|
||||
foreach (var (invalid, setting) in new (ServerSettingsDto, string)[]
|
||||
{
|
||||
(edited with { PublicHttpPort = 70000 }, "PublicHttpPort"),
|
||||
(edited with { PublicHttpsPort = -1 }, "PublicHttpsPort"),
|
||||
})
|
||||
{
|
||||
using var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", invalid, ProtocolJson.Default.ServerSettingsDto);
|
||||
Assert.Equal(setting, (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_setting")).Details);
|
||||
}
|
||||
Assert.Equal((int?)8087, server.Options.PublicHttpPort);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AVariableLocksItsPublicPort()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.PublicHttpsPort = 8444;
|
||||
o.Locked = [nameof(ServerOptions.PublicHttpsPort)];
|
||||
o.LockedBy = new Dictionary<string, string> { [nameof(ServerOptions.PublicHttpsPort)] = "CHRONOS_PUBLIC_HTTPS_PORT" };
|
||||
});
|
||||
var admin = await server.AdminAsync();
|
||||
var settings = await SettingsAsync(admin);
|
||||
Assert.Equal(((int?)8444, "CHRONOS_PUBLIC_HTTPS_PORT"), (settings.PublicHttpsPort, settings.LockedBy["PublicHttpsPort"]));
|
||||
|
||||
var edited = settings with { HttpPort = 18080, HttpsPort = 18443 };
|
||||
using (var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { PublicHttpsPort = 9444 }, ProtocolJson.Default.ServerSettingsDto))
|
||||
Assert.Equal("PublicHttpsPort", (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
|
||||
using (var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { PublicHttpsPort = 0 }, ProtocolJson.Default.ServerSettingsDto))
|
||||
Assert.Equal("PublicHttpsPort", (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
|
||||
// The other public port, and a request that leaves the locked one as it is, still save.
|
||||
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { PublicHttpPort = 8087 }, ProtocolJson.Default.ServerSettingsDto))
|
||||
await saved.ExpectAsync(HttpStatusCode.OK);
|
||||
Assert.Equal(((int?)8087, (int?)8444), (server.Options.PublicHttpPort, server.Options.PublicHttpsPort));
|
||||
|
||||
// The variables lock their settings at start, with an empty one taken as unset.
|
||||
var root = context.CreateTempDirectory("public-locked");
|
||||
var loaded = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["CHRONOS_DATA_PATH"] = root,
|
||||
["CHRONOS_DB"] = "postgres",
|
||||
["CHRONOS_PUBLIC_HTTPS_PORT"] = "8444",
|
||||
["CHRONOS_PUBLIC_HTTP_PORT"] = "",
|
||||
});
|
||||
Assert.SequenceEqual(["Database", "PublicHttpsPort"], loaded.Locked);
|
||||
Assert.Equal("CHRONOS_PUBLIC_HTTPS_PORT", loaded.LockedBy["PublicHttpsPort"]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task InAContainerTheListeningPortsAreTheTemplates()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.InContainer = true);
|
||||
var admin = await server.AdminAsync();
|
||||
var settings = await SettingsAsync(admin);
|
||||
Assert.True(settings.InContainer);
|
||||
Assert.Contains("HttpPort", settings.Locked);
|
||||
Assert.Contains("HttpsPort", settings.Locked);
|
||||
Assert.Equal(("DOTNET_RUNNING_IN_CONTAINER", "DOTNET_RUNNING_IN_CONTAINER"), (settings.LockedBy["HttpPort"], settings.LockedBy["HttpsPort"]));
|
||||
|
||||
using (var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", settings with { HttpPort = 8087, HttpsPort = 8444 }, ProtocolJson.Default.ServerSettingsDto))
|
||||
Assert.Equal("HttpPort", (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
|
||||
// The ports stay as they are, which is valid whatever they are; the host ports go in the public ones.
|
||||
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", settings with { PublicHttpPort = 8087, PublicHttpsPort = 8444 },
|
||||
ProtocolJson.Default.ServerSettingsDto))
|
||||
Assert.False((await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).RestartRequired);
|
||||
Assert.Equal((8087, 8444), (server.Options.PublicHttpPort!.Value, server.Options.PublicHttpsPort!.Value));
|
||||
var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject();
|
||||
Assert.False(file.ContainsKey("HttpPort") || file.ContainsKey("HttpsPort"), "the container's ports are never written");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AContainerIgnoresListeningPortsSavedEarlier()
|
||||
{
|
||||
var root = context.CreateTempDirectory("container");
|
||||
File.WriteAllText(Path.Combine(root, "server.json"), """{ "HttpPort": 8087, "HttpsPort": 8444, "PublicHttpsPort": 8444 }""");
|
||||
Dictionary<string, string?> Env(params (string Name, string Value)[] more)
|
||||
{
|
||||
var env = new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" };
|
||||
foreach (var (name, value) in more) env[name] = value;
|
||||
return env;
|
||||
}
|
||||
|
||||
// Outside a container the saved ports apply, as before.
|
||||
var host = ServerOptions.Load(Env());
|
||||
Assert.Equal((8087, 8444, false, false), (host.HttpPort, host.HttpsPort, host.InContainer, host.IgnoredSavedPorts));
|
||||
|
||||
var container = ServerOptions.Load(Env((ServerOptions.ContainerVariable, "true")));
|
||||
Assert.Equal((8080, 8443, true, true), (container.HttpPort, container.HttpsPort, container.InContainer, container.IgnoredSavedPorts));
|
||||
Assert.Equal((int?)8444, container.PublicHttpsPort);
|
||||
|
||||
// A variable still sets a container's port.
|
||||
var variable = ServerOptions.Load(Env((ServerOptions.ContainerVariable, "true"), ("CHRONOS_HTTPS_PORT", "9443")));
|
||||
Assert.Equal((8080, 9443), (variable.HttpPort, variable.HttpsPort));
|
||||
Assert.Equal("CHRONOS_HTTPS_PORT", variable.LockedBy["HttpsPort"]);
|
||||
|
||||
Assert.False(ServerOptions.Load(Env((ServerOptions.ContainerVariable, "false"))).InContainer);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AContainerRemovesListeningPortsSavedEarlierAtTheNextSave()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
// As ServerOptions.Load leaves a container whose server.json held ports.
|
||||
o.InContainer = true;
|
||||
o.IgnoredSavedPorts = true;
|
||||
Directory.CreateDirectory(o.DataPath);
|
||||
File.WriteAllText(o.SettingsFile, """{ "HttpPort": 8087, "HttpsPort": 8444, "ServerName": "NAS" }""");
|
||||
});
|
||||
var admin = await server.AdminAsync();
|
||||
// Nothing changed, and still the saved ports go: the panel cannot edit them, so it could never remove them otherwise.
|
||||
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", await SettingsAsync(admin), ProtocolJson.Default.ServerSettingsDto))
|
||||
await saved.ExpectAsync(HttpStatusCode.OK);
|
||||
var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject();
|
||||
Assert.False(file.ContainsKey("HttpPort") || file.ContainsKey("HttpsPort"), "the saved listening ports are removed");
|
||||
Assert.Equal("NAS", file["ServerName"]!.GetValue<string>());
|
||||
Assert.False(server.Options.IgnoredSavedPorts);
|
||||
var restarted = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["CHRONOS_DATA_PATH"] = server.Options.DataPath,
|
||||
["CHRONOS_DB"] = "postgres",
|
||||
[ServerOptions.ContainerVariable] = "true",
|
||||
});
|
||||
Assert.False(restarted.IgnoredSavedPorts, "the next start no longer warns");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASettingsAnswerStaysReadableInTheShapeBeforePublicPorts()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.PublicHttpsPort = 8444);
|
||||
var admin = await server.AdminAsync();
|
||||
using var read = await admin.GetAsync("/api/v1/server/settings");
|
||||
var json = await read.Content.ReadAsStringAsync();
|
||||
var older = Assert.NotNull(JsonSerializer.Deserialize<SettingsBeforePublicPorts>(json, new JsonSerializerOptions(JsonSerializerDefaults.Web)));
|
||||
var current = Assert.NotNull(JsonSerializer.Deserialize(json, ProtocolJson.Default.ServerSettingsDto));
|
||||
Assert.Equal((current.ServerName, current.HttpsPort, current.Parallelism, current.Logs.FileLevel), (older.ServerName, older.HttpsPort, older.Parallelism, older.Logs.FileLevel));
|
||||
Assert.Equal((int?)8444, current.PublicHttpsPort);
|
||||
|
||||
// And the shape before them deserialises into the current one, the new members at their defaults.
|
||||
var old = JsonSerializer.Serialize(older, new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||||
var parsed = Assert.NotNull(JsonSerializer.Deserialize(old, ProtocolJson.Default.ServerSettingsDto));
|
||||
Assert.Equal(((int?)null, (int?)null, false), (parsed.PublicHttpPort, parsed.PublicHttpsPort, parsed.InContainer));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ThePanelShowsThePublicPortsAndTheClientAddress()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var page = await server.Client.GetStringAsync("/admin/pages/settings.js");
|
||||
foreach (var part in new[] { "publicPort(\"publicHttpPort\"", "publicPort(\"publicHttpsPort\"", "field(\"clientAddress\"", "id=\"copy-address\"",
|
||||
"Admin.Settings.ContainerPort.Tip", "settings.publicHttpsPort ?? settings.httpsPort", "location.origin", "navigator.clipboard.writeText",
|
||||
// The port the page came through over HTTPS wins over a saved one, is offered for the Public HTTPS port,
|
||||
// and saving another one asks first (the HTTPS redirect follows it at once).
|
||||
"pagePort() ?? savedHttps()", "id=\"use-page-port\"", "Admin.Settings.UsePagePort", "Admin.Settings.PortChangeTitle", "confirmDialog({" })
|
||||
Assert.Contains(part, page);
|
||||
}
|
||||
|
||||
private static async Task<ServerSettingsDto> SettingsAsync(HttpClient admin)
|
||||
{
|
||||
using var read = await admin.GetAsync("/api/v1/server/settings");
|
||||
return await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
|
||||
}
|
||||
|
||||
/// <summary>Plain HTTP to the panel from another machine, as the owner's browser sends it.</summary>
|
||||
private static DefaultHttpContext AdminRequest()
|
||||
{
|
||||
var request = new DefaultHttpContext();
|
||||
request.Connection.RemoteIpAddress = IPAddress.Parse("192.168.30.50");
|
||||
request.Request.Scheme = "http";
|
||||
request.Request.Host = new HostString("192.168.30.23", 8087);
|
||||
request.Request.Path = "/admin/";
|
||||
return request;
|
||||
}
|
||||
|
||||
/// <summary><see cref="ServerSettingsDto"/> as it was before owner review 3.</summary>
|
||||
private sealed record SettingsBeforePublicPorts(
|
||||
string ServerName,
|
||||
int HttpPort,
|
||||
int HttpsPort,
|
||||
string TlsMode,
|
||||
string? TlsCert,
|
||||
string? TlsKey,
|
||||
string Language,
|
||||
int Parallelism,
|
||||
bool PriorityQueue,
|
||||
IReadOnlyList<JobPriorityDto> JobPriorities,
|
||||
bool Discovery,
|
||||
long MaxUploadBytes,
|
||||
int ChunkSizeBytes,
|
||||
int JobHistoryDays,
|
||||
int TokenLifetimeDays,
|
||||
int UploadRetentionHours,
|
||||
LogSettingsDto Logs,
|
||||
IReadOnlyList<string> Locked,
|
||||
IReadOnlyDictionary<string, string> LockedBy,
|
||||
bool RestartRequired,
|
||||
bool ProxyWarning);
|
||||
}
|
||||
@@ -22,33 +22,32 @@ dotnet run --project src/Chronos.Tools -- screenshots diff out/screenshots --out
|
||||
## The pictures are reproducible
|
||||
|
||||
The capture runs on sample data whose clock stands at `SampleData.Now` (2026-10-02 10:18 UTC), in English with English
|
||||
formats and with animations off, so the same code draws the same pixels on any day. Two things still come from the
|
||||
machine:
|
||||
|
||||
- the time zone: times are shown in local time, and the baselines are made on the Windows runner of CI's `windows` job
|
||||
(`WINDOWS_RUNNER`), which compares them in its own time zone;
|
||||
- a few measured values: the server's response time and the time and duration of the last sync comparison. They change
|
||||
a few dozen pixels, well inside the allowed fraction.
|
||||
formats and with animations off, so the same code draws the same pixels on any day. What the screens measure on
|
||||
the machine is shown as fixed sample values while the clock is frozen (`AppClock`): free space (1.2 TB), the
|
||||
server's response time (12 ms) and the time and duration of the last sync comparison. Two things still come from the
|
||||
machine: the time zone (times are shown in local time; the baselines are made in the development PC's, Europe/Rome,
|
||||
which the Windows runner must share) and the fonts and scaling of Windows itself.
|
||||
|
||||
## Adding or updating baselines
|
||||
|
||||
Take them from CI, never from another PC (fonts, scaling and the time zone differ). On the Windows runner, every
|
||||
same-repository pull request pushes its screenshots to the `ci-screenshots` branch (one commit, the PNGs at its root).
|
||||
After checking them:
|
||||
Capture them on the development PC, the one where the Windows runner is registered (fonts, scaling and the time zone
|
||||
differ per machine), from a Release build of the branch that changes the screens:
|
||||
|
||||
```
|
||||
git fetch origin ci-screenshots
|
||||
git worktree add ../ci-screenshots origin/ci-screenshots
|
||||
dotnet run --project src/Chronos.Tools -- screenshots accept ../ci-screenshots
|
||||
git worktree remove ../ci-screenshots
|
||||
dotnet build Chronos.slnx -c Release
|
||||
src/Chronos.App/bin/Release/net10.0-windows/Chronos.exe --capture out/screenshots
|
||||
src/Chronos.Uploader/bin/Release/net10.0-windows/Chronos.Uploader.exe --capture out/screenshots
|
||||
src/Chronos.Setup/bin/Release/net10.0-windows/Chronos.Setup.exe --capture out/screenshots
|
||||
dotnet run --project src/Chronos.Tools -- screenshots diff out/screenshots
|
||||
dotnet run --project src/Chronos.Tools -- screenshots accept out/screenshots
|
||||
```
|
||||
|
||||
`screenshots accept <dir>` copies every PNG of `<dir>` here. Commit only the screens whose change is intended, and delete
|
||||
the baseline of a screen that no longer exists.
|
||||
the baseline of a screen that no longer exists. If the Windows runner is ever registered on another PC, accept a new
|
||||
set captured there in one commit.
|
||||
|
||||
## The first baselines
|
||||
|
||||
None is committed yet. Screenshots captured before the capture was made reproducible cannot serve: their times and
|
||||
dates follow the moment they were taken (a job finished at "12:18 AM", sample sequences dated from that day). The first
|
||||
baselines are accepted, all at once, from the `ci-screenshots` commit of the first green `windows` job run whose code
|
||||
captures at `SampleData.Now`; from that commit on, every screen is gated.
|
||||
The first set (156 screens) was captured on the development PC on 2026-11-04 (owner review 3, R2), at `SampleData.Now`,
|
||||
and is committed with the ports fix of `v0.1.0-rc.9`. Until a Windows runner is registered, CI skips the `windows` job
|
||||
and nothing compares them: run `screenshots diff` locally before a pull request that touches a screen.
|
||||
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 64 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 171 KiB |
|
After Width: | Height: | Size: 166 KiB |
|
After Width: | Height: | Size: 173 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 236 KiB |
|
After Width: | Height: | Size: 229 KiB |
|
After Width: | Height: | Size: 107 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
After Width: | Height: | Size: 210 KiB |
|
After Width: | Height: | Size: 208 KiB |
|
After Width: | Height: | Size: 211 KiB |
|
After Width: | Height: | Size: 208 KiB |
|
After Width: | Height: | Size: 275 KiB |
|
After Width: | Height: | Size: 270 KiB |
|
After Width: | Height: | Size: 420 KiB |
|
After Width: | Height: | Size: 400 KiB |
|
After Width: | Height: | Size: 272 KiB |
|
After Width: | Height: | Size: 316 KiB |
|
After Width: | Height: | Size: 309 KiB |
|
After Width: | Height: | Size: 226 KiB |
|
After Width: | Height: | Size: 220 KiB |
|
After Width: | Height: | Size: 249 KiB |
|
After Width: | Height: | Size: 244 KiB |
|
After Width: | Height: | Size: 266 KiB |
|
After Width: | Height: | Size: 259 KiB |
|
After Width: | Height: | Size: 104 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 114 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
After Width: | Height: | Size: 107 KiB |
|
After Width: | Height: | Size: 111 KiB |
|
After Width: | Height: | Size: 107 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
After Width: | Height: | Size: 112 KiB |
|
After Width: | Height: | Size: 228 KiB |
|
After Width: | Height: | Size: 223 KiB |
|
After Width: | Height: | Size: 241 KiB |
|
After Width: | Height: | Size: 235 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 90 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 86 KiB |
|
After Width: | Height: | Size: 80 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 86 KiB |
|
After Width: | Height: | Size: 80 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 71 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 75 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 109 KiB |
|
After Width: | Height: | Size: 107 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 112 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 84 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 9.5 KiB |