Files
Chronos/tests/Chronos.App.Tests/Server/ConnectFlowTests.cs
T
Alby96andClaude Opus 5.5 5f27a86406
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s
refactor!: rename Titano to Chronos and move CI and releases to Gitea
The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout. The release cross-compiles the Windows programs, checks their
  icon, version and DPI manifest, packs installers and zips, publishes the
  Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only
  tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow) and
  pe-check.

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 11:34:48 +02:00

239 lines
10 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)]
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 void AddressesAreNormalised()
{
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"));
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);
}
}
}