refactor!: rename Titano to Chronos and move CI and releases to Gitea
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
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
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>
This commit is contained in:
1 parent
c99842cc86
commit
5f27a86406
1799 files changed
+11728
-10668
No files matched your search
@@ -0,0 +1,284 @@
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using Chronos.Server.Hosting;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// The data folder and its secrets are private (BRIEF §14.2): mode 0600 off Windows; on Windows a protected ACL that no
|
||||
/// ordinary user appears in, where %ProgramData% would otherwise let every local user read the folder, with owners the
|
||||
/// server trusts and no links. On Windows a new archive folder lets other users only read it.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class DataFolderAccessTests(TestContext context)
|
||||
{
|
||||
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||||
|
||||
[Test]
|
||||
public async Task TheTlsKeyAndTheFirstAdminPasswordAreReadableOnlyByTheServer()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.AdminPassword = null);
|
||||
foreach (var file in new[] { Path.Combine(server.Options.TlsPath, "server.pfx"), Path.Combine(server.Options.DataPath, "initial-admin-password.txt") })
|
||||
{
|
||||
Assert.FileExists(file);
|
||||
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new FileInfo(file).GetAccessControl()), file);
|
||||
else Assert.Equal(OwnerOnly, File.GetUnixFileMode(file));
|
||||
}
|
||||
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(server.Options.DataPath).GetAccessControl()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ARewrittenSecretLosesTheAccessItHad()
|
||||
{
|
||||
var file = Path.Combine(context.CreateTempDirectory("secret"), "server.pfx");
|
||||
File.WriteAllBytes(file, [1]);
|
||||
if (OperatingSystem.IsWindows()) GrantUsersRead(new FileInfo(file));
|
||||
else File.SetUnixFileMode(file, OwnerOnly | UnixFileMode.GroupRead | UnixFileMode.OtherRead);
|
||||
|
||||
DataFolderAccess.WritePrivateFile(file, [1, 2, 3]);
|
||||
Assert.BytesEqual([1, 2, 3], File.ReadAllBytes(file));
|
||||
if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new FileInfo(file).GetAccessControl()));
|
||||
else Assert.Equal(OwnerOnly, File.GetUnixFileMode(file));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AFolderEveryUserCouldReadBecomesPrivateWithItsFiles()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("programdata"));
|
||||
// What %ProgramData% hands down to a new folder: every local user may read it and create files in it.
|
||||
var open = folder.GetAccessControl();
|
||||
open.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.ReadAndExecute | FileSystemRights.CreateFiles,
|
||||
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
|
||||
folder.SetAccessControl(open);
|
||||
var database = new FileInfo(Path.Combine(folder.FullName, "chronos.db"));
|
||||
File.WriteAllText(database.FullName, "rows");
|
||||
Assert.True(NamesUsers(database.GetAccessControl()), "the file inherited the users' entry");
|
||||
|
||||
DataFolderAccess.Restrict(folder.FullName);
|
||||
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
|
||||
Assert.False(NamesUsers(folder.GetAccessControl()));
|
||||
Assert.False(NamesUsers(database.GetAccessControl()), "the file still lets every user read it");
|
||||
Assert.Equal("rows", File.ReadAllText(database.FullName));
|
||||
|
||||
// Once private, a later start leaves it as it is.
|
||||
DataFolderAccess.Restrict(folder.FullName);
|
||||
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ANewDataFolderIsCreatedPrivate()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = new DirectoryInfo(Path.Combine(context.CreateTempDirectory("new"), "Chronos Server"));
|
||||
DataFolderAccess.Restrict(folder.FullName);
|
||||
Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl()));
|
||||
var settings = new FileInfo(Path.Combine(folder.FullName, "server.json"));
|
||||
File.WriteAllText(settings.FullName, "{}");
|
||||
Assert.False(NamesUsers(settings.GetAccessControl()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ASecretAnotherAccountOwnedIsReplacedByOneTheServerOwns()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = context.CreateTempDirectory("planted");
|
||||
var own = OwnerOf(NewFile(Path.Combine(folder, "probe.txt")));
|
||||
// Planted before the first start: whoever owns it keeps the right to change its ACL, whatever the server sets.
|
||||
var secret = NewFile(Path.Combine(folder, "initial-admin-password.txt"));
|
||||
if (!TrySetOwner(secret, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
|
||||
GrantUsersRead(secret);
|
||||
|
||||
DataFolderAccess.WritePrivateFile(secret.FullName, [1, 2, 3]);
|
||||
secret.Refresh();
|
||||
Assert.Equal(own, OwnerOf(secret));
|
||||
Assert.True(DataFolderAccess.IsPrivate(secret.GetAccessControl()));
|
||||
Assert.False(NamesUsers(secret.GetAccessControl()));
|
||||
Assert.BytesEqual([1, 2, 3], File.ReadAllBytes(secret.FullName));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnythingAnotherAccountOwnsIsFound()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("squatted"));
|
||||
var key = NewFile(Path.Combine(folder.CreateSubdirectory("tls").FullName, "server.pfx"));
|
||||
var own = OwnerOf(key);
|
||||
Assert.Null(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own }));
|
||||
// A folder someone else created before the first start is reported before anything inside it.
|
||||
Assert.Contains(folder.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { LocalSystem })));
|
||||
|
||||
if (!TrySetOwner(key, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
|
||||
Assert.Contains(key.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own })));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ALinkInTheDataFolderStopsTheServerBeforeTheAclChanges()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("linked"));
|
||||
var link = Path.Combine(folder.FullName, "logs");
|
||||
try
|
||||
{
|
||||
Directory.CreateSymbolicLink(link, context.CreateTempDirectory("elsewhere"));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Assert.Inconclusive("creating a symbolic link needs an elevated administrator or developer mode");
|
||||
}
|
||||
|
||||
var refused = Assert.Throws<InvalidOperationException>(() => DataFolderAccess.Restrict(folder.FullName));
|
||||
Assert.Contains(link, refused.Message);
|
||||
// The ACL change would have followed the link; it never started.
|
||||
Assert.False(folder.GetAccessControl().AreAccessRulesProtected);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void SettingsAnotherAccountOwnsAreNotRead()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var settings = NewFile(Path.Combine(context.CreateTempDirectory("settings"), "server.json"), """{ "ArchivePath": "D:\\Elsewhere" }""");
|
||||
Assert.Contains("Elsewhere", DataFolderAccess.ReadTrustedText(settings.FullName));
|
||||
// As if another account had planted it: the owner is not among those the server trusts.
|
||||
InvalidOperationException? refused = null;
|
||||
try
|
||||
{
|
||||
DataFolderAccess.ReadTrustedText(settings.FullName, new HashSet<SecurityIdentifier> { LocalSystem });
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
refused = ex;
|
||||
}
|
||||
Assert.Contains(settings.FullName, Assert.NotNull(refused).Message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AMissingArchiveFolderIsCreated()
|
||||
{
|
||||
var root = Path.Combine(context.CreateTempDirectory("archive"), "ChronosArchive");
|
||||
Assert.False(DataFolderAccess.PrepareArchive(root));
|
||||
Assert.True(Directory.Exists(root));
|
||||
// An existing folder is left as it is.
|
||||
Assert.False(DataFolderAccess.PrepareArchive(root));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ANewArchiveIsReadableByUsersButOnlyTheServerChangesIt()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
// Under C:\ a new folder would inherit "Authenticated Users: modify" and every local user could plant links
|
||||
// where the service moves uploads.
|
||||
var root = new DirectoryInfo(Path.Combine(context.CreateTempDirectory("archive"), "ChronosArchive"));
|
||||
Assert.False(DataFolderAccess.PrepareArchive(root.FullName));
|
||||
var security = root.GetAccessControl();
|
||||
Assert.True(security.AreAccessRulesProtected);
|
||||
Assert.Equal(FileSystemRights.ReadAndExecute, RightsOf(security, Users) & FileSystemRights.ReadAndExecute);
|
||||
Assert.Equal((FileSystemRights)0, RightsOf(security, Users) & (FileSystemRights.Write | FileSystemRights.Delete | FileSystemRights.ChangePermissions));
|
||||
|
||||
// Staging and trash are the server's alone.
|
||||
var meta = new DirectoryInfo(Path.Combine(root.FullName, ".chronos"));
|
||||
Assert.True(DataFolderAccess.IsPrivate(meta.GetAccessControl()));
|
||||
Assert.False(NamesUsers(meta.CreateSubdirectory("staging").GetAccessControl()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnArchiveOtherUsersCanChangeIsReportedButLeftAsItIs()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var root = new DirectoryInfo(context.CreateTempDirectory("shared"));
|
||||
DataFolderAccess.PrepareArchive(root.FullName);
|
||||
var open = root.GetAccessControl();
|
||||
open.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.Modify,
|
||||
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
|
||||
root.SetAccessControl(open);
|
||||
|
||||
Assert.True(DataFolderAccess.PrepareArchive(root.FullName));
|
||||
Assert.Equal(FileSystemRights.Modify, RightsOf(root.GetAccessControl(), Users) & FileSystemRights.Modify);
|
||||
// The .chronos folder the server added at the first start stays its own.
|
||||
Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(Path.Combine(root.FullName, ".chronos")).GetAccessControl()));
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier Users => new(WellKnownSidType.BuiltinUsersSid, null);
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier LocalSystem => new(WellKnownSidType.LocalSystemSid, null);
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier Administrators => new(WellKnownSidType.BuiltinAdministratorsSid, null);
|
||||
|
||||
private static FileInfo NewFile(string path, string contents = "x")
|
||||
{
|
||||
File.WriteAllText(path, contents);
|
||||
return new FileInfo(path);
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier OwnerOf(FileInfo file) => (SecurityIdentifier)file.GetAccessControl().GetOwner(typeof(SecurityIdentifier))!;
|
||||
|
||||
/// <summary>An owner this process may give a file that its new files do not get: its own account or Administrators.</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier OtherOwner(SecurityIdentifier own)
|
||||
{
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
return own == Administrators ? identity.User! : Administrators;
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static bool TrySetOwner(FileInfo file, SecurityIdentifier owner)
|
||||
{
|
||||
var security = new FileSecurity();
|
||||
security.SetOwner(owner);
|
||||
try
|
||||
{
|
||||
file.SetAccessControl(security);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The rights allow entries give <paramref name="account"/>.</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static FileSystemRights RightsOf(FileSystemSecurity security, SecurityIdentifier account)
|
||||
{
|
||||
FileSystemRights rights = 0;
|
||||
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
|
||||
{
|
||||
if (rule.AccessControlType == AccessControlType.Allow && rule.IdentityReference.Equals(account)) rights |= rule.FileSystemRights;
|
||||
}
|
||||
return rights;
|
||||
}
|
||||
|
||||
/// <summary>True when Users, Authenticated Users or Everyone have any allow entry.</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static bool NamesUsers(FileSystemSecurity security)
|
||||
{
|
||||
SecurityIdentifier[] ordinary = [Users, new(WellKnownSidType.AuthenticatedUserSid, null), new(WellKnownSidType.WorldSid, null)];
|
||||
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
|
||||
{
|
||||
if (rule.AccessControlType == AccessControlType.Allow && ordinary.Contains((SecurityIdentifier)rule.IdentityReference)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static void GrantUsersRead(FileInfo file)
|
||||
{
|
||||
var security = file.GetAccessControl();
|
||||
security.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.Read, AccessControlType.Allow));
|
||||
file.SetAccessControl(security);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Hosting;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
[Category("server")]
|
||||
public sealed class DiscoveryTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TheBeaconTravelsOverUdpAndParses()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.ServerName = "Studio NAS");
|
||||
var service = server.Services.GetRequiredService<DiscoveryBeaconService>();
|
||||
using var listener = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));
|
||||
using var sender = new UdpClient(AddressFamily.InterNetwork);
|
||||
await service.SendOnceAsync(sender, [(IPEndPoint)listener.Client.LocalEndPoint!], context.Cancellation);
|
||||
|
||||
var datagram = await listener.ReceiveAsync(context.Cancellation).AsTask().WaitAsync(TimeSpan.FromSeconds(5));
|
||||
var beacon = Assert.NotNull(DiscoveryBeacon.TryParse(datagram.Buffer));
|
||||
Assert.Equal("Studio NAS", beacon.Name);
|
||||
Assert.Equal(SystemEndpoints.Version, beacon.Version);
|
||||
Assert.Equal(server.HttpBase.Port, beacon.HttpPort);
|
||||
Assert.Equal(server.HttpsBase!.Port, beacon.HttpsPort);
|
||||
using var info = await server.Client.GetAsync("/api/v1/server/info");
|
||||
Assert.Equal((await info.ReadAsync(ProtocolJson.Default.ServerInfo)).TlsFingerprint, beacon.TlsFingerprint);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheBeaconAdvertisesThePortsClientsReach()
|
||||
{
|
||||
// Container ports published as other host ports: a client on the LAN must use the host's.
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.PublicHttpPort = 18080;
|
||||
o.PublicHttpsPort = 18443;
|
||||
});
|
||||
var beacon = server.Services.GetRequiredService<DiscoveryBeaconService>().CreateBeacon();
|
||||
Assert.Equal((18080, 18443), (beacon.HttpPort, beacon.HttpsPort));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ForeignDatagramsAreIgnored()
|
||||
{
|
||||
Assert.Null(DiscoveryBeacon.TryParse(Encoding.UTF8.GetBytes("HELLO {}")));
|
||||
Assert.Null(DiscoveryBeacon.TryParse(Encoding.UTF8.GetBytes("CHRONOS1 {not json")));
|
||||
Assert.Null(DiscoveryBeacon.TryParse(new byte[4096]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>TLS mode proxy (BRIEF §14.2): forwarded headers count only from trusted proxies, and the admin warns otherwise.</summary>
|
||||
[Category("server")]
|
||||
public sealed class ProxyModeTests(TestContext context)
|
||||
{
|
||||
/// <summary>A documentation network (RFC 5737) the test client never connects from.</summary>
|
||||
private const string ElsewhereOnly = "192.0.2.0/24";
|
||||
|
||||
[Test]
|
||||
public async Task AClientOutsideTheTrustedProxiesCannotChooseItsAddress()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.TrustedProxies = ElsewhereOnly;
|
||||
o.LoginAttemptsPerMinute = 5;
|
||||
});
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
using var failed = await LoginAsync(server, "user" + i, $"203.0.113.{i + 1}");
|
||||
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
||||
}
|
||||
// A new X-Forwarded-For per attempt does not buy a new budget: the limit stays on the real address.
|
||||
using var limited = await LoginAsync(server, "admin", "203.0.113.99");
|
||||
await limited.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "rate_limited");
|
||||
|
||||
var audit = await server.Database.Audit.ListAsync(null, "login_failed", 50, null, context.Cancellation);
|
||||
Assert.Count(5, audit.Items);
|
||||
Assert.True(audit.Items.All(e => IsLoopback(e.RemoteAddress)), string.Join(", ", audit.Items.Select(e => e.RemoteAddress)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ATrustedProxyReportsTheClientAddress()
|
||||
{
|
||||
// The default trusts loopback, where a proxy on the same machine (and this test) connects from.
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.LoginAttemptsPerMinute = 5;
|
||||
});
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
using var failed = await LoginAsync(server, "user" + i, $"203.0.113.{i + 1}");
|
||||
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
||||
}
|
||||
var audit = await server.Database.Audit.ListAsync(null, "login_failed", 50, null, context.Cancellation);
|
||||
Assert.Contains("203.0.113.8", audit.Items.Select(e => e.RemoteAddress));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ByDefaultAMachineOfTheHomeNetworkIsNoProxy()
|
||||
{
|
||||
// The machines of a home network reach the HTTP port directly from private addresses, also through Docker's
|
||||
// port publishing (which keeps the client's address): none of them may choose its own address.
|
||||
await using var server = await TestServer.StartAsync(context, o => o.TlsMode = TlsMode.Proxy);
|
||||
foreach (var peer in new[] { "192.168.1.50", "10.0.0.7", "172.17.0.1", "fd00::7" })
|
||||
Assert.Equal((peer, false), await ForwardAsync(server, peer));
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "127.0.0.1"));
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::ffff:127.0.0.1"));
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::1"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxyNetworkCountsOnceListed()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.TrustedProxies = "172.18.0.0/16";
|
||||
});
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "172.18.0.5"));
|
||||
Assert.Equal(("192.168.1.50", false), await ForwardAsync(server, "192.168.1.50"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnAdminSignInThroughAnUntrustedProxyNamesTheSetting()
|
||||
{
|
||||
// The warning chip needs a session first: the sign-in refusal itself points at CHRONOS_TRUSTED_PROXIES.
|
||||
var request = new DefaultHttpContext();
|
||||
request.Connection.RemoteIpAddress = IPAddress.Parse("172.18.0.5");
|
||||
request.Request.Scheme = "http";
|
||||
Assert.Equal("proxy_untrusted", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
|
||||
Assert.Equal("https_required", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Auto }));
|
||||
Assert.Contains("CHRONOS_TRUSTED_PROXIES", Loc.L("Server.Error.ProxyUntrusted"));
|
||||
|
||||
request.Request.Scheme = "https";
|
||||
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
|
||||
request.Request.Scheme = "http";
|
||||
request.Connection.RemoteIpAddress = IPAddress.Loopback;
|
||||
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheAdminWarnsWhenAPageDidNotComeThroughATrustedProxyOverHttps()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.TlsMode = TlsMode.Proxy);
|
||||
var admin = await server.AdminAsync();
|
||||
Assert.True((await DashboardAsync(admin, forwardedProto: null)).ProxyWarning, "plain HTTP to the server's own port");
|
||||
Assert.False((await DashboardAsync(admin, "https")).ProxyWarning, "HTTPS through a trusted proxy");
|
||||
Assert.True((await DashboardAsync(admin, "http")).ProxyWarning, "plain HTTP through the proxy");
|
||||
Assert.True((await SettingsAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
Assert.False((await SettingsAsync(admin, "https")).ProxyWarning);
|
||||
|
||||
await using var untrusted = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.TrustedProxies = ElsewhereOnly;
|
||||
});
|
||||
var other = await untrusted.AdminAsync();
|
||||
Assert.True((await DashboardAsync(other, "https")).ProxyWarning, "a claim of HTTPS from a peer that is no trusted proxy");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OtherTlsModesNeverWarn()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var admin = await server.AdminAsync();
|
||||
Assert.False((await DashboardAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
Assert.False((await SettingsAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the server's own forwarded-headers step on a request from <paramref name="peer"/> that claims to forward a
|
||||
/// client at 203.0.113.7 over HTTPS: the address and scheme the rest of the server then sees.
|
||||
/// </summary>
|
||||
private static async Task<(string? Address, bool Https)> ForwardAsync(TestServer server, string peer)
|
||||
{
|
||||
var request = new DefaultHttpContext();
|
||||
request.Connection.RemoteIpAddress = IPAddress.Parse(peer);
|
||||
request.Request.Scheme = "http";
|
||||
request.Request.Headers["X-Forwarded-For"] = "203.0.113.7";
|
||||
request.Request.Headers["X-Forwarded-Proto"] = "https";
|
||||
var forwarded = new ForwardedHeadersMiddleware(_ => Task.CompletedTask, NullLoggerFactory.Instance,
|
||||
server.Services.GetRequiredService<IOptions<ForwardedHeadersOptions>>());
|
||||
await forwarded.Invoke(request);
|
||||
var address = request.Connection.RemoteIpAddress;
|
||||
return ((address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString(), request.Request.IsHttps);
|
||||
}
|
||||
|
||||
private static bool IsLoopback(string? address) =>
|
||||
IPAddress.TryParse(address, out var ip) && IPAddress.IsLoopback(ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip);
|
||||
|
||||
private static async Task<HttpResponseMessage> LoginAsync(TestServer server, string username, string forwardedFor)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/login")
|
||||
{
|
||||
Content = JsonContent.Create(new LoginRequest(username, "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest),
|
||||
};
|
||||
request.Headers.Add("X-Forwarded-For", forwardedFor);
|
||||
return await server.Client.SendAsync(request);
|
||||
}
|
||||
|
||||
private static async Task<DashboardDto> DashboardAsync(HttpClient admin, string? forwardedProto)
|
||||
{
|
||||
using var response = await SendAsync(admin, "/api/v1/server/dashboard", forwardedProto);
|
||||
return await response.ReadAsync(ProtocolJson.Default.DashboardDto);
|
||||
}
|
||||
|
||||
private static async Task<ServerSettingsDto> SettingsAsync(HttpClient admin, string? forwardedProto)
|
||||
{
|
||||
using var response = await SendAsync(admin, "/api/v1/server/settings", forwardedProto);
|
||||
return await response.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> SendAsync(HttpClient client, string path, string? forwardedProto)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, path);
|
||||
if (forwardedProto is not null) request.Headers.Add("X-Forwarded-Proto", forwardedProto);
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using Chronos.Data;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Hosting;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
[Category("server")]
|
||||
public sealed class StartupTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void TheServerRefusesToStartWithoutTheArchiveModule()
|
||||
{
|
||||
var root = context.CreateTempDirectory("bare");
|
||||
var options = new ServerOptions
|
||||
{
|
||||
DataPath = Path.Combine(root, "data"),
|
||||
ArchivePath = Path.Combine(root, "archive"),
|
||||
HttpPort = 0,
|
||||
HttpsPort = 0,
|
||||
Database = DatabaseKind.Sqlite,
|
||||
Discovery = false,
|
||||
};
|
||||
var error = Assert.Throws<InvalidOperationException>(() => ServerHost.Build(options, []));
|
||||
Assert.Contains("IArchiveIngest", error.Message);
|
||||
Assert.Contains("IFrameAssetLocator", error.Message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ChronosDbAcceptsAConnectionString()
|
||||
{
|
||||
var root = context.CreateTempDirectory("env");
|
||||
var options = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["CHRONOS_DATA_PATH"] = root,
|
||||
["CHRONOS_DB"] = "Host=db.lan;Port=6543;Database=archive;Username=chronos;Password=secret",
|
||||
});
|
||||
Assert.Equal(DatabaseKind.Postgres, options.Database);
|
||||
var database = options.ToDatabaseOptions();
|
||||
Assert.Equal(Dialect.Postgres, database.Dialect);
|
||||
Assert.Equal(6543, Chronos.Data.Postgres.PostgresSettings.Parse(database.ConnectionString).Port);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PartsBuildAQuotedPostgresConnectionString()
|
||||
{
|
||||
var options = new ServerOptions
|
||||
{
|
||||
Database = DatabaseKind.Postgres, // the Windows default is SQLite
|
||||
DbHost = "postgres",
|
||||
DbName = "chronos",
|
||||
DbUser = "chronos",
|
||||
DbPassword = "it's;secret",
|
||||
DbSslMode = "disable",
|
||||
};
|
||||
var settings = Chronos.Data.Postgres.PostgresSettings.Parse(options.ToDatabaseOptions().ConnectionString);
|
||||
Assert.Equal(("postgres", "chronos", "it's;secret"), (settings.Host, settings.Database, settings.Password));
|
||||
Assert.Equal(Chronos.Data.Postgres.SslMode.Disable, settings.SslMode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EnvironmentVariablesLockTheirSettings()
|
||||
{
|
||||
var root = context.CreateTempDirectory("locked");
|
||||
var options = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["CHRONOS_DATA_PATH"] = root,
|
||||
["CHRONOS_DB"] = "postgres",
|
||||
["CHRONOS_HTTP_PORT"] = "9090",
|
||||
["CHRONOS_DISCOVERY"] = "false",
|
||||
});
|
||||
Assert.SequenceEqual(["Database", "HttpPort", "Discovery"], options.Locked);
|
||||
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "many" }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheFormerWorkersSettingStillSetsTheParallelism()
|
||||
{
|
||||
// Owner review 1: "workers" (jobs at once) became the parallelism (photos the running job processes at once).
|
||||
var root = context.CreateTempDirectory("workers");
|
||||
File.WriteAllText(Path.Combine(root, "server.json"), """{ "Workers": 6 }""");
|
||||
Assert.Equal(6, ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" }).Parallelism);
|
||||
|
||||
var former = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "5" });
|
||||
Assert.Equal((5, true), (former.Parallelism, former.FormerWorkersVariable));
|
||||
Assert.SequenceEqual(["Database", "Parallelism"], former.Locked);
|
||||
var both = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["CHRONOS_DATA_PATH"] = root,
|
||||
["CHRONOS_DB"] = "postgres",
|
||||
["CHRONOS_WORKERS"] = "5",
|
||||
["CHRONOS_PARALLELISM"] = "7",
|
||||
["CHRONOS_PRIORITY_QUEUE"] = "true",
|
||||
});
|
||||
Assert.Equal((7, true), (both.Parallelism, both.PriorityQueue));
|
||||
Assert.SequenceEqual(["Database", "Parallelism", "PriorityQueue"], both.Locked);
|
||||
Assert.False(ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PARALLELISM"] = "2" })
|
||||
.FormerWorkersVariable);
|
||||
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PRIORITY_QUEUE"] = "often" }));
|
||||
// A value the admin panel would refuse is brought within its range, so the panel can still save the other settings.
|
||||
Assert.Equal(ServerOptions.MaxParallelism,
|
||||
ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PARALLELISM"] = "96" }).Parallelism);
|
||||
Assert.Equal(1, ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "0" }).Parallelism);
|
||||
Assert.InRange(new ServerOptions().Parallelism, 1, ServerOptions.MaxParallelism);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TrustedProxiesAreAddressesOrNetworks()
|
||||
{
|
||||
var root = context.CreateTempDirectory("proxies");
|
||||
// Loopback only: machines of the home network reach the HTTP port directly from private addresses.
|
||||
var defaults = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" }).TrustedProxyNetworks();
|
||||
foreach (var address in new[] { "127.0.0.1", "127.0.0.53", "::1" })
|
||||
Assert.True(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
|
||||
foreach (var address in new[] { "10.20.30.40", "172.18.0.3", "192.168.1.2", "fd00::7", "203.0.113.5" })
|
||||
Assert.False(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
|
||||
|
||||
var options = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["CHRONOS_DATA_PATH"] = root,
|
||||
["CHRONOS_DB"] = "postgres",
|
||||
["CHRONOS_TRUSTED_PROXIES"] = "10.1.2.3, 2001:db8::/32;172.20.0.5/16",
|
||||
});
|
||||
Assert.Contains("TrustedProxies", options.Locked);
|
||||
Assert.SequenceEqual(["10.1.2.3/32", "2001:db8::/32", "172.20.0.0/16"], options.TrustedProxyNetworks().Select(n => n.ToString()));
|
||||
foreach (var invalid in new[] { "proxy.lan", "10.0.0.0/33", "fe80::1%2" })
|
||||
{
|
||||
var error = Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["CHRONOS_DATA_PATH"] = root,
|
||||
["CHRONOS_DB"] = "postgres",
|
||||
["CHRONOS_TRUSTED_PROXIES"] = "127.0.0.1," + invalid,
|
||||
}));
|
||||
Assert.Contains(invalid, error.Message);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PublicPortsComeFromTheEnvironment()
|
||||
{
|
||||
var root = context.CreateTempDirectory("public");
|
||||
var options = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["CHRONOS_DATA_PATH"] = root,
|
||||
["CHRONOS_DB"] = "postgres",
|
||||
["CHRONOS_PUBLIC_HTTP_PORT"] = "18080",
|
||||
["CHRONOS_PUBLIC_HTTPS_PORT"] = "18443",
|
||||
});
|
||||
Assert.Equal((18080, 18443), (options.PublicHttpPort, options.PublicHttpsPort));
|
||||
Assert.Null(ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" }).PublicHttpsPort);
|
||||
foreach (var invalid in new[] { "0", "70000", "https" })
|
||||
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PUBLIC_HTTPS_PORT"] = invalid }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HelpListsEveryVariable()
|
||||
{
|
||||
foreach (var variable in ServerOptions.EnvironmentVariables.Concat(["PUID", "PGID", "TZ"]))
|
||||
Assert.True(Regex.IsMatch(ServerCommandLine.Usage, $@"\b{variable}\b"), variable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
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 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 app = await server.Client.GetStringAsync("/admin/app.js");
|
||||
var pages = Regex.Match(app, @"const pages = \[([^\]]*)\]").Groups[1].Value.Split(',').Select(p => p.Trim().Trim('"'));
|
||||
var pending = new Queue<string>(pages.Select(p => $"pages/{p}.js").Prepend("app.js"));
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
while (pending.TryDequeue(out var module))
|
||||
{
|
||||
if (!seen.Add(module)) continue;
|
||||
using var response = await server.Client.GetAsync("/admin/" + module);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode, module);
|
||||
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
|
||||
foreach (Match import in Regex.Matches(await response.Content.ReadAsStringAsync(), @"from ""(\.{1,2}/[^""]+)"""))
|
||||
pending.Enqueue(Resolve(folder, import.Groups[1].Value));
|
||||
}
|
||||
Assert.True(seen.Count >= 14, string.Join(", ", seen));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using System.Diagnostics.Eventing.Reader;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using Chronos.Server.Hosting;
|
||||
using Chronos.Server.Hosting.Windows;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
public sealed class WindowsServiceTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void CommandSwitchesAreParsedAndTheRestPassedOn()
|
||||
{
|
||||
Assert.Equal(ServerCommand.Run, ServerCommandLine.Parse([]).Command);
|
||||
var service = ServerCommandLine.Parse(["--service", "--urls", "x"]);
|
||||
Assert.Equal(ServerCommand.Service, service.Command);
|
||||
Assert.SequenceEqual(["--urls", "x"], service.HostArguments);
|
||||
Assert.Equal(ServerCommand.InstallService, ServerCommandLine.Parse(["--install-service"]).Command);
|
||||
Assert.Equal(ServerCommand.UninstallService, ServerCommandLine.Parse(["--uninstall-service"]).Command);
|
||||
Assert.Equal(ServerCommand.HealthCheck, ServerCommandLine.Parse(["--healthcheck"]).Command);
|
||||
Assert.Equal(ServerCommand.Help, ServerCommandLine.Parse(["/?"]).Command);
|
||||
Assert.NotNull(ServerCommandLine.Parse(["--install-service", "--uninstall-service"]).Error);
|
||||
Assert.Null(ServerCommandLine.Parse(["--service", "--service"]).Error);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StatusReportsFollowTheServiceControlManagerRules()
|
||||
{
|
||||
var tracker = new ServiceStatusTracker();
|
||||
var start = tracker.StartPending(60_000);
|
||||
Assert.Equal((ServiceState.StartPending, 0u, 1u, 60_000u), (start.State, start.ControlsAccepted, start.CheckPoint, start.WaitHintMilliseconds));
|
||||
Assert.Equal(2u, tracker.StartPending(60_000).CheckPoint);
|
||||
var running = tracker.Running();
|
||||
Assert.Equal((ServiceState.Running, ServiceStatusTracker.AcceptStop | ServiceStatusTracker.AcceptShutdown, 0u), (running.State, running.ControlsAccepted, running.CheckPoint));
|
||||
Assert.Throws<InvalidOperationException>(() => tracker.Running());
|
||||
Assert.Equal(1u, tracker.StopPending(35_000).CheckPoint);
|
||||
Assert.Equal(2u, tracker.StopPending(35_000).CheckPoint);
|
||||
var stopped = tracker.Stopped(0);
|
||||
Assert.Equal((ServiceState.Stopped, 0u, 0u), (stopped.State, stopped.ControlsAccepted, stopped.CheckPoint));
|
||||
Assert.Throws<InvalidOperationException>(() => tracker.StopPending(1));
|
||||
Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AServiceFailureLeadsWithTheReasonTheServerGave()
|
||||
{
|
||||
var refused = new InvalidOperationException(@"C:\ProgramData\Chronos Server belongs to PC\ada, not to SYSTEM, Administrators or the account Chronos Server runs as.");
|
||||
var text = ServiceEventLog.Describe("Chronos Server did not start:", refused);
|
||||
Assert.True(text.StartsWith(@"Chronos Server did not start: C:\ProgramData\Chronos Server belongs to PC\ada", StringComparison.Ordinal), text);
|
||||
Assert.Contains("System.InvalidOperationException", text);
|
||||
|
||||
// ReportEvent refuses a longer string: the text is cut, never between the halves of a surrogate pair.
|
||||
var cut = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength)));
|
||||
Assert.Equal(ServiceEventLog.MaxLength, cut.Length);
|
||||
Assert.True(cut.EndsWith("a\u2026", StringComparison.Ordinal), cut[^5..]);
|
||||
var pair = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength - 4) + "\uD83D\uDE00" + new string('b', 99)));
|
||||
Assert.Equal(ServiceEventLog.MaxLength - 1, pair.Length);
|
||||
Assert.True(pair.EndsWith("a\u2026", StringComparison.Ordinal), pair[^5..]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AServiceFailureReachesTheApplicationEventLog()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
// Written as a source of its own, so a test run never looks like a failed service in Event Viewer.
|
||||
const string source = "Chronos.Server.Tests";
|
||||
var marker = source + " " + Guid.NewGuid().ToString("N");
|
||||
Assert.True(ServiceEventLog.Error(source, ServiceEventLog.StartFailed, marker), "the Application log takes the event");
|
||||
var filter = $"*[System[Provider[@Name='{source}'] and EventID={ServiceEventLog.StartFailed}]]";
|
||||
var query = new EventLogQuery("Application", PathType.LogName, filter) { ReverseDirection = true };
|
||||
for (var attempt = 0; attempt < 50; attempt++)
|
||||
{
|
||||
using (var reader = new EventLogReader(query))
|
||||
{
|
||||
for (var read = 0; read < 100 && reader.ReadEvent() is { } record; read++)
|
||||
{
|
||||
using (record)
|
||||
{
|
||||
// The event's one string, which Event Viewer shows whole.
|
||||
if (record.Properties.Count != 1 || record.Properties[0].Value as string != marker) continue;
|
||||
Assert.Equal((byte?)2, record.Level, "an error");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
Assert.Fail($"No {source} event carries '{marker}'.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheServiceIsRegisteredOnlyFromInsideProgramFiles()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
|
||||
Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Chronos", "Chronos.Server.exe")));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Chronos"));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Chronos")));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Chronos")));
|
||||
// The test build is not under Program Files: registering it is refused, naming the folder.
|
||||
Assert.Contains(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory), Assert.NotNull(ServiceInstaller.UnsafeLocation()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnyFileOrdinaryUsersCanChangeIsFound()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) Assert.Inconclusive("registering a service needs an administrator");
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("program"));
|
||||
File.WriteAllBytes(Path.Combine(folder.FullName, "Chronos.Server.exe"), [1]);
|
||||
var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Chronos.Core.resources.dll"));
|
||||
File.WriteAllBytes(satellite.FullName, [1]);
|
||||
|
||||
// Like Program Files: administrators may change the folder, users only read it.
|
||||
var locked = new DirectorySecurity();
|
||||
locked.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
var everything = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
|
||||
foreach (var account in new[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), identity.User! })
|
||||
locked.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, everything, PropagationFlags.None, AccessControlType.Allow));
|
||||
locked.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, everything,
|
||||
PropagationFlags.None, AccessControlType.Allow));
|
||||
folder.SetAccessControl(locked);
|
||||
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: true));
|
||||
|
||||
// One satellite assembly users may replace is enough: the service would load it as SYSTEM.
|
||||
var open = satellite.GetAccessControl();
|
||||
open.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow));
|
||||
satellite.SetAccessControl(open);
|
||||
Assert.Equal(satellite.FullName, ServiceInstaller.FindChangeable(folder, recursive: true));
|
||||
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheDispatcherDeclinesAConsoleProcess()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var built = false;
|
||||
Assert.False(WindowsServiceHost.Run(() =>
|
||||
{
|
||||
built = true;
|
||||
throw new InvalidOperationException("never built outside the SCM");
|
||||
}));
|
||||
Assert.False(built);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user