Review fixes on top of the public ports change (owner review 3): - Settings > Network and TLS: opened over HTTPS, the client address uses the port the page came through (a container's 8443 published as 8444 with Public HTTPS port still empty showed the wrong 8443), and a "Use <port>" button fills that port in. Saving a Public HTTPS port other than the page's asks first, since the HTTPS redirect follows it at once and a typo would lock the panel's link out. - GetInfoAsync tells Chronos from other services by stricter rules on both the trusted and the untrusted-certificate path: any redirect, any answer that is not JSON, more than 1 MB, or an error without the X-Chronos-Api header is not Chronos. Another service's certificate is no longer offered for trust after a cross-scheme redirect, an error page or a JSON 401/403/404, and a JSON 401 over HTTP no longer reads as a wrong password. - The HTTP port typed without a scheme (TLS to a plain HTTP port) now gives the not-Chronos error instead of "the server did not answer". - The Uploader's certificate question names the address with its port. - A link-local IPv6 address with a zone index is refused instead of losing it. - In a container, the first save of the settings removes HttpPort/HttpsPort from server.json, so the start-up warning stops; the warning says so. - Guide, README, compose and template: with network type Host the mappings do nothing and CHRONOS_HTTP_PORT / CHRONOS_HTTPS_PORT move the listening ports off ones another service uses; the template overview is back to two sentences. - BRIEF, DECISIONS and CHANGELOG updated; en/it strings added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
269 lines
16 KiB
C#
269 lines
16 KiB
C#
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);
|
|
}
|