Files
Chronos/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs
T
Alby96 0e52bf0e1b feat(admin): upload photos from the web panel
Owner review 2, R3: the panel can add photos to an existing or a new
sequence without the desktop app. upload.js is a dialog the library pages
open (openUpload({ api, sequence, onDone })): file picker or drag and drop
(folders are counted and left out: whole-folder import stays on the
desktop), per-photo state, a total bar, Cancel that deletes the started
uploads, and a leave-page guard while sending. Each photo is hashed in a
same-origin module worker with an in-house incremental SHA-256 (8 MiB
reads; crypto.subtle cannot hash in pieces), which runs the FIPS 180-4
known answers and a crypto.subtle cross-check before its first hash and
refuses to hash on any mismatch; the server verifies the hash again.
Chunks go through api.putBytes with the session's CSRF header, two files
and two chunks at a time, retrying no answer, 429 and 503; quota, space
and permission refusals stop the run with the server's message, and a
photo deleted from the sequence shows as deleted before.

server/info now lists the photo extensions the archive files, so the
dialog offers and sends only those. The CSP already allows the worker
(worker-src falls back to script-src 'self'); tests pin that, the module
walk follows the worker, and a browser-shaped upload runs end to end
through the cookie session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c64c60ab8bb41c102182e284177ac04a56bf1058)
2026-10-27 10:52:40 +01:00

334 lines
18 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Protocol;
using Chronos.Server.Hosting;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
[Category("server")]
public sealed partial class SystemEndpointTests(TestContext context)
{
[Test]
public async Task HealthReportsOk()
{
await using var server = await TestServer.StartAsync(context);
var health = await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus);
Assert.Equal("ok", Assert.NotNull(health).Status);
Assert.Equal("ok", health.Checks["archive"]);
}
[Test]
public async Task ServerInfoCarriesFingerprintAndApiHeader()
{
await using var server = await TestServer.StartAsync(context);
using var response = await server.Client.GetAsync("/api/v1/server/info");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("1", response.Headers.GetValues(ApiVersion.Header).Single());
var info = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ServerInfo);
Assert.Equal(1, Assert.NotNull(info).ApiVersion);
Assert.Equal(95, Assert.NotNull(info.TlsFingerprint).Length); // 32 bytes as XX: pairs
}
[Test]
public async Task HttpsServesTheAdvertisedCertificate()
{
await using var server = await TestServer.StartAsync(context);
var info = await server.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo);
string? seen = null;
using var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, cert, _, _) =>
{
seen = cert is null ? null : string.Join(':', cert.GetCertHash(System.Security.Cryptography.HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)));
return true;
},
};
using var https = new HttpClient(handler) { BaseAddress = Assert.NotNull(server.HttpsBase) };
using var response = await https.GetAsync("/health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Assert.NotNull(info).TlsFingerprint, seen);
}
[Test]
public async Task CertificateIsReusedAcrossRestarts()
{
var root = context.CreateTempDirectory("restart");
string? first;
await using (var a = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data")))
first = (await a.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint;
await using var b = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data"));
var second = (await b.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint;
Assert.Equal(first, second);
}
[Test]
public async Task UnknownApiRouteReturnsJsonError()
{
await using var server = await TestServer.StartAsync(context);
using var response = await server.Client.GetAsync("/api/v1/does-not-exist");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
var error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError);
Assert.Equal("not_found", Assert.NotNull(error).Code);
}
[Test]
public async Task AdminPanelIsServedWithEtags()
{
await using var server = await TestServer.StartAsync(context);
using var redirect = await new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { BaseAddress = server.HttpBase }.GetAsync("/admin");
Assert.Equal(HttpStatusCode.Redirect, redirect.StatusCode);
using var page = await server.Client.GetAsync("/admin/");
Assert.Equal(HttpStatusCode.OK, page.StatusCode);
Assert.Contains("app.js", await page.Content.ReadAsStringAsync());
var etag = page.Headers.ETag;
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin/");
request.Headers.IfNoneMatch.Add(Assert.NotNull(etag));
using var cached = await server.Client.SendAsync(request);
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
}
[Test]
public async Task PlainHttpFromAnotherMachineGoesToThePublicHttpsPort()
{
// The container listens on 8443, published on the host as 18443 (BRIEF §19.6: the template's ports are editable).
await using var server = await TestServer.StartAsync(context, o => o.PublicHttpsPort = 18443);
var kestrel = server.Services.GetRequiredService<IServer>();
var request = AdminRequest(IPAddress.Parse("10.0.0.7"));
Assert.Equal("https://10.0.0.5:18443/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
server.Options.PublicHttpsPort = null;
Assert.Equal($"https://10.0.0.5:{Assert.NotNull(server.HttpsBase).Port}/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
Assert.Null(AdminPanel.HttpsLocation(AdminRequest(IPAddress.Loopback), server.Options, kestrel));
}
private static DefaultHttpContext AdminRequest(IPAddress from)
{
var request = new DefaultHttpContext();
request.Connection.RemoteIpAddress = from;
request.Request.Scheme = "http";
request.Request.Host = new HostString("10.0.0.5", 18080);
request.Request.Path = "/admin/";
request.Request.QueryString = new QueryString("?page=jobs");
return request;
}
[Test]
public async Task AdminPanelRunsUnderAStrictPolicyAndIsNeverFramed()
{
await using var server = await TestServer.StartAsync(context);
foreach (var path in new[] { "/admin/", "/admin/app.js", "/admin/admin.css" })
{
using var response = await server.Client.GetAsync(path);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var policy = string.Join(' ', response.Headers.GetValues("Content-Security-Policy"));
foreach (var directive in new[] { "default-src 'self'", "script-src 'self'", "style-src 'self'", "frame-ancestors 'none'" })
Assert.Contains(directive, policy);
Assert.True(!policy.Contains("unsafe-inline", StringComparison.Ordinal), policy);
Assert.Equal("DENY", response.Headers.GetValues("X-Frame-Options").Single());
}
}
[Test]
public async Task AdminPanelModulesAllResolve()
{
await using var server = await TestServer.StartAsync(context);
var index = await server.Client.GetStringAsync("/admin/");
// The page container is not a live region: only toasts and form errors announce themselves.
Assert.True(!index.Contains("aria-live", StringComparison.Ordinal), index);
var seen = await ModulesAsync(server);
Assert.True(seen.Count >= 20, string.Join(", ", seen.Keys));
// The Library's views (owner review 2, R6) are modules of their own under pages/library; the web upload (R3) is the
// dialog, its hash worker and the in-house SHA-256 the worker imports.
foreach (var module in new[] { "pages/library.js", "pages/library/sequence.js", "pages/library/trash.js", "pages/library/shared.js", "upload.js", "hash-worker.js", "sha256.js" })
Assert.True(seen.ContainsKey(module), module);
}
[Test]
public async Task AdminPanelListsTheLibraryAndLoadsTheWebUploadOnlyWhenItIsThere()
{
// Owner review 2, R6: the Library comes right after the Dashboard. The web upload (R3) is a module of its own that the
// Library imports on demand, so the panel works with or without it.
await using var server = await TestServer.StartAsync(context);
var app = await server.Client.GetStringAsync("/admin/app.js");
var top = MenuPages(app)[0];
Assert.SequenceEqual(["dashboard", "library"], top.Take(2));
var icons = await server.Client.GetStringAsync("/admin/icons.js");
var strings = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
foreach (var page in MenuPages(app).SelectMany(group => group))
{
Assert.Contains($" {page}: `<svg", icons);
var name = $"Admin.Nav.{char.ToUpperInvariant(page[0])}{page[1..]}";
Assert.True(strings.ContainsKey(name) && strings.ContainsKey(name + ".Tip"), name);
}
var modules = await ModulesAsync(server);
Assert.Contains(@"import(""../upload.js"")", modules["pages/library.js"]);
foreach (var (module, source) in modules)
{
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
foreach (Match import in StaticImport().Matches(source))
Assert.True(Resolve(folder, import.Groups[1].Value) != "upload.js", $"{module} imports upload.js statically");
}
using var upload = await server.Client.GetAsync("/admin/upload.js");
if (upload.StatusCode == HttpStatusCode.OK)
Assert.True(Regex.IsMatch(await upload.Content.ReadAsStringAsync(), @"export (?:async )?function openUpload\("), "upload.js exports openUpload");
else
Assert.Equal(HttpStatusCode.NotFound, upload.StatusCode);
}
/// <summary>The admin panel's modules from app.js and the menu's pages along their static imports, with their source.</summary>
private static async Task<Dictionary<string, string>> ModulesAsync(TestServer server)
{
var app = await server.Client.GetStringAsync("/admin/app.js");
// The upload dialog is a module the Library opens on demand (owner review 2, R3); its hash worker is named by a URL.
var pending = new Queue<string>(MenuPages(app).SelectMany(group => group).Select(p => $"pages/{p}.js").Prepend("upload.js").Prepend("app.js"));
var seen = new Dictionary<string, string>(StringComparer.Ordinal);
while (pending.TryDequeue(out var module))
{
if (seen.ContainsKey(module)) continue;
using var response = await server.Client.GetAsync("/admin/" + module);
Assert.Equal(HttpStatusCode.OK, response.StatusCode, module);
Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType, module);
var source = await response.Content.ReadAsStringAsync();
seen[module] = source;
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
foreach (Match import in ModuleReference().Matches(source))
pending.Enqueue(Resolve(folder, import.Groups[1].Value));
}
return seen;
}
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
private static partial Regex StaticImport();
/// <summary>A module's static imports and the module workers it starts (<c>new URL("./…", import.meta.url)</c>).</summary>
[GeneratedRegex(@"(?:from |new URL\()""(\.{1,2}/[^""]+)""")]
private static partial Regex ModuleReference();
[Test]
public async Task TheUploadDialogsHashWorkerRunsUnderThePanelPolicy()
{
await using var server = await TestServer.StartAsync(context);
using var page = await server.Client.GetAsync("/admin/");
// CSP 3: a worker is allowed by worker-src, else child-src, else script-src, else default-src.
var policy = Directives(page);
var workers = new[] { "worker-src", "child-src", "script-src", "default-src" }.Select(d => policy.GetValueOrDefault(d)).First(v => v is not null);
Assert.SequenceEqual(["'self'"], Assert.NotNull(workers));
using var worker = await server.Client.GetAsync("/admin/hash-worker.js");
Assert.Equal(HttpStatusCode.OK, worker.StatusCode);
Assert.Equal("text/javascript", worker.Content.Headers.ContentType?.MediaType);
Assert.Equal("nosniff", worker.Headers.GetValues("X-Content-Type-Options").First());
// The worker runs under its own response's policy, which lets it import the hash from the same origin.
Assert.SequenceEqual(["'self'"], Assert.NotNull(Directives(worker).GetValueOrDefault("script-src")));
Assert.Contains(@"from ""./sha256.js""", await worker.Content.ReadAsStringAsync());
var upload = await server.Client.GetStringAsync("/admin/upload.js");
Assert.Contains(@"new Worker(new URL(""./hash-worker.js"", import.meta.url), { type: ""module"" })", upload);
Assert.Contains("api.putBytes(", upload);
// No folder picking on the web: importing a whole folder is a desktop feature (owner review 2, R9).
foreach (var picker in new[] { "webkitdirectory", "showDirectoryPicker", "mozdirectory" })
Assert.True(!upload.Contains(picker, StringComparison.OrdinalIgnoreCase), picker);
// The panel has no inline handlers for the policy to block (and none to allow).
Assert.True(!Regex.IsMatch(upload, @"\son[a-z]+="""), "inline handler");
}
/// <summary>The directives of a response's Content-Security-Policy, each with its sources.</summary>
private static Dictionary<string, string[]> Directives(HttpResponseMessage response) =>
string.Join(';', response.Headers.GetValues("Content-Security-Policy"))
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(d => d.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(d => d[0], d => d[1..], StringComparer.OrdinalIgnoreCase);
[Test]
public async Task AdminPanelDocksSettingsAtTheFootAndFoldsAboutIntoIt()
{
// Owner review 2: Settings below the other pages, About its last group; old #/about bookmarks open it there.
await using var server = await TestServer.StartAsync(context);
var app = await server.Client.GetStringAsync("/admin/app.js");
var groups = MenuPages(app);
Assert.Count(2, groups);
Assert.SequenceEqual(new[] { "settings" }, groups[1]);
Assert.DoesNotContain("about", groups[0]);
Assert.Contains(@"about: ""settings?group=about""", app);
using var about = await server.Client.GetAsync("/admin/pages/about.js");
Assert.Equal(HttpStatusCode.NotFound, about.StatusCode);
var settings = await server.Client.GetStringAsync("/admin/pages/settings.js");
Assert.Contains(@"id=""about-title""", settings);
// The page draws before the dashboard aggregate answers; these two rows fill in afterwards.
Assert.Contains(@"id=""about-database""", settings);
Assert.Contains(@"id=""about-uptime""", settings);
}
/// <summary>The menu's page groups as app.js lists them: the top pages, then the ones docked at the foot.</summary>
private static List<string[]> MenuPages(string app) =>
[.. Regex.Matches(app, @"const (?:top|bottom)Pages = \[([^\]]*)\]")
.Select(m => m.Groups[1].Value.Split(',').Select(p => p.Trim().Trim('"')).ToArray())];
private static string Resolve(string folder, string relative)
{
var parts = (folder + relative).Split('/').ToList();
for (var i = 0; i < parts.Count; i++)
{
if (parts[i] == ".") parts.RemoveAt(i--);
else if (parts[i] == ".." && i > 0) parts.RemoveRange(--i, 2);
}
return string.Join('/', parts.Where(p => p.Length > 0));
}
[Test]
public async Task I18nEndpointFallsBackToEnglish()
{
await using var server = await TestServer.StartAsync(context);
var it = await server.Client.GetFromJsonAsync("/api/v1/i18n/it-IT", ProtocolJson.Default.DictionaryStringString);
Assert.Equal("Accedi", Assert.NotNull(it)["Admin.Login.SignIn"]);
var unknown = await server.Client.GetFromJsonAsync("/api/v1/i18n/xx", ProtocolJson.Default.DictionaryStringString);
Assert.Equal("Sign in", Assert.NotNull(unknown)["Admin.Login.SignIn"]);
}
[Test]
public async Task I18nEndpointMarksRightToLeftLanguages()
{
await using var server = await TestServer.StartAsync(context);
foreach (var (culture, rtl) in new[] { ("ar", "true"), ("he", "true"), ("it", "false"), ("en", "false") })
{
var strings = Assert.NotNull(await server.Client.GetFromJsonAsync($"/api/v1/i18n/{culture}", ProtocolJson.Default.DictionaryStringString));
Assert.Equal((culture, rtl), (strings["$culture"], strings["$rtl"]));
// Count strings reach the panel in their plural forms.
Assert.True(strings.ContainsKey("Admin.Users.Accounts.one") && strings.ContainsKey("Admin.Users.Accounts.other"), culture);
}
}
[Test]
public void LinuxRefusesSqlite()
{
if (OperatingSystem.IsWindows()) TestContext.Skip("SQLite is allowed on Windows");
var options = new Chronos.Server.Configuration.ServerOptions { Database = Chronos.Server.Configuration.DatabaseKind.Sqlite };
Assert.Throws<InvalidOperationException>(options.Validate);
}
[Test]
public void EnvironmentOverridesDefaults()
{
var root = context.CreateTempDirectory("env");
var env = new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_HTTP_PORT"] = "9090",
["CHRONOS_TLS_MODE"] = "proxy",
["CHRONOS_DB"] = "postgres",
["CHRONOS_SERVER_NAME"] = "Studio NAS",
};
var options = Chronos.Server.Configuration.ServerOptions.Load(env);
Assert.Equal(9090, options.HttpPort);
Assert.Equal(Chronos.Server.Configuration.TlsMode.Proxy, options.TlsMode);
Assert.Equal("Studio NAS", options.ServerName);
}
}