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]); } /// Owner review 5, #67: this PC's own shared library is refused before the trust question, and once trusted. [Test] public async Task ThisPcsOwnSharedLibraryIsRefused() { var server = new FakeServer { SelfSigned = true }; var trust = new MemoryTrust(); using var flow = new ConnectFlow(server, trust) { IsOwnLibrary = (fingerprint, _) => fingerprint == Fingerprint }; Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("localhost:8443")); Assert.Equal(ConnectError.OwnLibrary, flow.Error); Assert.Null(flow.PendingFingerprint); Assert.Empty(trust.Fingerprints); trust.Trust("https://localhost:8443", Fingerprint); Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("localhost:8443")); Assert.Equal(ConnectError.OwnLibrary, flow.Error); Assert.Equal(0, server.Logins); flow.IsOwnLibrary = (_, _) => false; Assert.Equal(ConnectStep.AwaitingCredentials, await flow.ProbeAsync("localhost:8443")); } [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 _fingerprints = []; public List Servers { get; } = []; public IReadOnlyCollection Fingerprints => [.. _fingerprints]; public void Trust(string server, string fingerprint) { Servers.Add(server); _fingerprints.Add(fingerprint); } } /// A server with configurable behaviour, reached through clients that pin certificates like the real one. 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> Created { get; } = []; public IServerApi Create(Uri baseAddress, IReadOnlyCollection trustedFingerprints) { Created.Add(trustedFingerprints); return new Client(this, baseAddress, trustedFingerprints); } private sealed class Client(FakeServer server, Uri baseAddress, IReadOnlyCollection trusted) : IServerApi { public Uri BaseAddress { get; } = baseAddress; public string? Token { get; set; } public Task 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 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 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() { } /// What TLS would do: a self-signed certificate is accepted only when pinned. 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); } } }