Files
Chronos/tests/Titano.Server.Tests/Hosting/WindowsServiceTests.cs
T
Claude 047cddfe7b fix(server): keep Windows secrets private and the service out of user folders
On Windows the data folder sits in %ProgramData%, whose ACL let every local
user read the database, the password-less TLS key and the temporary admin
password, and create a server.json the LocalSystem service would load
(SRS-02, SRV-2). The folder now gets a protected DACL (SYSTEM,
Administrators, the server's account) at every start when it names anyone
else, which also replaces what the files inside inherited; server.pfx and
initial-admin-password.txt are written with their own protected DACL, and
with mode 0600 elsewhere. A folder whose ACL cannot be changed stops the
start with a clear message.

--install-service registered a LocalSystem service from any folder, so a
per-user install or an unpacked zip handed SYSTEM to that user (SRS-06). It
now refuses, with a localized one-line reason, unless the program folder is
inside Program Files and no account besides SYSTEM, Administrators,
TrustedInstaller or the registering administrator can change it or any file
below it (under dotnet, the host's folder too).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 09:27:06 +00:00

104 lines
5.9 KiB
C#

using System.Security.AccessControl;
using System.Security.Principal;
using Titano.Server.Hosting;
using Titano.Server.Hosting.Windows;
using Titano.Testing;
namespace Titano.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]
[WindowsOnly]
public void TheServiceIsRegisteredOnlyFromInsideProgramFiles()
{
if (!OperatingSystem.IsWindows()) return;
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Titano", "Titano.Server.exe")));
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles));
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Titano"));
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Titano")));
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Titano")));
// 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, "Titano.Server.exe"), [1]);
var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Titano.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);
}
}