Files
Chronos/tests/Chronos.App.Tests/Server/ConnectFlowTests.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

265 lines
12 KiB
C#

using System.Net;
using System.Net.Http;
using Chronos.App.Server;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Testing;
namespace Chronos.App.Tests.Server;
public sealed class ConnectFlowTests
{
private const string Fingerprint = "9A:3C:71:E0:5B:12:C4:88:0F:6D:2A:91:E7:44:B3:5C:19:D2:6F:80:A1:3E:57:C9:0B:64:F8:2D:93:A6:71:CE";
[Test]
public async Task AnUnknownCertificateIsConfirmedBeforeThePasswordIsSent()
{
var server = new FakeServer { SelfSigned = true };
var trust = new MemoryTrust();
using var flow = new ConnectFlow(server, trust);
Assert.Equal(ConnectStep.AwaitingTrust, await flow.ProbeAsync("nas.local:8443"));
Assert.Equal(Fingerprint, flow.PendingFingerprint);
Assert.Equal(new Uri("https://nas.local:8443/"), flow.Address);
// The password cannot be sent while the certificate waits for a decision.
Assert.Equal(ConnectStep.AwaitingTrust, await flow.SignInAsync("alberto", "secret"));
Assert.Equal(0, server.Logins);
Assert.Equal(ConnectStep.AwaitingCredentials, await flow.ConfirmTrustAsync(true));
Assert.Contains(Fingerprint, trust.Fingerprints);
Assert.Equal("https://nas.local:8443", trust.Servers.Single());
Assert.Equal("Studio NAS", flow.Info!.Name);
Assert.NotNull(flow.Latency);
Assert.Equal(ConnectStep.Connected, await flow.SignInAsync("alberto", "secret"));
Assert.Equal(1, server.Logins);
Assert.Equal("token-1", flow.Token);
Assert.Equal("alberto", flow.User!.Username);
Assert.NotNull(flow.Api);
// Every client got the trust list current at its creation.
Assert.Empty(server.Created[0]);
Assert.Contains(Fingerprint, server.Created[^1]);
}
[Test]
public async Task RejectingTheCertificateSendsNothing()
{
var server = new FakeServer { SelfSigned = true };
using var flow = new ConnectFlow(server, new MemoryTrust());
await flow.ProbeAsync("https://nas.local:8443");
Assert.Equal(ConnectStep.Failed, await flow.ConfirmTrustAsync(false));
Assert.Equal(ConnectError.Untrusted, flow.Error);
Assert.Equal(ConnectStep.Failed, await flow.SignInAsync("alberto", "secret"));
Assert.Equal(0, server.Logins);
Assert.Null(flow.Token);
}
[Test]
public async Task APubliclyValidCertificateNeedsNoQuestion()
{
var server = new FakeServer();
using var flow = new ConnectFlow(server, new MemoryTrust());
Assert.Equal(ConnectStep.AwaitingCredentials, await flow.ProbeAsync("https://chronos.example.com"));
Assert.Null(flow.PendingFingerprint);
}
[Test]
public async Task AWrongPasswordReturnsToTheForm()
{
var server = new FakeServer { Password = "right" };
using var flow = new ConnectFlow(server, new MemoryTrust());
await flow.ProbeAsync("nas.local");
Assert.Equal(ConnectStep.AwaitingCredentials, await flow.SignInAsync("alberto", "wrong"));
Assert.Equal(ConnectError.BadCredentials, flow.Error);
Assert.Equal(ConnectStep.Connected, await flow.SignInAsync("alberto", "right"));
Assert.Equal(ConnectError.None, flow.Error);
}
[Theory]
[Case("", ConnectError.InvalidAddress)]
[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());
Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync(address));
Assert.Equal(error, flow.Error);
Assert.Null(flow.Api);
}
[Test]
public async Task ASavedSessionIsRestoredWithoutAPassword()
{
var server = new FakeServer { SelfSigned = true };
var trust = new MemoryTrust();
trust.Trust("https://nas.local:8443", Fingerprint);
using var flow = new ConnectFlow(server, trust);
Assert.Equal(ConnectStep.Connected, await flow.RestoreAsync("https://nas.local:8443", "token-7"));
Assert.Equal(0, server.Logins);
Assert.Equal("token-7", flow.Token);
Assert.Equal("token-7", server.LastTokenSeen);
}
[Test]
public async Task AnExpiredTokenAsksForTheLoginAgain()
{
var server = new FakeServer { ValidToken = "fresh" };
using var flow = new ConnectFlow(server, new MemoryTrust());
Assert.Equal(ConnectStep.AwaitingCredentials, await flow.RestoreAsync("nas.local", "stale"));
Assert.Equal(ConnectError.SessionExpired, flow.Error);
Assert.Null(flow.Token);
}
[Test]
public async Task AChangedCertificateNeverReceivesTheSavedToken()
{
var server = new FakeServer { SelfSigned = true };
var trust = new MemoryTrust();
trust.Trust("https://nas.local:8443", "00:11:22"); // trusted earlier: a different certificate
using var flow = new ConnectFlow(server, trust);
Assert.Equal(ConnectStep.AwaitingTrust, await flow.RestoreAsync("nas.local:8443", "token-7"));
Assert.Equal(ConnectError.CertificateChanged, flow.Error);
Assert.Null(server.LastTokenSeen);
Assert.Null(flow.Token);
}
[Test]
public async Task SignOutForgetsTheSession()
{
var server = new FakeServer();
using var flow = new ConnectFlow(server, new MemoryTrust());
await flow.ProbeAsync("nas.local");
await flow.SignInAsync("alberto", "secret");
var changes = 0;
flow.Changed += (_, _) => changes++;
await flow.SignOutAsync();
Assert.Equal(1, server.Logouts);
Assert.Equal(ConnectStep.Idle, flow.Step);
Assert.Null(flow.Token);
Assert.Null(flow.Api);
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));
Assert.Equal("http://10.0.0.5:8080/chronos/", b.ToString());
Assert.False(ServerAddress.TryParse(" ", out _));
Assert.False(ServerAddress.TryParse("ftp://nas", out _));
Assert.Equal("https://nas.local:8443", ServerAddress.Display(a));
Assert.Equal("https://nas.local:8443", ServerAddress.Display("https://nas.local:8443/"));
}
private sealed class MemoryTrust : ITrustStore
{
private readonly List<string> _fingerprints = [];
public List<string> Servers { get; } = [];
public IReadOnlyCollection<string> Fingerprints => [.. _fingerprints];
public void Trust(string server, string fingerprint)
{
Servers.Add(server);
_fingerprints.Add(fingerprint);
}
}
/// <summary>A server with configurable behaviour, reached through clients that pin certificates like the real one.</summary>
private sealed class FakeServer : IServerApiFactory
{
public bool SelfSigned { get; init; }
public string Password { get; init; } = "secret";
public string? ValidToken { get; init; }
public int Logins { get; set; }
public int Logouts { get; set; }
public string? LastTokenSeen { get; set; }
public List<IReadOnlyCollection<string>> Created { get; } = [];
public IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints)
{
Created.Add(trustedFingerprints);
return new Client(this, baseAddress, trustedFingerprints);
}
private sealed class Client(FakeServer server, Uri baseAddress, IReadOnlyCollection<string> trusted) : IServerApi
{
public Uri BaseAddress { get; } = baseAddress;
public string? Token { get; set; }
public Task<ServerInfo> GetInfoAsync(CancellationToken ct)
{
Handshake();
return Task.FromResult(new ServerInfo("Studio NAS", "1.3.0", 1, [], server.SelfSigned ? Fingerprint : null, [], new ServerLimits(0, 0)));
}
public Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct)
{
Handshake();
server.Logins++;
if (password != server.Password) throw new ChronosApiException(HttpStatusCode.Unauthorized, new ApiError("bad_credentials", "Wrong"));
return Task.FromResult(new LoginResponse("token-" + server.Logins, User(username), false, DateTimeOffset.UtcNow.AddDays(1)));
}
public Task<UserDto> MeAsync(CancellationToken ct)
{
Handshake();
server.LastTokenSeen = Token;
if (server.ValidToken is { } valid && Token != valid) throw new ChronosApiException(HttpStatusCode.Unauthorized, new ApiError("expired", "Expired"));
return Task.FromResult(User("alberto"));
}
public Task LogoutAsync(CancellationToken ct)
{
server.Logouts++;
return Task.CompletedTask;
}
public void Dispose()
{
}
/// <summary>What TLS would do: a self-signed certificate is accepted only when pinned.</summary>
private void Handshake()
{
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);
}
private static UserDto User(string name) =>
new(Guid.Empty, name, null, "editor", 0, 5_000_000_000_000, 2_100_000_000_000, false, false, DateTimeOffset.UtcNow, null);
}
}
}