diff --git a/README.md b/README.md index 637b17f..3ffadb8 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ shared between the two views and is never removed. Deliver a header through policy as usual. The next elevated run moves it into that key and blanks the copy in policy, which every user can read. The policy value is emptied, not deleted, so the setting still shows as managed. The GUI shows a saved header masked and saves a new one -only after Unlock. BootstrapMate never writes a header to its logs, `session.json` or +when you click Save on the Prefs tab. BootstrapMate never writes a header to its logs, `session.json` or `last-run.json`, and it redacts `--headers` from every logged command line. ## Reporting @@ -318,6 +318,14 @@ policy for each, and either one locks the Prefs tab's "Show progress dialog" swi sets the dialog's icon. `SilentMode` and `VerboseMode` from policy or settings turn those modes on, and a CLI switch cannot turn them off. +The GUI Prefs tab edits every setting that policy does not manage; policy-set fields show in gray +under one note at the top of the tab. Edits stay pending until you click Save, which writes them to +`HKLM\SOFTWARE\BootstrapMate\Settings`. An unelevated GUI asks for administrator approval at that +point and runs a headless, elevated copy of itself (`--apply-settings `). The values travel +over a named pipe that only the user, Administrators and SYSTEM can open, never through a file. +The writer re-reads policy and never writes a managed value. Declining the prompt keeps the edits +pending. + ## csharpDialog authorisation key When csharpDialog is managed with an authorisation key, it opens only for a caller that diff --git a/src/BootstrapMate.App/BootstrapMate.App.csproj b/src/BootstrapMate.App/BootstrapMate.App.csproj index a5341a8..f7b5304 100644 --- a/src/BootstrapMate.App/BootstrapMate.App.csproj +++ b/src/BootstrapMate.App/BootstrapMate.App.csproj @@ -25,6 +25,8 @@ $(NoWarn);MVVMTK0045 + + $(DefineConstants);DISABLE_XAML_GENERATED_MAIN diff --git a/src/BootstrapMate.App/MainWindow.xaml.cs b/src/BootstrapMate.App/MainWindow.xaml.cs index ea0256f..c0c4688 100644 --- a/src/BootstrapMate.App/MainWindow.xaml.cs +++ b/src/BootstrapMate.App/MainWindow.xaml.cs @@ -44,11 +44,8 @@ public MainWindow() // Apply Mica backdrop for modern Windows 11 look SystemBackdrop = new MicaBackdrop(); - // Open on Prefs when asked to (the elevated relaunch from Unlock passes --prefs); - // Prefs is also the first tab, so this is the default either way. - NavView.SelectedItem = BootstrapMate.Core.PrefsElevation.OpensOnPrefs(Environment.GetCommandLineArgs().Skip(1)) - ? NavView.MenuItems.OfType().First(i => (string?)i.Tag == "prefs") - : NavView.MenuItems[0]; + // Prefs is the first tab. + NavView.SelectedItem = NavView.MenuItems[0]; } private void NavView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args) diff --git a/src/BootstrapMate.App/Program.cs b/src/BootstrapMate.App/Program.cs new file mode 100644 index 0000000..faec52d --- /dev/null +++ b/src/BootstrapMate.App/Program.cs @@ -0,0 +1,31 @@ +using BootstrapMate.Core; + +namespace BootstrapMate.App; + +/// +/// Entry point. Replaces the XAML-generated Main (DISABLE_XAML_GENERATED_MAIN) so the elevated +/// settings writer (--apply-settings <pipe>) runs headless and exits before any window exists. +/// +public static class Program +{ + [STAThread] + private static int Main(string[] args) + { + if (PrefsSettingsWriter.IsApplyRequest(args)) + { + return PrefsSettingsWriter.ApplyPipeName(args) is { } pipeName + ? PrefsSettingsWriter.Apply(pipeName) + : PrefsSettingsWriter.ExitUsage; + } + + WinRT.ComWrappersSupport.InitializeComWrappers(); + Microsoft.UI.Xaml.Application.Start(p => + { + var context = new Microsoft.UI.Dispatching.DispatcherQueueSynchronizationContext( + Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread()); + SynchronizationContext.SetSynchronizationContext(context); + new App(); + }); + return 0; + } +} diff --git a/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs b/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs index 84771fc..3a520a5 100644 --- a/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs +++ b/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs @@ -6,13 +6,12 @@ namespace BootstrapMate.App.ViewModels; /// /// ViewModel for the Prefs tab. Mirrors macOS SettingsViewModel. -/// Loads from ConfigManager and shows management lock state. Settings live in HKLM, so the tab is -/// read-only unless this process is elevated; Unlock relaunches the app elevated on this tab. -/// When elevated, non-managed settings auto-save to HKLM through ConfigManager.SaveMachineSettings. +/// Loads from ConfigManager and shows management lock state. Every setting policy does not manage +/// is editable; edits stay pending until Save writes them to HKLM, directly when this process is +/// elevated and otherwise through an elevated, headless copy of the app (UAC at save time). /// public partial class PrefsViewModel : ObservableObject { - private System.Threading.Timer? _autoSaveTimer; private bool _isLoading; // ── Connection ─────────────────────────────────────────────── @@ -54,14 +53,14 @@ public partial class PrefsViewModel : ObservableObject [ObservableProperty] private SaveState _saveStatus = SaveState.Idle; - public enum SaveState { Idle, Saving, Saved, Failed } + public enum SaveState { Idle, Saving, Saved } partial void OnSaveStatusChanged(SaveState value) { - OnPropertyChanged(nameof(SaveStatusGlyph)); OnPropertyChanged(nameof(SaveStatusMessage)); OnPropertyChanged(nameof(IsSaveStatusVisible)); OnPropertyChanged(nameof(IsSaveEnabled)); + OnPropertyChanged(nameof(IsSaveBarVisible)); } // ── Management State ───────────────────────────────────────────── @@ -70,6 +69,32 @@ partial void OnSaveStatusChanged(SaveState value) public bool IsManaged(string key) => _managedKeys.Contains(key); + /// True when any value comes from the policy key; shows the policy note on the tab. + public bool HasPolicySettings => _managedKeys.Count > 0; + + // ── Services ───────────────────────────────────────────────── + + /// The services and scheduled tasks the installer creates, with their live state. + [ObservableProperty] private IReadOnlyList _services = []; + + [ObservableProperty] private bool _isServicesLoading; + + /// Queries the installer's services and tasks off the UI thread. + public async Task LoadServicesAsync() + { + if (IsServicesLoading) + return; + IsServicesLoading = true; + try + { + Services = await Task.Run(InstallFootprint.QueryAll); + } + finally + { + IsServicesLoading = false; + } + } + // ── Binding-Friendly Display Properties ────────────────────── public string VersionDisplay => $"Version {AppVersion}"; @@ -89,55 +114,138 @@ public double NetworkTimeoutValue partial void OnNetworkTimeoutChanged(int value) => OnPropertyChanged(nameof(NetworkTimeoutValue)); - // ── Policy Lock Properties (for x:Bind) ───────────────────── + // ── Pending Changes and Save ──────────────────────────────── + + /// True when this process can write HKLM directly (elevated administrator token). + private static readonly bool IsElevated = PrefsElevation.IsProcessElevated(); - // ── Elevation State ───────────────────────────────────────── + /// True once a setting is edited and until it is saved or discarded. + [ObservableProperty] private bool _hasPendingChanges; - /// True when this process can write HKLM (elevated administrator token). - public bool IsElevated { get; } = PrefsElevation.IsProcessElevated(); + /// Why the last Save did not write, as "Not saved: …"; empty otherwise. + [ObservableProperty] private string _saveError = ""; - public bool IsReadOnly => !IsElevated; + public bool HasSaveError => !string.IsNullOrEmpty(SaveError); - [ObservableProperty] private string _unlockError = ""; + partial void OnSaveErrorChanged(string value) + { + OnPropertyChanged(nameof(HasSaveError)); + OnPropertyChanged(nameof(IsSaveBarVisible)); + } - public bool HasUnlockError => !string.IsNullOrEmpty(UnlockError); + partial void OnHasPendingChangesChanged(bool value) => OnPropertyChanged(nameof(IsSaveBarVisible)); - partial void OnUnlockErrorChanged(string value) => OnPropertyChanged(nameof(HasUnlockError)); + /// The save bar shows while there is anything to save or report. + public bool IsSaveBarVisible => HasPendingChanges || HasSaveError || IsSaveStatusVisible; /// - /// Relaunches this app elevated through UAC, opening on the Prefs tab. Returns true when the - /// elevated instance started, so the caller can close this one. A cancelled UAC prompt - /// returns false quietly and leaves the tab read-only. + /// Writes the pending values to the machine settings, skipping anything policy manages. + /// Elevated, it writes directly; otherwise it raises UAC and runs this app's own executable + /// headless, sending the values over an ACL'd named pipe. A declined prompt keeps the edits pending. /// - public bool TryRelaunchElevated() + public async Task SaveAsync() { - UnlockError = ""; + if (!HasPendingChanges || SaveStatus == SaveState.Saving) + return; + + var payload = BuildPayload(); + if (PrefsSettingsWriter.Validate(payload) is { } invalid) + { + SaveError = $"Not saved: {invalid}"; + return; + } + + SaveError = ""; + SaveStatus = SaveState.Saving; + string? error; try { - var exe = Environment.ProcessPath; - if (string.IsNullOrEmpty(exe)) - { - UnlockError = "Could not find the app's own executable to relaunch."; - return false; - } + error = IsElevated + ? await Task.Run(() => { PrefsSettingsWriter.Save(payload, _managedKeys); return (string?)null; }) + : await SaveElevatedAsync(payload); + } + catch (Exception ex) + { + error = $"Not saved: {ex.Message}"; + } - using var process = System.Diagnostics.Process.Start(PrefsElevation.BuildElevatedRelaunch(exe)); - return process is not null; + if (error is not null) + { + SaveStatus = SaveState.Idle; + SaveError = error; + return; + } + + Load(); + SaveStatus = SaveState.Saved; + } + + /// Drops the pending edits and shows the saved values again. + public void Discard() + { + SaveError = ""; + SaveStatus = SaveState.Idle; + Load(); + } + + private static async Task SaveElevatedAsync(PrefsSettingsPayload payload) + { + var exe = Environment.ProcessPath; + if (string.IsNullOrEmpty(exe)) + return "Not saved: could not find the app's own executable."; + + // The values travel over a pipe only this user, Administrators and SYSTEM can open, + // never through a file: they can include a credential header. + var pipeName = PrefsSettingsWriter.NewPipeName(); + using var pipe = PrefsSettingsWriter.CreatePipe(pipeName); + + System.Diagnostics.Process? process; + try + { + process = System.Diagnostics.Process.Start(PrefsElevation.BuildElevatedApply(exe, pipeName)); } catch (Exception ex) when (PrefsElevation.IsElevationCancelled(ex)) { - return false; + return "Not saved: administrator approval was declined."; } - catch (Exception ex) + if (process is null) + return "Not saved: the elevated writer did not start."; + + using (process) { - UnlockError = $"Could not relaunch as administrator: {ex.Message}"; - return false; + using var timeout = new CancellationTokenSource(PrefsSettingsWriter.ConnectTimeout); + var send = PrefsSettingsWriter.SendAsync(pipe, payload, timeout.Token); + var exited = process.WaitForExitAsync(timeout.Token); + await Task.WhenAny(send, exited); + + if (!send.IsCompletedSuccessfully) + { + timeout.Cancel(); + try { await send; } catch { } + return process.HasExited + ? $"Not saved: {PrefsSettingsWriter.DescribeExitCode(process.ExitCode)}" + : "Not saved: the elevated writer did not connect in time."; + } + + using var finish = new CancellationTokenSource(PrefsSettingsWriter.ConnectTimeout); + try + { + await process.WaitForExitAsync(finish.Token); + } + catch (OperationCanceledException) + { + return "Not saved: the elevated writer did not finish in time."; + } + + return process.ExitCode == PrefsSettingsWriter.ExitSaved + ? null + : $"Not saved: {PrefsSettingsWriter.DescribeExitCode(process.ExitCode)}"; } } - // ── Editability (elevated and not managed by policy) ──────── + // ── Editability (only policy locks a setting) ─────────────── - private bool CanEdit(string field) => PrefsElevation.CanEdit(IsElevated, IsLocked(field)); + private bool CanEdit(string field) => PrefsPolicy.CanEdit(field, _managedKeys); private bool IsLocked(string field) => PrefsPolicy.IsLocked(field, _managedKeys); @@ -154,34 +262,12 @@ public bool TryRelaunchElevated() public bool CanEditCustomInstallPath => CanEdit("CustomInstallPath"); public bool CanEditNetworkTimeout => CanEdit("NetworkTimeout"); - public bool IsManifestUrlLocked => IsLocked("ManifestUrl"); - public bool IsAuthHeaderLocked => IsLocked("AuthorizationHeader"); - public bool IsSilentModeLocked => IsLocked("SilentMode"); - public bool IsVerboseModeLocked => IsLocked("VerboseMode"); - public bool IsDryRunLocked => IsLocked("DryRun"); - public bool IsEnableDialogLocked => IsLocked("EnableDialog"); - public bool IsDialogTitleLocked => IsLocked("DialogTitle"); - public bool IsDialogMessageLocked => IsLocked("DialogMessage"); - public bool IsDialogIconLocked => IsLocked("DialogIcon"); - public bool IsBlurScreenLocked => IsLocked("BlurScreen"); - public bool IsCustomInstallPathLocked => IsLocked("CustomInstallPath"); - public bool IsNetworkTimeoutLocked => IsLocked("NetworkTimeout"); - // ── Save Status Display (for x:Bind) ──────────────────────── - public string SaveStatusGlyph => SaveStatus switch - { - SaveState.Saving => "\uE895", - SaveState.Saved => "\uE73E", - SaveState.Failed => "\uE783", - _ => "" - }; - public string SaveStatusMessage => SaveStatus switch { SaveState.Saving => "Saving...", SaveState.Saved => "Saved", - SaveState.Failed => "Save failed — check permissions", _ => "" }; @@ -203,6 +289,7 @@ public void Load() var config = configMgr.Config; _managedKeys = ManagementDetector.Instance.AllManagedKeys(); + OnPropertyChanged(nameof(HasPolicySettings)); ManifestUrl = config.ManifestUrl ?? ""; HasExistingAuth = !string.IsNullOrEmpty(config.AuthorizationHeader); @@ -221,6 +308,7 @@ public void Load() // Notify all bindings (management locks, computed display properties) OnPropertyChanged(string.Empty); + HasPendingChanges = false; _isLoading = false; } @@ -228,12 +316,13 @@ public void Load() private static readonly HashSet _nonSettingProperties = [ - nameof(SaveStatus), nameof(SaveStatusGlyph), nameof(SaveStatusMessage), + nameof(SaveStatus), nameof(SaveStatusMessage), nameof(HasPendingChanges), + nameof(SaveError), nameof(HasSaveError), nameof(IsSaveBarVisible), nameof(IsSaveStatusVisible), nameof(IsSaveEnabled), nameof(HasExistingAuth), nameof(AuthPlaceholderText), nameof(NetworkTimeoutValue), nameof(VersionDisplay), nameof(IsManifestPreviewLoading), nameof(ManifestPreviewContent), nameof(ManifestPreviewError), nameof(HasManifestPreviewContent), nameof(HasManifestPreviewError), - nameof(UnlockError), nameof(HasUnlockError), + nameof(HasPolicySettings), nameof(Services), nameof(IsServicesLoading), "", // string.Empty from Load's bulk notify ]; @@ -241,15 +330,13 @@ protected override void OnPropertyChanged(System.ComponentModel.PropertyChangedE { base.OnPropertyChanged(e); - // Not elevated: HKLM is not writable and the tab is read-only, so never save. - if (_isLoading || !IsElevated || _nonSettingProperties.Contains(e.PropertyName ?? "")) + // A setting changed by the user: hold it until Save or Discard. + if (_isLoading || _nonSettingProperties.Contains(e.PropertyName ?? "")) return; - _autoSaveTimer?.Dispose(); - _autoSaveTimer = new System.Threading.Timer(_ => - { - try { ConfigManager.SaveMachineSettings(BuildConfig(), PageKeys); } catch { } - }, null, 500, System.Threading.Timeout.Infinite); + HasPendingChanges = true; + if (SaveStatus == SaveState.Saved) + SaveStatus = SaveState.Idle; } // ── Build Run Arguments ────────────────────────────────────── @@ -291,18 +378,7 @@ public List BuildRunArguments() // ── Private ────────────────────────────────────────────────── - /// - /// The machine settings this tab edits. Saving writes only these, so values the tab does not - /// show (reporting, signature checks, baseline interval) keep whatever HKLM already holds. - /// - private static readonly string[] PageKeys = - [ - "ManifestUrl", "AuthorizationHeader", "SilentMode", "VerboseMode", "DryRun", - "EnableDialog", "NoDialog", "DialogTitle", "DialogMessage", "DialogIcon", "BlurScreen", - "CustomInstallPath", "NetworkTimeout", - ]; - - private BootstrapMateConfig BuildConfig() => new() + private PrefsSettingsPayload BuildPayload() => new() { ManifestUrl = ManifestUrl, AuthorizationHeader = string.IsNullOrWhiteSpace(AuthorizationHeader) ? null : AuthorizationHeader, @@ -310,7 +386,6 @@ public List BuildRunArguments() VerboseMode = VerboseMode, DryRun = DryRun, EnableDialog = EnableDialog, - NoDialog = !EnableDialog, DialogTitle = DialogTitle, DialogMessage = DialogMessage, DialogIcon = string.IsNullOrWhiteSpace(DialogIcon) ? null : DialogIcon, diff --git a/src/BootstrapMate.App/Views/PrefsPage.xaml b/src/BootstrapMate.App/Views/PrefsPage.xaml index 91d213e..9c3fac9 100644 --- a/src/BootstrapMate.App/Views/PrefsPage.xaml +++ b/src/BootstrapMate.App/Views/PrefsPage.xaml @@ -3,15 +3,26 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="using:BootstrapMate.App.ViewModels" + xmlns:core="using:BootstrapMate.Core" NavigationCacheMode="Required"> + + + + - + @@ -40,62 +51,62 @@ HorizontalAlignment="Center" /> - - - - - - - - - - - - - - - - - + - - + + - + + + + + + + + + + + + + - - - - - - - - - + - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - + - - - - @@ -329,12 +265,77 @@ - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/BootstrapMate.App/Views/PrefsPage.xaml.cs b/src/BootstrapMate.App/Views/PrefsPage.xaml.cs index 8c79a76..1ec0f1a 100644 --- a/src/BootstrapMate.App/Views/PrefsPage.xaml.cs +++ b/src/BootstrapMate.App/Views/PrefsPage.xaml.cs @@ -26,18 +26,26 @@ protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); ViewModel.Load(); + _ = ViewModel.LoadServicesAsync(); } - private void UnlockButton_Click(object sender, RoutedEventArgs e) + private async void SaveButton_Click(object sender, RoutedEventArgs e) { - // Once the elevated copy has started (UAC accepted), this read-only instance closes. - // A cancelled UAC prompt returns false and the tab simply stays read-only. - if (ViewModel.TryRelaunchElevated()) - Application.Current.Exit(); + await ViewModel.SaveAsync(); + } + + private void DiscardButton_Click(object sender, RoutedEventArgs e) + { + ViewModel.Discard(); } private async void PreviewManifestButton_Click(object sender, RoutedEventArgs e) { await ViewModel.FetchManifestPreviewAsync(); } + + private async void RefreshServicesButton_Click(object sender, RoutedEventArgs e) + { + await ViewModel.LoadServicesAsync(); + } } diff --git a/src/BootstrapMate.Core/InstallFootprint.cs b/src/BootstrapMate.Core/InstallFootprint.cs new file mode 100644 index 0000000..c2823b3 --- /dev/null +++ b/src/BootstrapMate.Core/InstallFootprint.cs @@ -0,0 +1,237 @@ +using System.Globalization; +using System.Xml; +using System.Xml.Linq; + +namespace BootstrapMate.Core; + +/// A Windows service or scheduled task the installer creates. +public enum FootprintKind { Service, ScheduledTask } + +/// One entry of the installer's footprint: what it is called and what it is for. +public sealed record FootprintItem(string FriendlyName, string Name, FootprintKind Kind, string Description); + +/// The live state of one footprint entry, already in plain words for display. +public sealed record FootprintStatus( + string FriendlyName, string Name, string KindText, string Description, + string State, string LastResult, string Trigger); + +/// +/// The Windows services and scheduled tasks the MSI installs, and a read-only look at their +/// current state for the Prefs tab. The list is the installer's own (installer/Product.wxs): +/// it registers one scheduled task and no services. Querying never needs elevation; anything +/// the caller may not read shows as "Unknown". +/// +public static class InstallFootprint +{ + public const string SelfHealTaskName = "BootstrapMate Self-Heal"; + + public static readonly IReadOnlyList Items = + [ + new("Daily self-heal", SelfHealTaskName, FootprintKind.ScheduledTask, + "Re-runs the bootstrap as SYSTEM so missing packages are reinstalled."), + ]; + + // Task Scheduler result codes that are not failures. + private const int SchedTaskHasNotRun = 0x00041303; + private const int SchedTaskRunning = 0x00041301; + + private const int HResultFileNotFound = unchecked((int)0x80070002); + private const int HResultPathNotFound = unchecked((int)0x80070003); + + private static readonly XNamespace TaskNs = "http://schemas.microsoft.com/windows/2004/02/mit/task"; + + /// Queries every footprint entry. Blocking; call it off the UI thread. + public static IReadOnlyList QueryAll() => Items.Select(Query).ToList(); + + private static FootprintStatus Query(FootprintItem item) => item.Kind switch + { + FootprintKind.ScheduledTask => QueryTask(item), + // The installer registers no services, so there is nothing to query here yet. + _ => Row(item, "Unknown", "—", "—"), + }; + + private static FootprintStatus QueryTask(FootprintItem item) + { + try + { + var type = Type.GetTypeFromProgID("Schedule.Service"); + if (type is null) + return Row(item, "Unknown", "—", "—"); + + dynamic service = Activator.CreateInstance(type)!; + service.Connect(); + dynamic task = service.GetFolder("\\").GetTask(item.Name); + + int state = task.State; + DateTime lastRun = task.LastRunTime; + int lastResult = task.LastTaskResult; + string xml = task.Xml; + + return Row(item, DescribeTaskState(state), DescribeTaskResult(lastRun, lastResult), DescribeTaskTriggers(xml)); + } + catch (Exception ex) when (ex.HResult is HResultFileNotFound or HResultPathNotFound) + { + return Row(item, "Not installed", "—", "—"); + } + catch (Exception) + { + // Access denied for a standard user, or the scheduler is unavailable. + return Row(item, "Unknown", "Unknown", "Unknown"); + } + } + + private static FootprintStatus Row(FootprintItem item, string state, string lastResult, string trigger) => + new(item.FriendlyName, item.Name, DescribeKind(item.Kind), item.Description, state, lastResult, trigger); + + // ── Plain-words formatting ─────────────────────────────────── + + public static string DescribeKind(FootprintKind kind) => + kind == FootprintKind.Service ? "Service" : "Scheduled task"; + + /// Task Scheduler TASK_STATE value in words. + public static string DescribeTaskState(int state) => state switch + { + 1 => "Disabled", + 2 => "Ready", // queued to run + 3 => "Ready", + 4 => "Running", + _ => "Unknown", + }; + + /// + /// Last run time and result in words: "Never run", or "Succeeded" / "Failed (0x…)" with the + /// run time. The scheduler reports a task that has never run with a zero date or 0x41303. + /// + public static string DescribeTaskResult(DateTime lastRun, int lastResult) + { + if (lastResult == SchedTaskHasNotRun || lastRun.Year < 2000) + return "Never run"; + + var outcome = lastResult switch + { + 0 => "Succeeded", + SchedTaskRunning => "Running", + _ => $"Failed (0x{lastResult:X8})", + }; + return $"{outcome} — {lastRun.ToString("MMM d, yyyy h:mm tt", CultureInfo.InvariantCulture)}"; + } + + /// A service start type in words ("Starts automatically at boot", …). + public static string DescribeStartType(string startType, bool delayed) => startType switch + { + "Automatic" when delayed => "Starts automatically (delayed) at boot", + "Automatic" => "Starts automatically at boot", + "Boot" or "System" => "Starts with Windows", + "Manual" => "Starts manually", + "Disabled" => "Disabled", + _ => "Unknown", + }; + + /// A stopped service's Win32 exit code in words; "—" while it runs. + public static string DescribeServiceResult(bool running, int win32ExitCode) => + running ? "—" : $"Exit code {win32ExitCode}"; + + /// + /// The enabled triggers of a task definition (Task Scheduler XML) in words, joined with "; ". + /// + public static string DescribeTaskTriggers(string taskXml) + { + XDocument doc; + try { doc = XDocument.Parse(taskXml); } + catch (XmlException) { return "Unknown"; } + + var triggers = doc.Root?.Element(TaskNs + "Triggers")?.Elements() ?? []; + var words = triggers + .Where(t => !string.Equals((string?)t.Element(TaskNs + "Enabled"), "false", StringComparison.OrdinalIgnoreCase)) + .Select(DescribeTrigger) + .ToList(); + + return words.Count == 0 ? "On demand only" : string.Join("; ", words); + } + + private static string DescribeTrigger(XElement trigger) + { + var text = trigger.Name.LocalName switch + { + "BootTrigger" => "At startup", + "LogonTrigger" => trigger.Element(TaskNs + "UserId") is { } user + ? $"At logon of {user.Value}" + : "At logon of any user", + "TimeTrigger" => $"Once at {FormatBoundary(trigger)}", + "CalendarTrigger" => DescribeCalendar(trigger), + "IdleTrigger" => "When the computer is idle", + "EventTrigger" => "On an event log entry", + "RegistrationTrigger" => "When the task is created or changed", + "SessionStateChangeTrigger" => "On a session change", + _ => "On a custom trigger", + }; + + var interval = (string?)trigger.Element(TaskNs + "Repetition")?.Element(TaskNs + "Interval"); + if (!string.IsNullOrEmpty(interval) && TryDuration(interval, out var every)) + text += $", then every {every}"; + return text; + } + + private static string DescribeCalendar(XElement trigger) + { + var at = $"at {FormatTime(trigger)}"; + + if (trigger.Element(TaskNs + "ScheduleByDay") is { } byDay) + { + var days = (int?)byDay.Element(TaskNs + "DaysInterval") ?? 1; + return days == 1 ? $"Daily {at}" : $"Every {days} days {at}"; + } + if (trigger.Element(TaskNs + "ScheduleByWeek") is { } byWeek) + { + var weeks = (int?)byWeek.Element(TaskNs + "WeeksInterval") ?? 1; + var names = byWeek.Element(TaskNs + "DaysOfWeek")?.Elements().Select(d => d.Name.LocalName).ToList() ?? []; + var prefix = weeks == 1 ? "Weekly" : $"Every {weeks} weeks"; + return names.Count == 0 ? $"{prefix} {at}" : $"{prefix} on {string.Join(", ", names)} {at}"; + } + if (trigger.Element(TaskNs + "ScheduleByMonth") is not null + || trigger.Element(TaskNs + "ScheduleByMonthDayOfWeek") is not null) + return $"Monthly {at}"; + + return $"On a schedule {at}"; + } + + private static string FormatTime(XElement trigger) => + TryBoundary(trigger, out var start) + ? start.ToString("h:mm tt", CultureInfo.InvariantCulture) + : "an unknown time"; + + private static string FormatBoundary(XElement trigger) => + TryBoundary(trigger, out var start) + ? start.ToString("MMM d, yyyy h:mm tt", CultureInfo.InvariantCulture) + : "an unknown time"; + + // StartBoundary is local wall-clock time, sometimes with an offset; the wall-clock part is + // what the scheduler shows, so the offset is ignored rather than converted. + private static bool TryBoundary(XElement trigger, out DateTime start) + { + start = default; + var raw = (string?)trigger.Element(TaskNs + "StartBoundary"); + if (string.IsNullOrEmpty(raw) || raw.Length < 19) + return false; + return DateTime.TryParseExact(raw[..19], "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture, + DateTimeStyles.None, out start); + } + + private static bool TryDuration(string iso, out string words) + { + words = ""; + TimeSpan span; + try { span = XmlConvert.ToTimeSpan(iso); } + catch (FormatException) { return false; } + + words = span switch + { + { TotalDays: >= 1 } when span.TotalDays % 1 == 0 => Plural((int)span.TotalDays, "day"), + { TotalHours: >= 1 } when span.TotalHours % 1 == 0 => Plural((int)span.TotalHours, "hour"), + _ => Plural((int)span.TotalMinutes, "minute"), + }; + return true; + } + + private static string Plural(int n, string unit) => n == 1 ? unit : $"{n} {unit}s"; +} diff --git a/src/BootstrapMate.Core/PrefsElevation.cs b/src/BootstrapMate.Core/PrefsElevation.cs index ae8bfc6..307cfd3 100644 --- a/src/BootstrapMate.Core/PrefsElevation.cs +++ b/src/BootstrapMate.Core/PrefsElevation.cs @@ -5,27 +5,15 @@ namespace BootstrapMate.Core; /// -/// Decisions behind the GUI's read-only Prefs tab. Settings live in HKLM, so they can only be -/// changed by an elevated process: a non-elevated GUI shows them read-only and "Unlock" -/// relaunches the app itself through UAC, opening straight on the Prefs tab. +/// Elevation for saving the GUI Prefs tab. Settings live in HKLM, so an unelevated GUI raises +/// UAC only when the user clicks Save: it relaunches its own executable elevated and headless +/// to write the pending values (see ). /// public static class PrefsElevation { - /// Command-line switch that opens the GUI on the Prefs tab. - public const string PrefsArgument = "--prefs"; - /// Win32 ERROR_CANCELLED: the user dismissed the UAC prompt. public const int ErrorCancelled = 1223; - /// True when the command line asks the GUI to open on the Prefs tab. - public static bool OpensOnPrefs(IEnumerable? args) - => args?.Any(a => string.Equals(a?.Trim(), PrefsArgument, StringComparison.OrdinalIgnoreCase)) == true; - - /// - /// A setting can be edited only by an elevated process, and never when policy manages it. - /// - public static bool CanEdit(bool isElevated, bool isPolicyManaged) => isElevated && !isPolicyManaged; - /// True when the exception is the user cancelling the UAC prompt, not a real failure. public static bool IsElevationCancelled(Exception? ex) => ex is Win32Exception { NativeErrorCode: ErrorCancelled }; @@ -47,14 +35,18 @@ public static bool IsProcessElevated() } } - /// Start info that relaunches elevated on the Prefs tab. - public static ProcessStartInfo BuildElevatedRelaunch(string exePath) + /// + /// Start info that runs elevated and headless to write the + /// settings sent over the named pipe . + /// + public static ProcessStartInfo BuildElevatedApply(string exePath, string pipeName) { ArgumentException.ThrowIfNullOrWhiteSpace(exePath); + ArgumentException.ThrowIfNullOrWhiteSpace(pipeName); return new ProcessStartInfo { FileName = exePath, - Arguments = PrefsArgument, + Arguments = $"{PrefsSettingsWriter.ApplyArgument} \"{pipeName}\"", UseShellExecute = true, Verb = "runas", WorkingDirectory = Path.GetDirectoryName(exePath) ?? string.Empty, diff --git a/src/BootstrapMate.Core/PrefsPolicy.cs b/src/BootstrapMate.Core/PrefsPolicy.cs index a500196..79c359b 100644 --- a/src/BootstrapMate.Core/PrefsPolicy.cs +++ b/src/BootstrapMate.Core/PrefsPolicy.cs @@ -32,6 +32,11 @@ public static bool IsLocked(string field, IReadOnlySet managedKeys) return keys.Any(managedKeys.Contains); } + /// + /// A field is editable unless policy manages it; elevation is asked for only at save time. + /// + public static bool CanEdit(string field, IReadOnlySet managedKeys) => !IsLocked(field, managedKeys); + /// /// Whether the progress dialog is shown: EnableDialog false or NoDialog true /// turns it off, wherever each comes from. diff --git a/src/BootstrapMate.Core/PrefsSettingsWriter.cs b/src/BootstrapMate.Core/PrefsSettingsWriter.cs new file mode 100644 index 0000000..d1a0dbf --- /dev/null +++ b/src/BootstrapMate.Core/PrefsSettingsWriter.cs @@ -0,0 +1,206 @@ +using System.IO.Pipes; +using System.Security.Principal; +using System.Text; +using System.Text.Json; + +namespace BootstrapMate.Core; + +/// The values the GUI Prefs tab edits, as handed to the elevated writer. +public sealed class PrefsSettingsPayload +{ + public string? ManifestUrl { get; set; } + /// A new header to save; null or empty keeps the saved one. + public string? AuthorizationHeader { get; set; } + public bool SilentMode { get; set; } + public bool VerboseMode { get; set; } + public bool DryRun { get; set; } + public bool EnableDialog { get; set; } = true; + public string DialogTitle { get; set; } = BootstrapMateConstants.DefaultDialogTitle; + public string DialogMessage { get; set; } = BootstrapMateConstants.DefaultDialogMessage; + public string? DialogIcon { get; set; } + public bool BlurScreen { get; set; } + public string? CustomInstallPath { get; set; } + public int NetworkTimeout { get; set; } = BootstrapMateConstants.DefaultNetworkTimeout; +} + +/// +/// Saving the Prefs tab. Settings live in HKLM, so an unelevated GUI relaunches its own executable +/// elevated with and a pipe name, then sends the pending values as JSON +/// over that named pipe; nothing touches disk, since the values can include a credential header. +/// The pipe admits only the current user, Administrators and SYSTEM, so an over-the-shoulder admin +/// account can read it. The headless writer re-reads policy itself, never writes a policy-managed +/// value, and exits without a window. +/// +public static class PrefsSettingsWriter +{ + /// Command-line switch, followed by the pipe name, for the headless writer. + public const string ApplyArgument = "--apply-settings"; + + public const int ExitSaved = 0; + public const int ExitFailed = 1; + public const int ExitUsage = 2; + public const int ExitInvalid = 3; + + /// How long either side waits for the other; covers the UAC prompt. + public static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(60); + + public const int MinNetworkTimeout = 10; + public const int MaxNetworkTimeout = 600; + + private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = false }; + + /// True when the command line asks for the headless writer. + public static bool IsApplyRequest(IReadOnlyList args) => + args.Any(a => string.Equals(a?.Trim(), ApplyArgument, StringComparison.OrdinalIgnoreCase)); + + /// The pipe name that follows , or null when missing. + public static string? ApplyPipeName(IReadOnlyList args) + { + for (var i = 0; i < args.Count - 1; i++) + { + if (string.Equals(args[i]?.Trim(), ApplyArgument, StringComparison.OrdinalIgnoreCase) + && !string.IsNullOrWhiteSpace(args[i + 1])) + return args[i + 1]; + } + return null; + } + + public static string Serialize(PrefsSettingsPayload payload) => JsonSerializer.Serialize(payload, JsonOptions); + + public static PrefsSettingsPayload? Deserialize(string json) => + JsonSerializer.Deserialize(json, JsonOptions); + + /// The GUI's own rules; null when the payload is valid, otherwise why it is not. + public static string? Validate(PrefsSettingsPayload payload) + { + if (payload.NetworkTimeout is < MinNetworkTimeout or > MaxNetworkTimeout) + return $"Network timeout must be between {MinNetworkTimeout} and {MaxNetworkTimeout} seconds."; + return null; + } + + /// + /// The machine-settings keys the Prefs tab writes, minus every key whose field policy + /// manages. A blank header is left out so the saved one is kept. + /// + public static IReadOnlyList WritableKeys(PrefsSettingsPayload payload, IReadOnlySet managedKeys) + { + var keys = new List(); + foreach (var field in PrefsPolicy.FieldKeys.Keys) + { + if (PrefsPolicy.IsLocked(field, managedKeys)) + continue; + if (field == "AuthorizationHeader" && string.IsNullOrEmpty(payload.AuthorizationHeader)) + continue; + keys.Add(field); + // The "Show progress dialog" switch is stored as both EnableDialog and NoDialog. + if (field == "EnableDialog") + keys.Add("NoDialog"); + } + return keys; + } + + public static BootstrapMateConfig ToConfig(PrefsSettingsPayload payload) => new() + { + ManifestUrl = payload.ManifestUrl, + AuthorizationHeader = string.IsNullOrWhiteSpace(payload.AuthorizationHeader) ? null : payload.AuthorizationHeader, + SilentMode = payload.SilentMode, + VerboseMode = payload.VerboseMode, + DryRun = payload.DryRun, + EnableDialog = payload.EnableDialog, + NoDialog = !payload.EnableDialog, + DialogTitle = payload.DialogTitle, + DialogMessage = payload.DialogMessage, + DialogIcon = string.IsNullOrWhiteSpace(payload.DialogIcon) ? null : payload.DialogIcon, + BlurScreen = payload.BlurScreen, + CustomInstallPath = string.IsNullOrWhiteSpace(payload.CustomInstallPath) ? null : payload.CustomInstallPath, + NetworkTimeout = payload.NetworkTimeout, + }; + + /// Writes the payload where the current policy allows. Needs an elevated process. + public static void Save(PrefsSettingsPayload payload, IReadOnlySet managedKeys) => + ConfigManager.SaveMachineSettings(ToConfig(payload), WritableKeys(payload, managedKeys)); + + /// A new, unguessable pipe name for one save. + public static string NewPipeName() => $"BootstrapMate-settings-{Guid.NewGuid():N}"; + + /// + /// Creates the one-instance outbound pipe the GUI sends the payload on. Only the current + /// user, BUILTIN\Administrators and SYSTEM may open it. + /// + public static NamedPipeServerStream CreatePipe(string pipeName) + { + var security = new PipeSecurity(); + using (var identity = WindowsIdentity.GetCurrent()) + { + security.AddAccessRule(new PipeAccessRule(identity.User!, PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow)); + } + foreach (var sid in new[] { WellKnownSidType.BuiltinAdministratorsSid, WellKnownSidType.LocalSystemSid }) + { + security.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(sid, null), + PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow)); + } + return NamedPipeServerStreamAcl.Create(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, + PipeOptions.Asynchronous, 0, 0, security); + } + + /// Waits for the writer to connect, sends the payload and closes the pipe. + public static async Task SendAsync(NamedPipeServerStream pipe, PrefsSettingsPayload payload, CancellationToken cancellationToken) + { + await pipe.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false); + var bytes = Encoding.UTF8.GetBytes(Serialize(payload)); + await pipe.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); + await pipe.FlushAsync(cancellationToken).ConfigureAwait(false); + pipe.WaitForPipeDrain(); + pipe.Disconnect(); + } + + /// Connects to the GUI's pipe and reads the payload JSON to the end. + public static string Receive(string pipeName, TimeSpan timeout) + { + using var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In); + client.Connect((int)timeout.TotalMilliseconds); + using var reader = new StreamReader(client, Encoding.UTF8); + return reader.ReadToEnd(); + } + + /// + /// The headless writer: reads the payload from the pipe, re-reads policy, validates and saves. + /// Never creates a window. Returns one of the Exit* codes. + /// + public static int Apply(string pipeName) => Apply(pipeName, ConnectTimeout); + + public static int Apply(string pipeName, TimeSpan timeout) + { + PrefsSettingsPayload? payload; + try + { + payload = Deserialize(Receive(pipeName, timeout)); + } + catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException or JsonException) + { + return ExitUsage; + } + + if (payload is null || Validate(payload) is not null) + return ExitInvalid; + + try + { + Save(payload, ManagementDetector.Instance.AllManagedKeys()); + return ExitSaved; + } + catch + { + return ExitFailed; + } + } + + /// Why the headless writer did not save, for the "Not saved: …" caption. + public static string DescribeExitCode(int code) => code switch + { + ExitSaved => "saved", + ExitUsage => "the settings could not be passed to the elevated writer.", + ExitInvalid => "a value is not valid.", + _ => $"the machine settings could not be written (exit code {code}).", + }; +} diff --git a/tests/BootstrapMate.Core.Tests/InstallFootprintTests.cs b/tests/BootstrapMate.Core.Tests/InstallFootprintTests.cs new file mode 100644 index 0000000..62146a9 --- /dev/null +++ b/tests/BootstrapMate.Core.Tests/InstallFootprintTests.cs @@ -0,0 +1,121 @@ +using BootstrapMate.Core; +using Xunit; + +namespace BootstrapMate.Core.Tests; + +public class InstallFootprintTests +{ + private static string TaskXml(string triggers) => $""" + + + {triggers} + + """.Trim(); + + [Fact] + public void TheFootprintIsTheSelfHealTaskTheInstallerRegisters() + { + var item = Assert.Single(InstallFootprint.Items); + Assert.Equal("BootstrapMate Self-Heal", item.Name); + Assert.Equal(FootprintKind.ScheduledTask, item.Kind); + } + + [Theory] + [InlineData("Automatic", false, "Starts automatically at boot")] + [InlineData("Automatic", true, "Starts automatically (delayed) at boot")] + [InlineData("Manual", false, "Starts manually")] + [InlineData("Disabled", false, "Disabled")] + [InlineData("Something", false, "Unknown")] + public void StartTypesReadAsWords(string startType, bool delayed, string expected) => + Assert.Equal(expected, InstallFootprint.DescribeStartType(startType, delayed)); + + [Theory] + [InlineData(1, "Disabled")] + [InlineData(3, "Ready")] + [InlineData(4, "Running")] + [InlineData(0, "Unknown")] + public void TaskStatesReadAsWords(int state, string expected) => + Assert.Equal(expected, InstallFootprint.DescribeTaskState(state)); + + [Fact] + public void ASuccessfulRunShowsSucceededWithItsTime() => + Assert.Equal("Succeeded — Oct 12, 2026 3:00 AM", + InstallFootprint.DescribeTaskResult(new DateTime(2026, 10, 12, 3, 0, 0), 0)); + + [Fact] + public void AFailedRunShowsItsHexCode() => + Assert.StartsWith("Failed (0x00000002)", + InstallFootprint.DescribeTaskResult(new DateTime(2026, 10, 12, 3, 0, 0), 2)); + + [Fact] + public void ANegativeResultShowsAsAnHResult() => + Assert.StartsWith("Failed (0x80070005)", + InstallFootprint.DescribeTaskResult(new DateTime(2026, 10, 12, 3, 0, 0), unchecked((int)0x80070005))); + + [Theory] + [InlineData(0x41303)] + [InlineData(0)] + public void ATaskThatHasNotRunSaysSo(int result) => + Assert.Equal("Never run", InstallFootprint.DescribeTaskResult(new DateTime(1899, 12, 30), result)); + + [Theory] + [InlineData(false, 1067, "Exit code 1067")] + [InlineData(true, 0, "—")] + public void ServiceResultsReadAsWords(bool running, int code, string expected) => + Assert.Equal(expected, InstallFootprint.DescribeServiceResult(running, code)); + + [Fact] + public void TheSelfHealScheduleReadsAsDailyAtThree() => + Assert.Equal("Daily at 3:00 AM", InstallFootprint.DescribeTaskTriggers(TaskXml(""" + + 2026-10-12T03:00:00 + true + 1 + + """))); + + [Fact] + public void EveryFewDaysNamesTheInterval() => + Assert.Equal("Every 3 days at 9:30 PM", InstallFootprint.DescribeTaskTriggers(TaskXml(""" + + 2026-10-12T21:30:00-07:00 + 3 + + """))); + + [Fact] + public void WeeklyListsItsDays() => + Assert.Equal("Weekly on Monday, Friday at 8:00 AM", InstallFootprint.DescribeTaskTriggers(TaskXml(""" + + 2026-10-12T08:00:00 + 1 + + """))); + + [Fact] + public void StartupLogonAndRepetitionReadAsWords() => + Assert.Equal("At startup; At logon of any user; Once at Oct 12, 2026 12:00 AM, then every 4 hours", + InstallFootprint.DescribeTaskTriggers(TaskXml(""" + + + + 2026-10-12T00:00:00 + PT4H + + """))); + + [Fact] + public void DisabledTriggersAreLeftOut() => + Assert.Equal("At startup", InstallFootprint.DescribeTaskTriggers(TaskXml(""" + + false + """))); + + [Fact] + public void ATaskWithNoTriggersRunsOnDemand() => + Assert.Equal("On demand only", InstallFootprint.DescribeTaskTriggers(TaskXml(""))); + + [Fact] + public void UnreadableXmlIsUnknown() => + Assert.Equal("Unknown", InstallFootprint.DescribeTaskTriggers(" - args.Length == 0 ? [] : args.Split('|'); + private static HashSet Managed(params string[] keys) => + new(keys, StringComparer.OrdinalIgnoreCase); - [Theory] - [InlineData("--prefs")] - [InlineData("--PREFS")] - [InlineData(" --prefs ")] - [InlineData("--verbose|--prefs")] - public void ThePrefsSwitchOpensOnPrefs(string args) => - Assert.True(PrefsElevation.OpensOnPrefs(Split(args))); - - [Theory] - [InlineData("")] - [InlineData("--prefsx")] - [InlineData("prefs")] - [InlineData("--verbose|--run")] - public void AnythingElseDoesNot(string args) => - Assert.False(PrefsElevation.OpensOnPrefs(Split(args))); + [Fact] + public void AnUnmanagedSettingIsEditableWithoutElevation() => + Assert.True(PrefsPolicy.CanEdit("DialogTitle", Managed())); [Fact] - public void NullArgsDoNotOpenOnPrefs() => - Assert.False(PrefsElevation.OpensOnPrefs(null)); + public void AManagedSettingIsNotEditable() => + Assert.False(PrefsPolicy.CanEdit("DialogTitle", Managed("DialogTitle"))); - [Theory] - [InlineData(true, false, true)] - [InlineData(true, true, false)] - [InlineData(false, false, false)] - [InlineData(false, true, false)] - public void OnlyElevatedAndUnmanagedSettingsAreEditable(bool elevated, bool managed, bool expected) => - Assert.Equal(expected, PrefsElevation.CanEdit(elevated, managed)); + [Fact] + public void NoDialogPolicyLocksTheShowDialogSwitch() => + Assert.False(PrefsPolicy.CanEdit("EnableDialog", Managed("NoDialog"))); [Fact] public void DismissingUacIsACancelNotAFailure() @@ -48,19 +31,23 @@ public void DismissingUacIsACancelNotAFailure() } [Fact] - public void RelaunchRunsTheSameExeElevatedOnPrefs() + public void SaveRunsTheSameExeElevatedAndHeadless() { var exe = @"C:\Program Files\BootstrapMate\Managed Bootstrap Install.exe"; - var info = PrefsElevation.BuildElevatedRelaunch(exe); + var pipe = "BootstrapMate-settings-1"; + var info = PrefsElevation.BuildElevatedApply(exe, pipe); Assert.Equal(exe, info.FileName); - Assert.Equal("--prefs", info.Arguments); + Assert.Equal("--apply-settings \"BootstrapMate-settings-1\"", info.Arguments); Assert.Equal("runas", info.Verb); Assert.True(info.UseShellExecute); Assert.Equal(@"C:\Program Files\BootstrapMate", info.WorkingDirectory); } [Fact] - public void RelaunchNeedsAnExe() => - Assert.ThrowsAny(() => PrefsElevation.BuildElevatedRelaunch(" ")); + public void SaveNeedsAnExeAndAPipe() + { + Assert.ThrowsAny(() => PrefsElevation.BuildElevatedApply(" ", "pipe")); + Assert.ThrowsAny(() => PrefsElevation.BuildElevatedApply("app.exe", "")); + } } diff --git a/tests/BootstrapMate.Core.Tests/PrefsSettingsWriterTests.cs b/tests/BootstrapMate.Core.Tests/PrefsSettingsWriterTests.cs new file mode 100644 index 0000000..5f94be8 --- /dev/null +++ b/tests/BootstrapMate.Core.Tests/PrefsSettingsWriterTests.cs @@ -0,0 +1,145 @@ +using BootstrapMate.Core; +using Xunit; + +namespace BootstrapMate.Core.Tests; + +public class PrefsSettingsWriterTests +{ + private static HashSet Managed(params string[] keys) => + new(keys, StringComparer.OrdinalIgnoreCase); + + private static PrefsSettingsPayload Sample() => new() + { + ManifestUrl = "https://example.com/bootstrap.json", + AuthorizationHeader = "Bearer abc", + SilentMode = true, + VerboseMode = true, + DryRun = false, + EnableDialog = false, + DialogTitle = "Title", + DialogMessage = "Message", + DialogIcon = @"C:\icon.png", + BlurScreen = true, + CustomInstallPath = @"D:\BootstrapMate", + NetworkTimeout = 120, + }; + + [Fact] + public void ThePayloadRoundTripsThroughJson() + { + var original = Sample(); + var copy = PrefsSettingsWriter.Deserialize(PrefsSettingsWriter.Serialize(original)); + + Assert.NotNull(copy); + Assert.Equivalent(original, copy, strict: true); + } + + [Fact] + public async Task ThePayloadRoundTripsThroughTheNamedPipe() + { + var name = PrefsSettingsWriter.NewPipeName(); + using var pipe = PrefsSettingsWriter.CreatePipe(name); + var send = PrefsSettingsWriter.SendAsync(pipe, Sample(), CancellationToken.None); + + var json = await Task.Run(() => PrefsSettingsWriter.Receive(name, TimeSpan.FromSeconds(10))); + await send; + + Assert.Equivalent(Sample(), PrefsSettingsWriter.Deserialize(json), strict: true); + } + + [Fact] + public void EachSaveGetsItsOwnPipeName() => + Assert.NotEqual(PrefsSettingsWriter.NewPipeName(), PrefsSettingsWriter.NewPipeName()); + + [Fact] + public void WithNoPolicyEveryPageKeyIsWritten() => + Assert.Equal( + ["ManifestUrl", "AuthorizationHeader", "SilentMode", "VerboseMode", "DryRun", "EnableDialog", "NoDialog", + "DialogTitle", "DialogMessage", "DialogIcon", "BlurScreen", "CustomInstallPath", "NetworkTimeout"], + PrefsSettingsWriter.WritableKeys(Sample(), Managed())); + + [Fact] + public void TheWriterSkipsPolicyManagedKeys() + { + var keys = PrefsSettingsWriter.WritableKeys(Sample(), Managed("ManifestUrl", "networktimeout")); + Assert.DoesNotContain("ManifestUrl", keys); + Assert.DoesNotContain("NetworkTimeout", keys); + Assert.Contains("DialogTitle", keys); + } + + [Fact] + public void ANoDialogPolicySkipsBothDialogSwitchKeys() + { + var keys = PrefsSettingsWriter.WritableKeys(Sample(), Managed("NoDialog")); + Assert.DoesNotContain("EnableDialog", keys); + Assert.DoesNotContain("NoDialog", keys); + } + + [Fact] + public void ABlankHeaderKeepsTheSavedOne() + { + var payload = Sample(); + payload.AuthorizationHeader = ""; + Assert.DoesNotContain("AuthorizationHeader", PrefsSettingsWriter.WritableKeys(payload, Managed())); + } + + [Fact] + public void TheDialogSwitchIsStoredAsBothKeys() + { + var config = PrefsSettingsWriter.ToConfig(Sample()); + Assert.False(config.EnableDialog); + Assert.True(config.NoDialog); + } + + [Theory] + [InlineData(10, true)] + [InlineData(600, true)] + [InlineData(9, false)] + [InlineData(601, false)] + public void TimeoutFollowsTheGuiRange(int timeout, bool valid) + { + var payload = Sample(); + payload.NetworkTimeout = timeout; + Assert.Equal(valid, PrefsSettingsWriter.Validate(payload) is null); + } + + [Fact] + public void TheApplySwitchCarriesItsPath() + { + string[] args = ["--apply-settings", "BootstrapMate-settings-abc"]; + Assert.True(PrefsSettingsWriter.IsApplyRequest(args)); + Assert.Equal("BootstrapMate-settings-abc", PrefsSettingsWriter.ApplyPipeName(args)); + } + + [Fact] + public void TheApplySwitchWithoutAPipeHasNoPipe() + { + string[] args = ["--apply-settings"]; + Assert.True(PrefsSettingsWriter.IsApplyRequest(args)); + Assert.Null(PrefsSettingsWriter.ApplyPipeName(args)); + } + + [Fact] + public void ANormalLaunchIsNotAnApplyRequest() => + Assert.False(PrefsSettingsWriter.IsApplyRequest(["--prefs"])); + + [Fact] + public void NoPipeIsAUsageError() => + Assert.Equal(PrefsSettingsWriter.ExitUsage, + PrefsSettingsWriter.Apply(PrefsSettingsWriter.NewPipeName(), TimeSpan.FromMilliseconds(200))); + + [Fact] + public async Task AnInvalidPayloadIsRejectedBeforeWriting() + { + var payload = Sample(); + payload.NetworkTimeout = 5; + var name = PrefsSettingsWriter.NewPipeName(); + using var pipe = PrefsSettingsWriter.CreatePipe(name); + var send = PrefsSettingsWriter.SendAsync(pipe, payload, CancellationToken.None); + + var code = await Task.Run(() => PrefsSettingsWriter.Apply(name, TimeSpan.FromSeconds(10))); + await send; + + Assert.Equal(PrefsSettingsWriter.ExitInvalid, code); + } +}