Files
Chronos/tests/Chronos.Server.Tests/Hosting/WindowsServiceTests.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

153 lines
8.7 KiB
C#

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);
}
}