using System.Globalization; using System.IO; using Microsoft.Win32; using Chronos.Core.Packaging; using Chronos.Setup.Cli; using Chronos.Setup.Engine; using Chronos.Setup.Interop; using Chronos.Testing; namespace Chronos.App.Tests.Setup; /// /// What setup leaves behind and what it registers: services and startup entries of the programs it installed, never /// of other programs in the same folder (SETUP-1, SETUP-2), shortcuts another product owns or takes over (SRS-09), the /// Server's all-users scope inside Program Files (SRS-06) and the file type name in setup's language (SRS-04). /// public sealed class SetupEngineTests(TestContext context) { private const string TestsKey = @"Software\Chronos.Tests"; /// The StartupApproved state Task Manager writes for an entry it turned off. private static readonly byte[] TurnedOff = [0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; [Theory] [Case(@"""C:\Program Files\Chronos\Chronos.Server.exe"" --service", @"C:\Program Files\Chronos\Chronos.Server.exe")] [Case(@"C:\Program Files\Chronos\Chronos.Server.exe --service", @"C:\Program Files\Chronos\Chronos.Server.exe")] [Case(@"""C:\Program Files\dotnet\dotnet.exe"" ""C:\Apps\Chronos\Chronos.Server.dll"" --service", @"C:\Apps\Chronos\Chronos.Server.dll")] [Case(@"C:\Windows\system32\svchost.exe -k netsvcs", @"C:\Windows\system32\svchost.exe")] [Case(@"Chronos.Uploader.exe --tray", null)] [Case("", null)] public void TheProgramOfACommandLineIsItsFirstFullPath(string commandLine, string? program) => Assert.Equal(program, CommandProgram.Of(commandLine)); [Test] public void ServiceStepsTravelToTheElevatedCopyWithTheirServices() { var arguments = new SetupArguments { Services = ServiceActions.Prune | ServiceActions.Start, ServiceNames = ["ChronosServer"], Directory = @"C:\Program Files\Chronos", Elevated = true, }; var switches = arguments.ToSwitches().ToList(); Assert.Contains("/SERVICES=prune,start", switches); Assert.Contains("/NAMES=ChronosServer", switches); var parsed = SetupArguments.Parse(switches); Assert.Equal(arguments.Services, parsed.Services); Assert.Equal(arguments.Directory, parsed.Directory); Assert.SequenceEqual(["ChronosServer"], parsed.ServiceNames!); Assert.True(parsed.Elevated); Assert.Equal(ServiceActions.Remove, SetupArguments.Parse(["/SERVICES=Remove", "/NAMES=ChronosServer", "/DIR=C:\\Apps\\Chronos"]).Services); // The step acts only on services the unelevated setup named. Assert.Throws(() => SetupArguments.Parse(["/SERVICES=stop", "/NAMES=ChronosServer"])); Assert.Throws(() => SetupArguments.Parse(["/SERVICES=stop", "/DIR=C:\\Apps\\Chronos"])); Assert.Throws(() => SetupArguments.Parse(["/SERVICES=kill", "/NAMES=ChronosServer", "/DIR=C:\\Apps\\Chronos"])); Assert.Throws(() => SetupArguments.Parse(["/SERVICES=none", "/NAMES=ChronosServer", "/DIR=C:\\Apps\\Chronos"])); } [Test] [WindowsOnly] public void OnlyTheServicesOfProgramsSetupInstalledAreFound() { var folder = Path.Combine(context.CreateTempDirectory("services"), "Apps"); var owned = CommandProgram.FullPaths(folder, ["Chronos.Server.exe", "Chronos.exe", "lib/Chronos.Core.dll"]); var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N"); try { using var services = Registry.CurrentUser.CreateSubKey(keyPath, writable: true); Service(services, "ChronosServer", 0x10, $"\"{Path.Combine(folder, "Chronos.Server.exe")}\" --service"); Service(services, "ChronosServerUnquoted", 0x10, Path.Combine(folder, "CHRONOS.SERVER.EXE") + " --service"); // Another vendor's service, and a driver, that live in the same folder (a shared D:\Apps): never Chronos's. Service(services, "OtherVendor", 0x10, $"\"{Path.Combine(folder, "Other", "Other.exe")}\""); Service(services, "OtherBeside", 0x10, $"\"{Path.Combine(folder, "Helper.exe")}\" /run"); Service(services, "Driver", 0x1, Path.Combine(folder, "Chronos.Server.exe")); using (var deleting = services.CreateSubKey("Deleting", writable: true)) { deleting.SetValue("Type", 0x10, RegistryValueKind.DWord); deleting.SetValue("DeleteFlag", 1, RegistryValueKind.DWord); deleting.SetValue("ImagePath", Path.Combine(folder, "Chronos.Server.exe"), RegistryValueKind.ExpandString); } var found = InstalledServices.Find(services, owned); Assert.SequenceEqual(["ChronosServer", "ChronosServerUnquoted"], found.Select(s => s.Name).Order(StringComparer.Ordinal)); Assert.True(found.All(s => s.Program.Equals(Path.Combine(folder, "Chronos.Server.exe"), StringComparison.OrdinalIgnoreCase))); Assert.Empty(InstalledServices.Find(services, CommandProgram.FullPaths(folder, ["Chronos.exe"]))); } finally { DeleteTestKey(keyPath); } static void Service(RegistryKey services, string name, int type, string imagePath) { using var key = services.CreateSubKey(name, writable: true); key.SetValue("Type", type, RegistryValueKind.DWord); key.SetValue("ImagePath", imagePath, RegistryValueKind.ExpandString); } } [Test] [WindowsOnly] public void AServiceThatIsNotRegisteredNeedsNothing() { var folder = context.CreateTempDirectory("services"); // No service starts a program of a fresh folder, and nothing is asked of the Service Control Manager. Assert.Empty(InstalledServices.Find(CommandProgram.FullPaths(folder, ["Chronos.Server.exe"]))); Assert.Equal(SetupExitCode.Success, InstalledServices.Apply([], ServiceActions.Remove)); var gone = new InstalledService("ChronosTest" + Guid.NewGuid().ToString("N"), "Chronos Server", Path.Combine(folder, "Chronos.Server.exe")); Assert.False(InstalledServices.IsRunning(gone)); foreach (var action in (ServiceActions[])[ServiceActions.Stop, ServiceActions.Prune, ServiceActions.Start, ServiceActions.Remove]) Assert.False(InstalledServices.NeedsWork([gone], action), $"{action} of a service that does not exist"); // Applying to it skips it: a service deleted meanwhile is not a failure. Assert.Equal(SetupExitCode.Success, InstalledServices.Apply([gone], ServiceActions.Remove | ServiceActions.Start)); } [Test] [WindowsOnly] public void AServiceWhoseProgramIsGoneIsDeletedAndAnotherFoldersServiceStays() { // The Service Control Manager registers services for administrators only; CI runners have the rights. if (!Elevation.IsElevated) TestContext.Skip("needs administrator rights"); var root = context.CreateTempDirectory("services"); var folder = Path.Combine(root, "Apps"); Directory.CreateDirectory(folder); var ours = "ChronosTest" + Guid.NewGuid().ToString("N"); var other = "ChronosTest" + Guid.NewGuid().ToString("N"); try { // Two stopped services whose programs are gone: one in the install folder, one in a folder setup did not install. ScratchServices.Create(ours, $"\"{Path.Combine(folder, "Chronos.Server.exe")}\" --service"); ScratchServices.Create(other, $"\"{Path.Combine(root, "Elsewhere", "Chronos.Server.exe")}\" --service"); var found = InstalledServices.Find(CommandProgram.FullPaths(folder, ["Chronos.Server.exe"])); var service = Assert.Contains(found, s => s.Name == ours); Assert.False(found.Any(s => s.Name == other), "a service of another folder is not this installation's"); Assert.False(InstalledServices.IsRunning(service)); Assert.True(InstalledServices.NeedsWork([service], ServiceActions.Prune), "a service whose program is gone is pruned"); Assert.False(InstalledServices.NeedsWork([service], ServiceActions.Start), "nothing to start: its program is gone"); Assert.Equal(SetupExitCode.Success, InstalledServices.Apply(found, ServiceActions.Prune)); Assert.False(ScratchServices.Exists(ours), "the pruned service is deleted"); Assert.True(ScratchServices.Exists(other), "the other folder's service stays"); Assert.Empty(InstalledServices.Find(CommandProgram.FullPaths(folder, ["Chronos.Server.exe"]))); } finally { ScratchServices.DeleteQuietly(ours); ScratchServices.DeleteQuietly(other); } } [Test] [WindowsOnly] public void UninstallRemovesOnlyTheSignInEntriesOfTheProgramsItRemoves() { var folder = Path.Combine(context.CreateTempDirectory("startup"), "Apps"); var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N"); try { using (var run = Registry.CurrentUser.CreateSubKey(keyPath + @"\Run", writable: true)) using (var approval = Registry.CurrentUser.CreateSubKey(keyPath + @"\Approved", writable: true)) { run.SetValue("Chronos Uploader", $"\"{Path.Combine(folder, "Uploader", "Chronos.Uploader.exe")}\" --tray"); // A portable Chronos unpacked in a subfolder of the same folder: not a program this installation lists. run.SetValue("Chronos", $"\"{Path.Combine(folder, "Portable", "Chronos.exe")}\" --minimized"); // Another program in the same folder, and a copy in a sibling folder. run.SetValue("Other", $"\"{Path.Combine(folder, "Other.exe")}\" --background"); run.SetValue("Sibling", $"\"{folder} 2\\Chronos.Uploader.exe\""); // Both Chronos entries were turned off in Task Manager. approval.SetValue("Chronos Uploader", TurnedOff, RegistryValueKind.Binary); approval.SetValue("Chronos", TurnedOff, RegistryValueKind.Binary); var programs = CommandProgram.FullPaths(folder, ["Chronos.exe", "Uploader/Chronos.Uploader.exe", "Other.exe"]); Assert.SequenceEqual(["Chronos Uploader"], SetupRegistry.DeleteStartupEntries(run, approval, programs)); Assert.SequenceEqual(["Chronos", "Other", "Sibling"], run.GetValueNames().Order(StringComparer.Ordinal)); Assert.SequenceEqual(["Chronos"], approval.GetValueNames()); } } finally { DeleteTestKey(keyPath); } } [Test] [WindowsOnly] public void AnUpgradeMovesTheSignInEntryOfARenamedProgramAndRemovesThatOfADroppedOne() { var folder = Path.Combine(context.CreateTempDirectory("upgrade"), "Apps"); var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N"); // This version ships the client as Chronos.exe (the previous one as Chronos.old.exe), and the user left out the Uploader. var manifest = Manifest(); manifest.Components.Add(new PayloadComponent { Id = "Uploader", DisplayName = "Chronos Uploader", DefaultSelected = true }); manifest.Shortcuts.Add(new PayloadShortcut { Component = "Chronos", Name = "Chronos", Target = "Chronos.exe", StartMenu = true }); manifest.Shortcuts.Add(new PayloadShortcut { Component = "Uploader", Name = "Chronos Uploader", Target = "Chronos.Uploader.exe", StartMenu = true }); var programs = InstallEngine.StartupPrograms(manifest, folder, ["Chronos", "Server"]); Assert.SequenceEqual(["Chronos"], programs.Keys); Assert.Equal(Path.Combine(folder, "Chronos.exe"), programs["Chronos"]); try { using (var run = Registry.CurrentUser.CreateSubKey(keyPath + @"\Run", writable: true)) using (var approval = Registry.CurrentUser.CreateSubKey(keyPath + @"\Approved", writable: true)) { run.SetValue("Chronos", $"\"{Path.Combine(folder, "Chronos.old.exe")}\" --minimized"); run.SetValue("Chronos Uploader", $"\"{Path.Combine(folder, "Chronos.Uploader.exe")}\" --tray"); run.SetValue("Other", $"\"{Path.Combine(folder, "Other.exe")}\" --background"); approval.SetValue("Chronos", TurnedOff, RegistryValueKind.Binary); approval.SetValue("Chronos Uploader", TurnedOff, RegistryValueKind.Binary); var dropped = CommandProgram.FullPaths(folder, ["Chronos.old.exe", "Chronos.Uploader.exe", "Other.exe"]); Assert.SequenceEqual(["Chronos", "Chronos Uploader"], SetupRegistry.MoveStartupEntries(run, approval, dropped, programs)); // The new client finds its entry with its option, still turned off; the Uploader no longer starts; other values stay. Assert.Equal($"\"{Path.Combine(folder, "Chronos.exe")}\" --minimized", run.GetValue("Chronos")); Assert.SequenceEqual(["Chronos", "Other"], run.GetValueNames().Order(StringComparer.Ordinal)); Assert.SequenceEqual(["Chronos"], approval.GetValueNames()); // An entry that starts another copy is not this upgrade's to move. var other = $"\"{Path.Combine(folder + " 2", "Chronos.old.exe")}\" --minimized"; run.SetValue("Chronos", other); Assert.Empty(SetupRegistry.MoveStartupEntries(run, approval, dropped, programs)); Assert.Equal(other, run.GetValue("Chronos")); } } finally { DeleteTestKey(keyPath); } } [Test] [WindowsOnly] public void AShortcutTellsWhichProgramItStarts() { var folder = context.CreateTempDirectory("links"); var target = Path.Combine(folder, "Product A", "Chronos.Uploader.exe"); Directory.CreateDirectory(Path.GetDirectoryName(target)!); File.WriteAllBytes(target, [0x4D, 0x5A]); var link = Path.Combine(folder, "Chronos Uploader.lnk"); ShellLink.Create(link, target, "Chronos Uploader"); // The shell may store the long form of a short (8.3) temporary path: the same file either way. var stored = Assert.NotNull(ShellLink.TargetOf(link)); Assert.Equal(Path.GetFileName(target), Path.GetFileName(stored)); Assert.FileExists(stored); var productA = Path.GetDirectoryName(stored)!; Assert.True(CommandProgram.IsPathInside(stored, productA)); Assert.False(CommandProgram.IsPathInside(stored, Path.Combine(Path.GetDirectoryName(productA)!, "Product B"))); Assert.False(CommandProgram.IsPathInside(stored, productA + " 2")); Assert.Null(ShellLink.TargetOf(Path.Combine(folder, "missing.lnk"))); var notALink = Path.Combine(folder, "not a link.lnk"); File.WriteAllText(notALink, "plain text"); Assert.Null(ShellLink.TargetOf(notALink)); } [Test] [WindowsOnly] public void AnUninstalledProductHandsItsShortcutToTheProductThatKeepsTheProgram() { var root = context.CreateTempDirectory("handover"); foreach (var product in (string[])["Product A", "Product B"]) { Directory.CreateDirectory(Path.Combine(root, product)); File.WriteAllBytes(Path.Combine(root, product, "Chronos.Uploader.exe"), [0x4D, 0x5A]); } // A uniquely named shortcut in the user's own Start menu, the only folder setup deletes shortcuts from. var link = Path.Combine(SetupPaths.StartMenu(InstallScope.CurrentUser), "Chronos Test " + Guid.NewGuid().ToString("N") + ".lnk"); try { ShellLink.Create(link, Path.Combine(root, "Product A", "Chronos.Uploader.exe"), "Chronos Test"); // The folders as the shell stores them (the long form of a short temporary path). var productA = Path.GetDirectoryName(Assert.NotNull(ShellLink.TargetOf(link)))!; var productB = Path.Combine(Path.GetDirectoryName(productA)!, "Product B"); var logB = new InstallLog { Product = "Chronos Uploader", Version = "1.0.0", Scope = InstallScope.CurrentUser, Files = ["Chronos.Uploader.exe"], Shortcuts = [link] }; // Product B also has the program and lists the shortcut: uninstalling A points it at B's copy. UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, [new OtherInstall(productB, logB)]); var handed = Assert.NotNull(ShellLink.TargetOf(link)); Assert.Equal("Product B", Path.GetFileName(Path.GetDirectoryName(handed))); // Uninstalling A again leaves B's shortcut alone; uninstalling B with nobody left deletes it. UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, []); Assert.FileExists(link); UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productB, [new OtherInstall(productA, null)]); Assert.FileMissing(link); // A product that does not list the shortcut, or whose folder cannot be read now, takes nothing over. ShellLink.Create(link, Path.Combine(productA, "Chronos.Uploader.exe"), "Chronos Test"); UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, [new OtherInstall(productB, new InstallLog { Product = "Chronos", Version = "1.0.0", Files = ["Chronos.Uploader.exe"] })]); Assert.FileMissing(link); } finally { if (File.Exists(link)) File.Delete(link); } } [Test] [WindowsOnly] public void TheServerMakesANewInstallationAnAllUsersOneInsideProgramFiles() { var manifest = Manifest(); var plan = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Chronos", "Server"] }); Assert.Equal(InstallScope.AllUsers, plan.Scope); Assert.Equal(SetupPaths.DefaultDirectory(InstallScope.AllUsers, manifest.Product), plan.Directory); Assert.True(InstallPlan.IsValidDirectory(manifest, plan.Scope, plan.Directory, plan.Components)); // A folder standard users can change (C:\Chronos, D:\Apps\Chronos) would let them replace what the service starts. var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); var custom = Path.Combine(Path.GetPathRoot(programFiles)!, "Chronos"); Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Chronos", "Server"])); Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Chronos"])); Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, custom, ["Chronos"])); Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, Path.Combine(programFiles, "Chronos"), ["Server"])); Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, Path.Combine(programFiles, "Vendor", "Chronos"), ["Server"])); Assert.False(SetupPaths.IsInsideProgramFiles(programFiles), "Program Files itself is shared by every program"); Assert.False(SetupPaths.IsInsideProgramFiles(programFiles + " Extra" + Path.DirectorySeparatorChar + "Chronos")); var desktop = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Chronos"] }); Assert.Equal(InstallScope.CurrentUser, desktop.Scope); Assert.True(desktop.CanInstall(manifest.FindComponent("Server")!)); // A per-user installation upgraded in place keeps its scope, so it cannot take the Server; nor can an // all-users one in a folder outside Program Files. var perUser = desktop with { Existing = new ExistingInstall(InstallScope.CurrentUser, desktop.Directory, "0.9.0") }; Assert.False(perUser.CanInstall(manifest.FindComponent("Server")!)); Assert.True(perUser.CanInstall(manifest.FindComponent("Chronos")!)); var elsewhere = desktop with { Existing = new ExistingInstall(InstallScope.AllUsers, custom, "0.9.0") }; Assert.False(elsewhere.CanInstall(manifest.FindComponent("Server")!)); var protectedFolder = desktop with { Existing = new ExistingInstall(InstallScope.AllUsers, Path.Combine(programFiles, "Chronos"), "0.9.0") }; Assert.True(protectedFolder.CanInstall(manifest.FindComponent("Server")!)); } [Test] public void TheProjectFileTypeIsNamedInSetupsLanguage() { var association = new PayloadAssociation { Component = "Chronos", Extension = ".chronos", ProgId = "Chronos.Project", Description = "Chronos project", Target = "Chronos.exe" }; Assert.Equal("Chronos project", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("en"))); Assert.Equal("Progetto Chronos", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("it"))); var unknown = new PayloadAssociation { Component = "Chronos", Extension = ".tlx", ProgId = "Chronos.Unknown", Description = "Something else", Target = "Chronos.exe" }; Assert.Equal("Something else", InstallEngine.FileTypeName(unknown, CultureInfo.GetCultureInfo("it"))); } /// Deletes a scratch key under , and that key too once it is empty. private static void DeleteTestKey(string keyPath) { Registry.CurrentUser.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false); bool empty; using (var tests = Registry.CurrentUser.OpenSubKey(TestsKey)) empty = tests is { SubKeyCount: 0, ValueCount: 0 }; if (empty) Registry.CurrentUser.DeleteSubKey(TestsKey, throwOnMissingSubKey: false); } /// A manifest under a product name no machine has installed, so the registry holds no installation of it. private static PayloadManifest Manifest() => new() { Product = "ChronosTest" + Guid.NewGuid().ToString("N")[..12], Version = "1.0.0", Components = [ new PayloadComponent { Id = "Chronos", DisplayName = "Chronos", DefaultSelected = true }, new PayloadComponent { Id = "Server", DisplayName = "Chronos Server", AllUsersOnly = true }, ], }; }