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; /// /// 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. /// [Category("server")] public sealed class ServerIdentityTests(TestContext context) { /// Answers of another service, each under its own path. private static readonly string[] OtherAnswers = [ "html/", "redirect/", "away/", "empty/", "json/", "unauthorized/", "missing/", "text/", "failed/", "gateway/", "json401/", "json403/", "json404/", "huge/", "hugejson/", ]; [Test] public async Task AnAddressThatAnswersAsSomethingElseIsNotAChronosServer() { await using var other = await OtherService.StartAsync(context); // Over HTTP, and over HTTPS behind the service's own certificate, which nobody trusted. foreach (var address in new[] { other.Http, other.Https }.SelectMany(root => OtherAnswers.Select(path => new Uri(root, path)))) { using var client = new ChronosClient(address, new CertificatePinning([]), "tests"); var error = await Assert.ThrowsAsync(() => client.GetInfoAsync(context.Cancellation), address.ToString()); Assert.Equal(address, error.Address, address.ToString()); } Assert.Equal(0, other.Authorized, "no request carried credentials"); } [Test] public async Task TheHttpPortTypedWithoutASchemeIsNotAChronosServer() { // "192.168.30.23:8087", the port of the panel's link: HTTPS to a port that answers plain HTTP. await using var server = await TestServer.StartAsync(context); Assert.True(ChronosAddress.TryParse($"127.0.0.1:{server.HttpBase.Port}", out var typed)); using var client = new ChronosClient(typed, new CertificatePinning([]), "tests"); var error = await Assert.ThrowsAsync(() => client.GetInfoAsync(context.Cancellation)); Assert.Equal(typed, error.Address); await using var other = await OtherService.StartAsync(context); using var otherClient = new ChronosClient(new UriBuilder(other.Http) { Scheme = "https", Port = other.Http.Port }.Uri, new CertificatePinning([]), "tests"); await Assert.ThrowsAsync(() => otherClient.GetInfoAsync(context.Cancellation)); // A port where nothing answers is still unreachable, not another service. var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); listener.Start(); var closed = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); using var nobody = new ChronosClient(new Uri($"https://127.0.0.1:{closed}/"), new CertificatePinning([]), "tests"); await Assert.ThrowsAsync(() => nobody.GetInfoAsync(context.Cancellation)); } [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(() => client.GetInfoAsync(context.Cancellation)); // Nothing was trusted, and the next request still refuses the certificate. await Assert.ThrowsAsync(() => client.MeAsync(context.Cancellation)); Assert.Equal(0, other.Authorized, "no request carried credentials"); } [Test] public async Task AChronosErrorFromTheInfoIsReportedAsThatError() { // Chronos's own error (its header and code) is read once to tell it from other services: it must still come back // as the server's error, and an unknown certificate still asks for trust. await using var other = await OtherService.StartAsync(context); foreach (var (path, status, code) in new[] { ("chronos500/", HttpStatusCode.InternalServerError, "internal"), ("chronos400/", HttpStatusCode.BadRequest, "bad_request") }) { using var plain = new ChronosClient(new Uri(other.Http, path), new CertificatePinning([]), "tests"); var error = await Assert.ThrowsAsync(() => plain.GetInfoAsync(context.Cancellation), path); Assert.Equal(status, error.Status, path); Assert.Equal(code, error.Error.Code, path); using var untrusted = new ChronosClient(new Uri(other.Https, path), new CertificatePinning([]), "tests"); await Assert.ThrowsAsync(() => untrusted.GetInfoAsync(context.Cancellation), path); } } [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(() => 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); } /// A web service that is not Chronos, on HTTP and on HTTPS with a self-signed certificate of its own. private sealed class OtherService : IAsyncDisposable { private readonly WebApplication _app; private int _authorized; private OtherService(WebApplication app) { _app = app; var addresses = app.Services.GetRequiredService().Features.Get()!.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; } /// Requests that carried an Authorization header. public int Authorized => Volatile.Read(ref _authorized); public static async Task 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("NAS", "text/html")); app.MapGet("/redirect/api/v1/server/info", () => Results.Redirect("/login")); app.MapGet("/login", () => Results.Content("
Sign in
", "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)); // An absolute redirect to plain HTTP, which a client never follows from HTTPS. app.MapGet("/away/api/v1/server/info", (HttpContext http) => Results.Redirect($"http://{http.Request.Host}/login")); app.MapGet("/text/api/v1/server/info", () => Results.Text("ok")); app.MapGet("/failed/api/v1/server/info", () => Results.Content("Error", "text/html", statusCode: StatusCodes.Status500InternalServerError)); app.MapGet("/gateway/api/v1/server/info", () => Results.Content("Bad gateway", "text/html", statusCode: StatusCodes.Status502BadGateway)); // Errors in JSON with a code of their own, as many web services write them. foreach (var (path, status) in new[] { ("json401", 401), ("json403", 403), ("json404", 404) }) app.MapGet($"/{path}/api/v1/server/info", () => Results.Content("""{"code":"denied","message":"Sign in"}""", "application/json", statusCode: status)); // Errors as Chronos writes them: its header and a code of its own. foreach (var (path, status, code) in new[] { ("chronos500", 500, "internal"), ("chronos400", 400, "bad_request") }) app.MapGet($"/{path}/api/v1/server/info", (HttpContext http) => { http.Response.Headers[ApiVersion.Header] = "1"; return Results.Content($$"""{"code":"{{code}}","message":"Failed"}""", "application/json", statusCode: status); }); // More than a server info ever holds. app.MapGet("/huge/api/v1/server/info", () => Results.Content("" + new string('x', 2 << 20), "text/html")); app.MapGet("/hugejson/api/v1/server/info", () => Results.Content("{\"name\":\"" + new string('x', 2 << 20) + "\"}", "application/json")); await app.StartAsync(context.Cancellation); service = new OtherService(app); return service; } public async ValueTask DisposeAsync() { await _app.StopAsync(); await _app.DisposeAsync(); } } }