Files
Chronos/tests/Titano.App.Tests/Setup/SetupEngineTests.cs
T
Claude 067e8ca062 fix(setup): change only what starts a program setup installed; Server only inside Program Files
Services, sign-in entries and shortcuts are matched against the full paths of the files the install log or the
payload lists, never against everything under the install folder: an install into a shared folder such as D:\Apps
or /DIR="C:\Program Files" no longer stops, starts or deletes other vendors' services or removes their Run values.
The elevated step now takes the names the unelevated setup found (/SERVICES=... /NAMES=...) and reads each service
again, acting only when it still starts a program of the folder's log or of its own payload (or, for Prune, a
program of the folder that is gone).

Programs are asked to close before any service is touched. On uninstall the services are deleted only once the
programs have closed, just before the files go; a failed install or uninstall starts again the services it
stopped, and after an upgrade setup starts exactly the services it stopped, whatever their start type.

The Server component installs only for all users in a folder inside Program Files. In the window a custom folder
outside it is invalid while the Server is selected, with a tooltip saying why; silent mode refuses it. An upgrade
of an installation elsewhere cannot add the Server, and one it carried is dropped with its service.

Sign-in entries use StartupCommand (the same file as on fix/shell-notify) and are removed by
SetupRegistry.DeleteStartupEntries only when the client's or the Uploader's value starts a program the install log
lists; an upgrade that drops a program removes its entry too. StartupEntries is gone.

A shortcut that starts another product's existing copy is still left alone but now logged; uninstalling the
product it starts hands it to another product of the same scope that lists it and has the same program, so the
Uploader that stays keeps its shortcuts. Another registered Titano installation whose folder or log cannot be read
now counts as using every program's data, so "Remove my data" never offers it.

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

279 lines
16 KiB
C#

using System.Globalization;
using System.IO;
using Microsoft.Win32;
using Titano.Core.Packaging;
using Titano.Setup.Cli;
using Titano.Setup.Engine;
using Titano.Setup.Interop;
using Titano.Testing;
namespace Titano.App.Tests.Setup;
/// <summary>
/// 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).
/// </summary>
public sealed class SetupEngineTests(TestContext context)
{
private const string TestsKey = @"Software\Titano.Tests";
[Theory]
[Case(@"""C:\Program Files\Titano\Titano.Server.exe"" --service", @"C:\Program Files\Titano\Titano.Server.exe")]
[Case(@"C:\Program Files\Titano\Titano.Server.exe --service", @"C:\Program Files\Titano\Titano.Server.exe")]
[Case(@"""C:\Program Files\dotnet\dotnet.exe"" ""C:\Apps\Titano\Titano.Server.dll"" --service", @"C:\Apps\Titano\Titano.Server.dll")]
[Case(@"C:\Windows\system32\svchost.exe -k netsvcs", @"C:\Windows\system32\svchost.exe")]
[Case(@"Titano.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 = ["TitanoServer"],
Directory = @"C:\Program Files\Titano",
Elevated = true,
};
var switches = arguments.ToSwitches().ToList();
Assert.Contains("/SERVICES=prune,start", switches);
Assert.Contains("/NAMES=TitanoServer", switches);
var parsed = SetupArguments.Parse(switches);
Assert.Equal(arguments.Services, parsed.Services);
Assert.Equal(arguments.Directory, parsed.Directory);
Assert.SequenceEqual(["TitanoServer"], parsed.ServiceNames!);
Assert.True(parsed.Elevated);
Assert.Equal(ServiceActions.Remove, SetupArguments.Parse(["/SERVICES=Remove", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"]).Services);
// The step acts only on services the unelevated setup named.
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=stop", "/NAMES=TitanoServer"]));
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=stop", "/DIR=C:\\Apps\\Titano"]));
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=kill", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"]));
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=none", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"]));
}
[Test]
[WindowsOnly]
public void OnlyTheServicesOfProgramsSetupInstalledAreFound()
{
var folder = Path.Combine(context.CreateTempDirectory("services"), "Apps");
var owned = CommandProgram.FullPaths(folder, ["Titano.Server.exe", "Titano.exe", "lib/Titano.Core.dll"]);
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
try
{
using var services = Registry.CurrentUser.CreateSubKey(keyPath, writable: true);
Service(services, "TitanoServer", 0x10, $"\"{Path.Combine(folder, "Titano.Server.exe")}\" --service");
Service(services, "TitanoServerUnquoted", 0x10, Path.Combine(folder, "TITANO.SERVER.EXE") + " --service");
// Another vendor's service, and a driver, that live in the same folder (a shared D:\Apps): never Titano'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, "Titano.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, "Titano.Server.exe"), RegistryValueKind.ExpandString);
}
var found = InstalledServices.Find(services, owned);
Assert.SequenceEqual(["TitanoServer", "TitanoServerUnquoted"], found.Select(s => s.Name).Order(StringComparer.Ordinal));
Assert.True(found.All(s => s.Program.Equals(Path.Combine(folder, "Titano.Server.exe"), StringComparison.OrdinalIgnoreCase)));
Assert.Empty(InstalledServices.Find(services, CommandProgram.FullPaths(folder, ["Titano.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, ["Titano.Server.exe"])));
Assert.Equal(SetupExitCode.Success, InstalledServices.Apply([], ServiceActions.Remove));
var gone = new InstalledService("TitanoTest" + Guid.NewGuid().ToString("N"), "Titano Server", Path.Combine(folder, "Titano.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 UninstallRemovesOnlyTheSignInEntriesOfTheProgramsItRemoves()
{
var folder = Path.Combine(context.CreateTempDirectory("startup"), "Apps");
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
try
{
using (var run = Registry.CurrentUser.CreateSubKey(keyPath, writable: true))
{
run.SetValue("Titano Uploader", $"\"{Path.Combine(folder, "Uploader", "Titano.Uploader.exe")}\" --tray");
// A portable Titano unpacked in a subfolder of the same folder: not a program this installation lists.
run.SetValue("Titano", $"\"{Path.Combine(folder, "Portable", "Titano.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\\Titano.Uploader.exe\"");
var programs = CommandProgram.FullPaths(folder, ["Titano.exe", "Uploader/Titano.Uploader.exe", "Other.exe"]);
Assert.SequenceEqual(["Titano Uploader"], SetupRegistry.DeleteStartupEntries(run, programs));
Assert.SequenceEqual(["Other", "Sibling", "Titano"], run.GetValueNames().Order(StringComparer.Ordinal));
}
}
finally
{
DeleteTestKey(keyPath);
}
}
[Test]
[WindowsOnly]
public void AShortcutTellsWhichProgramItStarts()
{
var folder = context.CreateTempDirectory("links");
var target = Path.Combine(folder, "Product A", "Titano.Uploader.exe");
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
File.WriteAllBytes(target, [0x4D, 0x5A]);
var link = Path.Combine(folder, "Titano Uploader.lnk");
ShellLink.Create(link, target, "Titano 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, "Titano.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), "Titano Test " + Guid.NewGuid().ToString("N") + ".lnk");
try
{
ShellLink.Create(link, Path.Combine(root, "Product A", "Titano.Uploader.exe"), "Titano 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 = "Titano Uploader", Version = "1.0.0", Scope = InstallScope.CurrentUser, Files = ["Titano.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, "Titano.Uploader.exe"), "Titano Test");
UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, [new OtherInstall(productB, new InstallLog { Product = "Titano", Version = "1.0.0", Files = ["Titano.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 = ["Titano", "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:\Titano, D:\Apps\Titano) would let them replace what the service starts.
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
var custom = Path.Combine(Path.GetPathRoot(programFiles)!, "Titano");
Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Titano", "Server"]));
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Titano"]));
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, custom, ["Titano"]));
Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, Path.Combine(programFiles, "Titano"), ["Server"]));
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, Path.Combine(programFiles, "Vendor", "Titano"), ["Server"]));
Assert.False(SetupPaths.IsInsideProgramFiles(programFiles), "Program Files itself is shared by every program");
Assert.False(SetupPaths.IsInsideProgramFiles(programFiles + " Extra" + Path.DirectorySeparatorChar + "Titano"));
var desktop = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Titano"] });
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("Titano")!));
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, "Titano"), "0.9.0") };
Assert.True(protectedFolder.CanInstall(manifest.FindComponent("Server")!));
}
[Test]
public void TheProjectFileTypeIsNamedInSetupsLanguage()
{
var association = new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" };
Assert.Equal("Titano project", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("en")));
Assert.Equal("Progetto Titano", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("it")));
var unknown = new PayloadAssociation { Component = "Titano", Extension = ".tlx", ProgId = "Titano.Unknown", Description = "Something else", Target = "Titano.exe" };
Assert.Equal("Something else", InstallEngine.FileTypeName(unknown, CultureInfo.GetCultureInfo("it")));
}
/// <summary>Deletes a scratch key under <see cref="TestsKey"/>, and that key too once it is empty.</summary>
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);
}
/// <summary>A manifest under a product name no machine has installed, so the registry holds no installation of it.</summary>
private static PayloadManifest Manifest() => new()
{
Product = "TitanoTest" + Guid.NewGuid().ToString("N")[..12],
Version = "1.0.0",
Components =
[
new PayloadComponent { Id = "Titano", DisplayName = "Titano", DefaultSelected = true },
new PayloadComponent { Id = "Server", DisplayName = "Titano Server", AllUsersOnly = true },
],
};
}