Files
Chronos/tests/Chronos.Server.Tests/Api/ServerIdentityTests.cs
T
Alby96andClaude Opus 5.5 369e754bec fix(server): public ports as settings, container port lock and client address; clients default to 8443 and name non-Chronos servers
The owner's Uploader could not connect: the panel showed the container's
listening ports (8080/8443) as if clients used them, the public ports were
only environment variables (CHRONOS_PUBLIC_HTTP_PORT not even in the Unraid
template), and the clients mapped a bare host to 443, where another service
answered.

- Public HTTP/HTTPS ports are settings (server.json, or locked by
  CHRONOS_PUBLIC_*) and apply at once; ServerSettingsDto gains appended
  PublicHttpPort, PublicHttpsPort and InContainer members.
- In a container the listening ports are fixed by the template: locked in the
  panel, and saved values from earlier versions are ignored with a warning.
- Settings > Network and TLS shows the client address with a Copy button; the
  discovery tooltip says a container needs network type Host.
- ChronosAddress (shared by Chronos and the Uploader): no scheme and no port is
  https on 8443, https:// keeps 443, a typed port is kept, IPv6 is bracketed.
- GetInfoAsync throws NotChronosServerException for answers that are not a
  Chronos server; another service's certificate is never offered for trust
  and no credentials are sent to it. Both clients name the address asked.
- Unraid template, compose file, user guide, README, BRIEF, DECISIONS,
  CHANGELOG (with an Unraid upgrade note) and ARCHITECTURE updated; en/it
  strings added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:53:49 +01:00

125 lines
6.1 KiB
C#

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)
{
[Test]
public async Task AnAddressThatAnswersAsSomethingElseIsNotAChronosServer()
{
await using var other = await OtherService.StartAsync(context);
foreach (var path in new[] { "html/", "redirect/", "empty/", "json/", "unauthorized/", "missing/" })
{
var address = new Uri(other.Http, path);
using var client = new ChronosClient(address, new CertificatePinning([]), "tests");
var error = await Assert.ThrowsAsync<NotChronosServerException>(() => client.GetInfoAsync(context.Cancellation));
Assert.Equal(address, error.Address, path);
}
}
[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 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));
await app.StartAsync(context.Cancellation);
service = new OtherService(app);
return service;
}
public async ValueTask DisposeAsync()
{
await _app.StopAsync();
await _app.DisposeAsync();
}
}
}