From 10eb96443e3cdde9420c7572842df3f472eda8da Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 5 Nov 2026 11:47:23 +0100 Subject: [PATCH 01/22] Add 'devproxy system-proxy reset' and restore previous system proxy settings Dev Proxy now records the OS proxy settings it is about to replace (Windows ProxyEnable/ProxyServer, macOS networksetup web/secure web proxies) together with the owning PID, and restores them when it stops instead of just turning the system proxy off. Because the snapshot outlives the process, a killed or crashed instance (foreground or detached) can be recovered: - 'devproxy system-proxy reset' restores the settings on demand - Dev Proxy restores a stale registration automatically on startup Closes dotnet/dev-proxy#2060 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Proxy/ISystemProxyManager.cs | 6 +- DevProxy.Tests/SystemProxyManagerTests.cs | 119 +++++++ DevProxy/Commands/DevProxyCommand.cs | 1 + DevProxy/Commands/StopCommand.cs | 10 +- DevProxy/Commands/SystemProxyCommand.cs | 78 +++++ DevProxy/Program.cs | 37 +- DevProxy/Proxy/SystemProxyManager.cs | 315 ++++++++++++++++-- DevProxy/Proxy/SystemProxySnapshot.cs | 204 ++++++++++++ DevProxy/State/StateManager.cs | 2 +- 9 files changed, 720 insertions(+), 52 deletions(-) create mode 100644 DevProxy/Commands/SystemProxyCommand.cs create mode 100644 DevProxy/Proxy/SystemProxySnapshot.cs diff --git a/DevProxy.Abstractions/Proxy/ISystemProxyManager.cs b/DevProxy.Abstractions/Proxy/ISystemProxyManager.cs index d29269a3..f31fde62 100644 --- a/DevProxy.Abstractions/Proxy/ISystemProxyManager.cs +++ b/DevProxy.Abstractions/Proxy/ISystemProxyManager.cs @@ -25,8 +25,10 @@ public interface ISystemProxyManager void Enable(string? ipAddress, int port); /// - /// Removes Dev Proxy as the system proxy, restoring direct connections. Safe to call - /// even if the proxy was never enabled (idempotent best-effort cleanup). + /// Removes Dev Proxy as the system proxy, restoring the settings that were in place + /// before when they were recorded, or direct + /// connections otherwise. Safe to call even if the proxy was never enabled + /// (idempotent best-effort cleanup). /// void Disable(); } diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 659998d1..9ea84fd3 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -24,3 +24,122 @@ public void CreateToggleScriptStartInfo_PreservesPathAndArgumentsContainingSpace startInfo.ArgumentList); } } + +public class MacOSNetworkSetupTests +{ + [Fact] + public void ParseNetworkServices_SkipsHeaderBlankAndDisabledServices() + { + var output = "An asterisk (*) denotes that a network service is disabled.\nWi-Fi\n*Thunderbolt Bridge\nUSB 10/100/1000 LAN\n\n"; + + var services = MacOSNetworkSetup.ParseNetworkServices(output); + + Assert.Equal(["Wi-Fi", "USB 10/100/1000 LAN"], services); + } + + [Fact] + public void ParseProxyEndpoint_ReadsEnabledServerAndPort() + { + var output = "Enabled: Yes\nServer: proxy.contoso.com\nPort: 3128\nAuthenticated Proxy Enabled: 0\n"; + + var endpoint = MacOSNetworkSetup.ParseProxyEndpoint(output); + + Assert.True(endpoint.Enabled); + Assert.Equal("proxy.contoso.com", endpoint.Server); + Assert.Equal(3128, endpoint.Port); + } + + [Fact] + public void ParseProxyEndpoint_EmptyServer() + { + var endpoint = MacOSNetworkSetup.ParseProxyEndpoint("Enabled: No\nServer: \nPort: 0\n"); + + Assert.False(endpoint.Enabled); + Assert.Equal(string.Empty, endpoint.Server); + Assert.Equal(0, endpoint.Port); + } + + [Fact] + public void GetRestoreCommands_RestoresServerAndTurnsDisabledEndpointsOff() + { + var settings = new MacOSServiceProxySettings + { + Service = "Wi-Fi", + Web = new() { Enabled = true, Server = "proxy.contoso.com", Port = 3128 }, + SecureWeb = new() { Enabled = false, Server = "secure.contoso.com", Port = 3129 }, + }; + + var commands = MacOSNetworkSetup.GetRestoreCommands(settings); + + Assert.Equal(3, commands.Count); + Assert.Equal(["-setwebproxy", "Wi-Fi", "proxy.contoso.com", "3128"], commands[0]); + Assert.Equal(["-setsecurewebproxy", "Wi-Fi", "secure.contoso.com", "3129"], commands[1]); + Assert.Equal(["-setsecurewebproxystate", "Wi-Fi", "off"], commands[2]); + } + + [Fact] + public void GetRestoreCommands_NoPreviousServer_ReturnsNoCommands() + { + var settings = new MacOSServiceProxySettings + { + Service = "Wi-Fi", + Web = new() { Enabled = false, Server = string.Empty, Port = 0 }, + SecureWeb = null, + }; + + Assert.Empty(MacOSNetworkSetup.GetRestoreCommands(settings)); + } +} + +public class SystemProxySnapshotStoreTests +{ + [Fact] + public void SaveLoadDelete_RoundTripsSnapshot() + { + var folder = Directory.CreateTempSubdirectory("devproxy-snapshot-"); + try + { + var path = Path.Combine(folder.FullName, "system-proxy-backup.json"); + var snapshot = new SystemProxySnapshot + { + Pid = 1234, + CreatedAt = DateTimeOffset.UnixEpoch, + Windows = new() { ProxyEnable = 1, ProxyServer = "corp:8080" }, + MacOS = [new() { Service = "Wi-Fi", Web = new() { Enabled = true, Server = "corp", Port = 8080 } }], + }; + + SystemProxySnapshotStore.Save(path, snapshot); + var loaded = SystemProxySnapshotStore.Load(path); + + Assert.NotNull(loaded); + Assert.Equal(1234, loaded.Pid); + Assert.Equal(1, loaded.Windows?.ProxyEnable); + Assert.Equal("corp:8080", loaded.Windows?.ProxyServer); + var service = Assert.Single(loaded.MacOS!); + Assert.Equal("Wi-Fi", service.Service); + Assert.Equal(8080, service.Web?.Port); + + SystemProxySnapshotStore.Delete(path); + Assert.Null(SystemProxySnapshotStore.Load(path)); + } + finally + { + folder.Delete(recursive: true); + } + } + + [Fact] + public void Load_CorruptFile_ReturnsNull() + { + var path = Path.GetTempFileName(); + try + { + File.WriteAllText(path, "{ not json"); + Assert.Null(SystemProxySnapshotStore.Load(path)); + } + finally + { + File.Delete(path); + } + } +} diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 6577c0bc..b109a576 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -636,6 +636,7 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions) ActivatorUtilities.CreateInstance(_serviceProvider), ActivatorUtilities.CreateInstance(_serviceProvider), ActivatorUtilities.CreateInstance(_serviceProvider), + ActivatorUtilities.CreateInstance(_serviceProvider), ActivatorUtilities.CreateInstance(_serviceProvider) }; var pluginCommands = _plugins.SelectMany(p => p.GetCommands()); diff --git a/DevProxy/Commands/StopCommand.cs b/DevProxy/Commands/StopCommand.cs index f2ae0303..0d8c3636 100644 --- a/DevProxy/Commands/StopCommand.cs +++ b/DevProxy/Commands/StopCommand.cs @@ -45,7 +45,7 @@ private async Task RunAsync(ParseResult parseResult, CancellationToken canc var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(cancellationToken); var states = await StateManager.LoadAllStatesAsync(cancellationToken); - if (states.Count == 0 && reconciliation.Orphans.Count == 0) + if (states.Count == 0 && reconciliation.OrphanedPids.Count == 0) { Console.WriteLine("Dev Proxy is not running."); return 1; @@ -102,11 +102,11 @@ private static async Task StopByPidAsync(int pid, bool force, CancellationT private static void ReportReconciledOrphans(SystemProxyManager.OrphanReconciliation reconciliation) { - foreach (var orphan in reconciliation.Orphans) + foreach (var pid in reconciliation.OrphanedPids) { - Console.WriteLine(reconciliation.SystemProxyDisabled - ? $"Restored system proxy left by crashed Dev Proxy (PID: {orphan.Pid})." - : $"Removed stale record for crashed Dev Proxy (PID: {orphan.Pid}); system proxy is owned by a running instance."); + Console.WriteLine(reconciliation.SystemProxyRestored + ? $"Restored system proxy left by crashed Dev Proxy (PID: {pid})." + : $"Removed stale record for crashed Dev Proxy (PID: {pid}); system proxy is owned by a running instance."); } } diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs new file mode 100644 index 00000000..d0af867e --- /dev/null +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -0,0 +1,78 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using DevProxy.Proxy; +using DevProxy.State; +using System.CommandLine; + +namespace DevProxy.Commands; + +sealed class SystemProxyCommand : Command +{ + private readonly ILogger _systemProxyLogger; + private readonly Option _forceOption = new("--force", "-f") + { + Description = "Reset the system proxy even if a running Dev Proxy instance owns it" + }; + + public SystemProxyCommand(ILogger systemProxyLogger) : + base("system-proxy", "Manage the system proxy settings changed by Dev Proxy") + { + _systemProxyLogger = systemProxyLogger; + + var resetCommand = new Command("reset", "Restore the system proxy settings that Dev Proxy changed. Use after Dev Proxy was killed or crashed."); + resetCommand.Add(_forceOption); + resetCommand.SetAction(ResetAsync); + Add(resetCommand); + + HelpExamples.Add(this, [ + "devproxy system-proxy reset Restore system proxy settings", + ]); + HelpExamples.Add(resetCommand, [ + "devproxy system-proxy reset Restore system proxy settings", + "devproxy system-proxy reset --force Restore even if Dev Proxy is running", + ]); + } + + private async Task ResetAsync(ParseResult parseResult, CancellationToken cancellationToken) + { + var force = parseResult.GetValue(_forceOption); + + var liveOwner = await SystemProxyManager.FindLiveSystemProxyOwnerAsync(cancellationToken); + if (liveOwner is not null && !force) + { + await Console.Error.WriteLineAsync($"Dev Proxy (PID: {liveOwner}) is running as the system proxy."); + await Console.Error.WriteLineAsync("Use 'devproxy stop' to stop it, or 'devproxy system-proxy reset --force' to reset anyway."); + return 1; + } + + var result = new SystemProxyManager(_systemProxyLogger).Restore(); + if (result is SystemProxyRestoreResult.Failed) + { + await Console.Error.WriteLineAsync("Couldn't restore the system proxy settings. To reset them manually, see https://go.devproxy.net?go=proxy-reset."); + return 1; + } + + // The settings are restored, so records of dead instances that registered as the + // system proxy are stale. Remove them so they don't trigger another restore later. + foreach (var orphan in await StateManager.GetOrphanedSystemProxyStatesAsync(cancellationToken)) + { + await StateManager.DeleteStateAsync(orphan.Pid, cancellationToken); + } + + switch (result) + { + case SystemProxyRestoreResult.RestoredPrevious: + Console.WriteLine("Restored the system proxy settings from before Dev Proxy started."); + return 0; + case SystemProxyRestoreResult.Disabled: + Console.WriteLine("Turned off the system proxy."); + return 0; + case SystemProxyRestoreResult.NotSupported: + default: + Console.WriteLine("Dev Proxy doesn't change the system proxy settings on this operating system. Nothing to reset."); + return 0; + } + } +} diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index ec32588f..c968672b 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -51,20 +51,14 @@ Console.SetError(_detachedLogWriter); } -static async Task StartDetachedProcessAsync(string[] args) +static async Task ReconcileOrphanedSystemProxiesAsync(bool isJsonOutput) { - var isJsonOutput = IsJsonOutputRequested(args); - - // Recover from a system-proxy registration left behind by a previous - // instance that crashed before restoring the OS proxy. This must run before - // any state-loading call below, which prunes (deletes) the stale state files - // it depends on without restoring the proxy. var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(); - foreach (var orphan in reconciliation.Orphans) + foreach (var pid in reconciliation.OrphanedPids) { - var message = reconciliation.SystemProxyDisabled - ? $"Recovered system proxy left by a crashed Dev Proxy instance (PID: {orphan.Pid})." - : $"Removed stale system-proxy registration left by a crashed Dev Proxy instance (PID: {orphan.Pid}) while keeping the current system proxy owner unchanged."; + var message = reconciliation.SystemProxyRestored + ? $"Recovered system proxy left by a crashed Dev Proxy instance (PID: {pid})." + : $"Removed stale system-proxy registration left by a crashed Dev Proxy instance (PID: {pid}) while keeping the current system proxy owner unchanged."; if (isJsonOutput) { await Console.Out.WriteLineAsync(FormatJsonLogEntry("info", message)); @@ -74,6 +68,17 @@ static async Task StartDetachedProcessAsync(string[] args) await Console.Out.WriteLineAsync(message); } } +} + +static async Task StartDetachedProcessAsync(string[] args) +{ + var isJsonOutput = IsJsonOutputRequested(args); + + // Recover from a system-proxy registration left behind by a previous + // instance that crashed before restoring the OS proxy. This must run before + // any state-loading call below, which prunes (deletes) the stale state files + // it depends on without restoring the proxy. + await ReconcileOrphanedSystemProxiesAsync(isJsonOutput); // Check if an instance is already running as system proxy var systemProxyInstance = await StateManager.FindSystemProxyInstanceAsync(); @@ -431,6 +436,16 @@ static async Task RunProxyAsync(string[] args, DevProxyConfigOptions option return; } +// Recover from a system-proxy registration left behind by a previous instance +// that was killed or crashed. Detached daemons skip this because the parent +// process that spawned them already did it. +if (DevProxyCommand.IsRootCommand && + !DevProxyCommand.IsInternalDaemon && + !args.Any(a => a is "-h" or "-?" or "--help" or "--version")) +{ + await ReconcileOrphanedSystemProxiesAsync(IsJsonOutputRequested(args)); +} + var options = new DevProxyConfigOptions(); options.ParseOptions(args); diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 3571ac42..a7d82e96 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -6,6 +6,7 @@ using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; +using System.Text; using DevProxy.Abstractions.Proxy; using DevProxy.State; using Microsoft.Extensions.Logging.Abstractions; @@ -13,66 +14,175 @@ namespace DevProxy.Proxy; +/// +/// The outcome of restoring the OS proxy settings. +/// +internal enum SystemProxyRestoreResult +{ + /// The settings captured before Dev Proxy registered itself were put back. + RestoredPrevious, + /// No previous settings were recorded, so the system proxy was turned off. + Disabled, + /// Dev Proxy doesn't configure the system proxy on this OS. + NotSupported, + /// The OS settings couldn't be changed. Details are logged. + Failed, +} + /// /// Host-side . Engine-agnostic OS proxy on/off, shared by -/// the Kestrel engine and the stop --force crash-cleanup path. +/// the Kestrel engine, the stop --force crash-cleanup path, and +/// devproxy system-proxy reset. /// /// /// Enable(ip, port) Disable() /// ──────────────── ───────── -/// Windows → registry ProxyServer Windows → registry ProxyEnable = 0 -/// + ProxyEnable = 1 + WinINET refresh +/// snapshot current settings restore snapshot when present +/// Windows → registry ProxyServer Windows → registry ProxyServer/ProxyEnable +/// + ProxyEnable = 1 (or ProxyEnable = 0) + WinINET refresh /// + WinINET refresh -/// macOS → toggle-proxy.sh on … macOS → toggle-proxy.sh off +/// macOS → toggle-proxy.sh on … macOS → toggle-proxy.sh off + networksetup /// Linux → log warning Linux → no-op /// /// /// +/// Before registering, the current OS proxy settings are written to a snapshot file +/// () together with the owning PID. Restoring reads +/// that file, so the previous settings can be put back even after the owning instance was +/// killed or crashed. +/// +/// +/// /// The Windows path uses WinINET: it writes the per-user Internet Settings registry values /// and then broadcasts INTERNET_OPTION_SETTINGS_CHANGED + INTERNET_OPTION_REFRESH so running /// applications re-read the proxy without a restart. This is the standard WinINET mechanism; /// it cannot be exercised on non-Windows hosts. /// /// -internal sealed class SystemProxyManager(ILogger logger) : ISystemProxyManager +internal sealed class SystemProxyManager : ISystemProxyManager { private const string InternetSettingsKey = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings"; private const int InternetOptionSettingsChanged = 39; private const int InternetOptionRefresh = 37; + private readonly ILogger _logger; + private readonly string _snapshotPath; + + public SystemProxyManager(ILogger logger) : + this(logger, SystemProxySnapshotStore.DefaultPath) + { + } + + internal SystemProxyManager(ILogger logger, string snapshotPath) + { + _logger = logger; + _snapshotPath = snapshotPath; + } + public void Enable(string? ipAddress, int port) { if (OperatingSystem.IsWindows()) { + SaveSnapshot(CaptureWindows); EnableWindows(SystemProxyAddress.ToHostPort(ipAddress, port)); } else if (OperatingSystem.IsMacOS()) { - RunToggleScript( + SaveSnapshot(CaptureMacOS); + _ = RunToggleScript( "on", SystemProxyAddress.ResolveHost(ipAddress), port.ToString(CultureInfo.InvariantCulture)); } else { - logger.LogWarning( + _logger.LogWarning( "Configure your operating system to use this proxy's port and address {Address}:{Port}", SystemProxyAddress.ResolveHost(ipAddress), port); } } - public void Disable() + public void Disable() => _ = Restore(); + + /// + /// Puts back the OS proxy settings recorded before Dev Proxy registered itself, or turns + /// the system proxy off when nothing was recorded. Safe to call when Dev Proxy never + /// changed the settings. + /// + internal SystemProxyRestoreResult Restore() { + if (!OperatingSystem.IsWindows() && !OperatingSystem.IsMacOS()) + { + return SystemProxyRestoreResult.NotSupported; + } + + var snapshot = SystemProxySnapshotStore.Load(_snapshotPath); + bool succeeded; + bool restoredPrevious; if (OperatingSystem.IsWindows()) { - DisableWindows(); + restoredPrevious = snapshot?.Windows is not null; + succeeded = restoredPrevious + ? RestoreWindows(snapshot!.Windows!) + : DisableWindows(); } - else if (OperatingSystem.IsMacOS()) + else + { + succeeded = RunToggleScript("off"); + restoredPrevious = snapshot?.MacOS is not null; + if (succeeded && restoredPrevious) + { + succeeded = RestoreMacOS(snapshot!.MacOS!); + } + } + + if (!succeeded) + { + // Keep the snapshot so a later reset can still put the previous settings back. + return SystemProxyRestoreResult.Failed; + } + + if (snapshot is not null) { - RunToggleScript("off"); + SystemProxySnapshotStore.Delete(_snapshotPath); } + return restoredPrevious + ? SystemProxyRestoreResult.RestoredPrevious + : SystemProxyRestoreResult.Disabled; + } + + private void SaveSnapshot(Action capture) + { + try + { + // Keep an existing snapshot: it holds the settings from before Dev Proxy first + // took over, while the current settings may already point at Dev Proxy. + var snapshot = SystemProxySnapshotStore.Load(_snapshotPath); + if (snapshot is null) + { + snapshot = new() { CreatedAt = DateTimeOffset.UtcNow }; + capture(snapshot); + } + snapshot.Pid = Environment.ProcessId; + SystemProxySnapshotStore.Save(_snapshotPath, snapshot); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException or InvalidOperationException or System.ComponentModel.Win32Exception) + { + _logger.LogWarning(ex, "Couldn't save the current system proxy settings. They can't be restored when Dev Proxy stops."); + } + } + + [SupportedOSPlatform("windows")] + private static void CaptureWindows(SystemProxySnapshot snapshot) + { + using var key = Registry.CurrentUser.OpenSubKey(InternetSettingsKey, writable: false); + snapshot.Windows = new() + { + ProxyEnable = key?.GetValue("ProxyEnable") is int enable ? enable : null, + ProxyServer = key?.GetValue("ProxyServer") as string, + }; } [SupportedOSPlatform("windows")] @@ -83,7 +193,7 @@ private void EnableWindows(string hostPort) using var key = Registry.CurrentUser.OpenSubKey(InternetSettingsKey, writable: true); if (key is null) { - logger.LogError("Could not open the Windows Internet Settings registry key."); + _logger.LogError("Could not open the Windows Internet Settings registry key."); return; } @@ -93,27 +203,68 @@ private void EnableWindows(string hostPort) } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException) { - logger.LogError(ex, "Failed to set the system proxy via the Windows registry."); + _logger.LogError(ex, "Failed to set the system proxy via the Windows registry."); } } [SupportedOSPlatform("windows")] - private void DisableWindows() + private bool DisableWindows() { try { using var key = Registry.CurrentUser.OpenSubKey(InternetSettingsKey, writable: true); if (key is null) { - return; + return false; } key.SetValue("ProxyEnable", 0, RegistryValueKind.DWord); NotifyWinInetSettingsChanged(); + return true; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException) { - logger.LogError(ex, "Failed to clear the system proxy via the Windows registry."); + _logger.LogError(ex, "Failed to clear the system proxy via the Windows registry."); + return false; + } + } + + [SupportedOSPlatform("windows")] + private bool RestoreWindows(WindowsProxySettings settings) + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(InternetSettingsKey, writable: true); + if (key is null) + { + return false; + } + + if (settings.ProxyServer is null) + { + key.DeleteValue("ProxyServer", throwOnMissingValue: false); + } + else + { + key.SetValue("ProxyServer", settings.ProxyServer, RegistryValueKind.String); + } + + if (settings.ProxyEnable is null) + { + key.DeleteValue("ProxyEnable", throwOnMissingValue: false); + } + else + { + key.SetValue("ProxyEnable", settings.ProxyEnable.Value, RegistryValueKind.DWord); + } + + NotifyWinInetSettingsChanged(); + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException) + { + _logger.LogError(ex, "Failed to restore the system proxy via the Windows registry."); + return false; } } @@ -134,13 +285,79 @@ private static void NotifyWinInetSettingsChanged() private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength); #pragma warning restore SYSLIB1054 - private void RunToggleScript(params string[] arguments) + private static void CaptureMacOS(SystemProxySnapshot snapshot) + { + var services = MacOSNetworkSetup.ParseNetworkServices( + RunNetworkSetup("-listallnetworkservices") ?? string.Empty); + snapshot.MacOS = [.. services.Select(service => new MacOSServiceProxySettings + { + Service = service, + Web = MacOSNetworkSetup.ParseProxyEndpoint(RunNetworkSetup("-getwebproxy", service) ?? string.Empty), + SecureWeb = MacOSNetworkSetup.ParseProxyEndpoint(RunNetworkSetup("-getsecurewebproxy", service) ?? string.Empty), + })]; + } + + private bool RestoreMacOS(IEnumerable services) + { + try + { + foreach (var command in services.SelectMany(MacOSNetworkSetup.GetRestoreCommands)) + { + _ = RunNetworkSetup(command); + } + return true; + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException) + { + _logger.LogError(ex, "Failed to restore the system proxy via networksetup."); + return false; + } + } + + private static string? RunNetworkSetup(params string[] arguments) + { + var startInfo = new ProcessStartInfo + { + FileName = MacOSNetworkSetup.Executable, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + foreach (var argument in arguments) + { + startInfo.ArgumentList.Add(argument); + } + + using var process = new Process { StartInfo = startInfo }; + var output = new StringBuilder(); + process.OutputDataReceived += (_, e) => + { + if (e.Data is not null) + { + _ = output.AppendLine(e.Data); + } + }; + _ = process.Start(); + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + if (!process.WaitForExit(TimeSpan.FromSeconds(10))) + { + process.Kill(); + return null; + } + // Flush the asynchronous output readers. + process.WaitForExit(); + return output.ToString(); + } + + private bool RunToggleScript(params string[] arguments) { var bashScriptPath = Path.Join(AppContext.BaseDirectory, "toggle-proxy.sh"); if (!File.Exists(bashScriptPath)) { - logger.LogWarning("Could not find {Script} to toggle the system proxy.", "toggle-proxy.sh"); - return; + _logger.LogWarning("Could not find {Script} to toggle the system proxy.", "toggle-proxy.sh"); + return false; } var startInfo = CreateToggleScriptStartInfo(bashScriptPath, arguments); @@ -152,11 +369,14 @@ private void RunToggleScript(params string[] arguments) if (!process.WaitForExit(TimeSpan.FromSeconds(10))) { process.Kill(); + return false; } + return true; } catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException) { - logger.LogError(ex, "Failed to toggle the system proxy via toggle-proxy.sh."); + _logger.LogError(ex, "Failed to toggle the system proxy via toggle-proxy.sh."); + return false; } } @@ -184,36 +404,65 @@ internal static ProcessStartInfo CreateToggleScriptStartInfo(string bashScriptPa /// /// The outcome of reconciling orphaned system-proxy registrations. /// + /// PIDs of dead instances that left a system-proxy registration behind. + /// Whether the OS proxy settings were restored. internal readonly record struct OrphanReconciliation( - IReadOnlyList Orphans, - bool SystemProxyDisabled); + IReadOnlyList OrphanedPids, + bool SystemProxyRestored); /// - /// Reconciles system-proxy registrations left behind by crashed instances. + /// Finds the PID of a live process that owns the system proxy: a running detached + /// instance, or the (foreground or detached) instance recorded in the snapshot file. + /// Returns null when no live process owns it. + /// + internal static async Task FindLiveSystemProxyOwnerAsync(CancellationToken cancellationToken = default) + { + var liveInstance = await StateManager.FindSystemProxyInstanceAsync(cancellationToken); + if (liveInstance is not null) + { + return liveInstance.Pid; + } + + var snapshot = SystemProxySnapshotStore.Load(SystemProxySnapshotStore.DefaultPath); + return snapshot is not null && StateManager.IsProcessRunning(snapshot.Pid) + ? snapshot.Pid + : null; + } + + /// + /// Reconciles system-proxy registrations left behind by crashed or killed instances. /// Restores the OS proxy (unless a live instance still owns it) and removes /// the stale state records. Safe to call when there are no orphans. /// public static async Task ReconcileOrphanedSystemProxiesAsync(CancellationToken cancellationToken = default) { - var orphans = await StateManager.GetOrphanedSystemProxyStatesAsync(cancellationToken); - if (orphans.Count == 0) + var orphanedPids = (await StateManager.GetOrphanedSystemProxyStatesAsync(cancellationToken)) + .Select(o => o.Pid) + .ToList(); + + var snapshot = SystemProxySnapshotStore.Load(SystemProxySnapshotStore.DefaultPath); + if (snapshot is not null && !StateManager.IsProcessRunning(snapshot.Pid) && !orphanedPids.Contains(snapshot.Pid)) + { + orphanedPids.Add(snapshot.Pid); + } + + if (orphanedPids.Count == 0) { return new([], false); } - var liveOwner = await StateManager.FindSystemProxyInstanceAsync(cancellationToken); - var disabled = false; - if (liveOwner is null) + var restored = false; + if (await FindLiveSystemProxyOwnerAsync(cancellationToken) is null) { - new SystemProxyManager(NullLogger.Instance).Disable(); - disabled = true; + restored = new SystemProxyManager(NullLogger.Instance).Restore() + is SystemProxyRestoreResult.RestoredPrevious or SystemProxyRestoreResult.Disabled; } - foreach (var orphan in orphans) + foreach (var pid in orphanedPids) { - await StateManager.DeleteStateAsync(orphan.Pid, cancellationToken); + await StateManager.DeleteStateAsync(pid, cancellationToken); } - return new(orphans, disabled); + return new(orphanedPids, restored); } } diff --git a/DevProxy/Proxy/SystemProxySnapshot.cs b/DevProxy/Proxy/SystemProxySnapshot.cs new file mode 100644 index 00000000..acb3b0cc --- /dev/null +++ b/DevProxy/Proxy/SystemProxySnapshot.cs @@ -0,0 +1,204 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +using DevProxy.State; + +namespace DevProxy.Proxy; + +/// +/// The OS proxy settings that were in place before Dev Proxy registered itself as the +/// system proxy, plus the PID of the instance that did it. Persisted to disk so the +/// settings can be restored even if that instance is killed or crashes. +/// +internal sealed class SystemProxySnapshot +{ + [JsonPropertyName("pid")] + public int Pid { get; set; } + + [JsonPropertyName("createdAt")] + public DateTimeOffset CreatedAt { get; set; } + + [JsonPropertyName("windows")] + public WindowsProxySettings? Windows { get; set; } + + [JsonPropertyName("macOS")] + public List? MacOS { get; set; } +} + +internal sealed class WindowsProxySettings +{ + /// The previous ProxyEnable registry value; null when the value didn't exist. + [JsonPropertyName("proxyEnable")] + public int? ProxyEnable { get; set; } + + /// The previous ProxyServer registry value; null when the value didn't exist. + [JsonPropertyName("proxyServer")] + public string? ProxyServer { get; set; } +} + +internal sealed class MacOSServiceProxySettings +{ + [JsonPropertyName("service")] + public string Service { get; set; } = string.Empty; + + [JsonPropertyName("web")] + public MacOSProxyEndpoint? Web { get; set; } + + [JsonPropertyName("secureWeb")] + public MacOSProxyEndpoint? SecureWeb { get; set; } +} + +internal sealed class MacOSProxyEndpoint +{ + [JsonPropertyName("enabled")] + public bool Enabled { get; set; } + + [JsonPropertyName("server")] + public string Server { get; set; } = string.Empty; + + [JsonPropertyName("port")] + public int Port { get; set; } +} + +/// +/// Reads and writes the file. +/// +internal static class SystemProxySnapshotStore +{ + private const string FileName = "system-proxy-backup.json"; + + private static readonly JsonSerializerOptions _jsonOptions = new() { WriteIndented = true }; + + public static string DefaultPath => Path.Combine(StateManager.GetConfigFolder(), FileName); + + public static SystemProxySnapshot? Load(string path) + { + try + { + if (!File.Exists(path)) + { + return null; + } + + return JsonSerializer.Deserialize(File.ReadAllText(path)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + return null; + } + } + + public static void Save(string path, SystemProxySnapshot snapshot) + { + var json = JsonSerializer.Serialize(snapshot, _jsonOptions); + // Called from the synchronous ISystemProxyManager.Enable; the host has no + // synchronization context, so blocking here can't deadlock. +#pragma warning disable VSTHRD002 + PrivateFiles.WriteAllTextAsync(path, json).GetAwaiter().GetResult(); +#pragma warning restore VSTHRD002 + } + + public static void Delete(string path) + { + try + { + File.Delete(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } +} + +/// +/// Pure helpers for reading and restoring macOS proxy settings with networksetup. +/// +internal static class MacOSNetworkSetup +{ + public const string Executable = "/usr/sbin/networksetup"; + + /// + /// Parses networksetup -listallnetworkservices. The first line is an informational + /// header and services prefixed with * are disabled, so both are skipped. + /// + public static List ParseNetworkServices(string output) + { + return [.. output + .Split('\n') + .Skip(1) + .Select(l => l.TrimEnd('\r')) + .Where(l => !string.IsNullOrWhiteSpace(l) && !l.StartsWith('*'))]; + } + + /// + /// Parses networksetup -getwebproxy / -getsecurewebproxy output. + /// + public static MacOSProxyEndpoint ParseProxyEndpoint(string output) + { + var endpoint = new MacOSProxyEndpoint(); + foreach (var rawLine in output.Split('\n')) + { + var line = rawLine.TrimEnd('\r'); + var separator = line.IndexOf(':', StringComparison.Ordinal); + if (separator < 0) + { + continue; + } + + var key = line[..separator].Trim(); + var value = line[(separator + 1)..].Trim(); + switch (key) + { + case "Enabled": + endpoint.Enabled = value.Equals("Yes", StringComparison.OrdinalIgnoreCase); + break; + case "Server": + endpoint.Server = value; + break; + case "Port": + endpoint.Port = int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var port) ? port : 0; + break; + default: + break; + } + } + return endpoint; + } + + /// + /// Builds the networksetup argument lists that put back a service's previous + /// proxy server and state. Assumes the proxy has already been turned off for every + /// service, so endpoints without a previous server need no commands. + /// + public static List GetRestoreCommands(MacOSServiceProxySettings settings) + { + var commands = new List(); + AddEndpointCommands(commands, settings.Service, settings.Web, "-setwebproxy", "-setwebproxystate"); + AddEndpointCommands(commands, settings.Service, settings.SecureWeb, "-setsecurewebproxy", "-setsecurewebproxystate"); + return commands; + } + + private static void AddEndpointCommands( + List commands, + string service, + MacOSProxyEndpoint? endpoint, + string setProxyCommand, + string setStateCommand) + { + if (endpoint is null || string.IsNullOrEmpty(endpoint.Server) || endpoint.Port <= 0) + { + return; + } + + // Setting the server also turns the proxy on, so turn it back off if it was disabled. + commands.Add([setProxyCommand, service, endpoint.Server, endpoint.Port.ToString(CultureInfo.InvariantCulture)]); + if (!endpoint.Enabled) + { + commands.Add([setStateCommand, service, "off"]); + } + } +} diff --git a/DevProxy/State/StateManager.cs b/DevProxy/State/StateManager.cs index 5ca80d53..fa24e16d 100644 --- a/DevProxy/State/StateManager.cs +++ b/DevProxy/State/StateManager.cs @@ -288,7 +288,7 @@ public static async Task IsInstanceRunningAsync(CancellationToken cancella /// /// Checks if a process with the given PID is running. /// - private static bool IsProcessRunning(int pid) + internal static bool IsProcessRunning(int pid) { try { From e76ff0b2a0cbb33e26833b3d67dba4aae4b8e56a Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 5 Nov 2026 11:54:47 +0100 Subject: [PATCH 02/22] Address review feedback on system proxy reset - Run 'system-proxy reset' before loading config/plugins - Don't let an instance's shutdown undo a forced reset or another owner - Treat networksetup timeouts/nonzero exits and toggle-proxy.sh failures as restore failures so the snapshot is kept - Skip disabled macOS services in toggle-proxy.sh and propagate failures - Report the Linux no-op before checking proxy ownership Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy/Commands/DevProxyCommand.cs | 20 +++++++++ DevProxy/Commands/SystemProxyCommand.cs | 58 ++++++++++++++++++------- DevProxy/Program.cs | 9 ++++ DevProxy/Proxy/SystemProxyManager.cs | 39 ++++++++++++++--- DevProxy/toggle-proxy.sh | 20 ++++++--- 5 files changed, 118 insertions(+), 28 deletions(-) diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index b109a576..af668b8f 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -59,6 +59,7 @@ sealed class DevProxyCommand : RootCommand private static bool _isJwtCommandResolved; private static bool _isRootCommandResolved; private static bool _isConfigValidateCommandResolved; + private static bool _isSystemProxyResetCommandResolved; private static bool _isDetachedModeResolved; private static bool _isInternalDaemonResolved; private static bool _stdioLogFilePathResolved; @@ -132,6 +133,25 @@ public static bool IsConfigValidateCommand } } + public static bool IsSystemProxyResetCommand + { + get + { + if (_isSystemProxyResetCommandResolved) + { + return field; + } + + var args = Environment.GetCommandLineArgs(); + field = args.Length > 2 && + string.Equals(args[1], "system-proxy", StringComparison.OrdinalIgnoreCase) && + string.Equals(args[2], "reset", StringComparison.OrdinalIgnoreCase) && + !args.Any(arg => helpOptions.Contains(arg)); + _isSystemProxyResetCommandResolved = true; + return field; + } + } + public static bool IsDetachedMode { get diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index d0af867e..623ee6a7 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using DevProxy.Logging; using DevProxy.Proxy; using DevProxy.State; using System.CommandLine; @@ -35,9 +36,43 @@ public SystemProxyCommand(ILogger systemProxyLogger) : ]); } - private async Task ResetAsync(ParseResult parseResult, CancellationToken cancellationToken) + private Task ResetAsync(ParseResult parseResult, CancellationToken cancellationToken) => + ResetCoreAsync(parseResult.GetValue(_forceOption), _systemProxyLogger, cancellationToken); + + /// + /// Runs system-proxy reset without building the application host, so a broken + /// configuration or plugin can't prevent restoring network access. + /// + internal static async Task RunResetStandaloneAsync(string[] args) { - var force = parseResult.GetValue(_forceOption); + var force = args.Any(a => a is "--force" or "-f"); + + using var loggerFactory = LoggerFactory.Create(builder => + { + _ = builder + .SetMinimumLevel(LogLevel.Information) + .AddConsole(consoleOptions => + { + consoleOptions.FormatterName = ProxyConsoleFormatter.DefaultCategoryName; + consoleOptions.LogToStandardErrorThreshold = LogLevel.Warning; + }) + .AddConsoleFormatter(formatterOptions => + { + formatterOptions.IncludeScopes = false; + formatterOptions.ShowTimestamps = false; + }); + }); + + return await ResetCoreAsync(force, loggerFactory.CreateLogger(), CancellationToken.None); + } + + private static async Task ResetCoreAsync(bool force, ILogger logger, CancellationToken cancellationToken) + { + if (!OperatingSystem.IsWindows() && !OperatingSystem.IsMacOS()) + { + Console.WriteLine("Dev Proxy doesn't change the system proxy settings on this operating system. Nothing to reset."); + return 0; + } var liveOwner = await SystemProxyManager.FindLiveSystemProxyOwnerAsync(cancellationToken); if (liveOwner is not null && !force) @@ -47,7 +82,7 @@ private async Task ResetAsync(ParseResult parseResult, CancellationToken ca return 1; } - var result = new SystemProxyManager(_systemProxyLogger).Restore(); + var result = new SystemProxyManager(logger).Restore(); if (result is SystemProxyRestoreResult.Failed) { await Console.Error.WriteLineAsync("Couldn't restore the system proxy settings. To reset them manually, see https://go.devproxy.net?go=proxy-reset."); @@ -61,18 +96,9 @@ private async Task ResetAsync(ParseResult parseResult, CancellationToken ca await StateManager.DeleteStateAsync(orphan.Pid, cancellationToken); } - switch (result) - { - case SystemProxyRestoreResult.RestoredPrevious: - Console.WriteLine("Restored the system proxy settings from before Dev Proxy started."); - return 0; - case SystemProxyRestoreResult.Disabled: - Console.WriteLine("Turned off the system proxy."); - return 0; - case SystemProxyRestoreResult.NotSupported: - default: - Console.WriteLine("Dev Proxy doesn't change the system proxy settings on this operating system. Nothing to reset."); - return 0; - } + Console.WriteLine(result is SystemProxyRestoreResult.RestoredPrevious + ? "Restored the system proxy settings from before Dev Proxy started." + : "Turned off the system proxy."); + return 0; } } diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index c968672b..f19d0308 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -436,6 +436,15 @@ static async Task RunProxyAsync(string[] args, DevProxyConfigOptions option return; } +// Handle 'system-proxy reset' early so a broken configuration or plugin can't +// prevent restoring network access. +if (DevProxyCommand.IsSystemProxyResetCommand) +{ + var resetExitCode = await SystemProxyCommand.RunResetStandaloneAsync(args); + Environment.Exit(resetExitCode); + return; +} + // Recover from a system-proxy registration left behind by a previous instance // that was killed or crashed. Detached daemons skip this because the parent // process that spawned them already did it. diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index a7d82e96..038452b9 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -68,6 +68,7 @@ internal sealed class SystemProxyManager : ISystemProxyManager private readonly ILogger _logger; private readonly string _snapshotPath; + private bool _savedSnapshot; public SystemProxyManager(ILogger logger) : this(logger, SystemProxySnapshotStore.DefaultPath) @@ -104,7 +105,22 @@ public void Enable(string? ipAddress, int port) } } - public void Disable() => _ = Restore(); + public void Disable() + { + if (_savedSnapshot) + { + _savedSnapshot = false; + // The snapshot is gone or belongs to another process when 'system-proxy reset' + // already restored the settings or another instance took over. Restoring now + // would undo that, so leave the settings alone. + if (SystemProxySnapshotStore.Load(_snapshotPath)?.Pid != Environment.ProcessId) + { + return; + } + } + + _ = Restore(); + } /// /// Puts back the OS proxy settings recorded before Dev Proxy registered itself, or turns @@ -167,6 +183,7 @@ private void SaveSnapshot(Action capture) } snapshot.Pid = Environment.ProcessId; SystemProxySnapshotStore.Save(_snapshotPath, snapshot); + _savedSnapshot = true; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException or InvalidOperationException or System.ComponentModel.Win32Exception) { @@ -288,12 +305,12 @@ private static void NotifyWinInetSettingsChanged() private static void CaptureMacOS(SystemProxySnapshot snapshot) { var services = MacOSNetworkSetup.ParseNetworkServices( - RunNetworkSetup("-listallnetworkservices") ?? string.Empty); + RunNetworkSetup("-listallnetworkservices")); snapshot.MacOS = [.. services.Select(service => new MacOSServiceProxySettings { Service = service, - Web = MacOSNetworkSetup.ParseProxyEndpoint(RunNetworkSetup("-getwebproxy", service) ?? string.Empty), - SecureWeb = MacOSNetworkSetup.ParseProxyEndpoint(RunNetworkSetup("-getsecurewebproxy", service) ?? string.Empty), + Web = MacOSNetworkSetup.ParseProxyEndpoint(RunNetworkSetup("-getwebproxy", service)), + SecureWeb = MacOSNetworkSetup.ParseProxyEndpoint(RunNetworkSetup("-getsecurewebproxy", service)), })]; } @@ -314,7 +331,7 @@ private bool RestoreMacOS(IEnumerable services) } } - private static string? RunNetworkSetup(params string[] arguments) + private static string RunNetworkSetup(params string[] arguments) { var startInfo = new ProcessStartInfo { @@ -344,10 +361,14 @@ private bool RestoreMacOS(IEnumerable services) if (!process.WaitForExit(TimeSpan.FromSeconds(10))) { process.Kill(); - return null; + throw new InvalidOperationException($"networksetup {arguments[0]} timed out."); } // Flush the asynchronous output readers. process.WaitForExit(); + if (process.ExitCode != 0) + { + throw new InvalidOperationException($"networksetup {arguments[0]} exited with code {process.ExitCode}."); + } return output.ToString(); } @@ -369,6 +390,12 @@ private bool RunToggleScript(params string[] arguments) if (!process.WaitForExit(TimeSpan.FromSeconds(10))) { process.Kill(); + _logger.LogError("Timed out toggling the system proxy via toggle-proxy.sh."); + return false; + } + if (process.ExitCode != 0) + { + _logger.LogError("toggle-proxy.sh exited with code {ExitCode}.", process.ExitCode); return false; } return true; diff --git a/DevProxy/toggle-proxy.sh b/DevProxy/toggle-proxy.sh index 179ecdb2..50b3f284 100644 --- a/DevProxy/toggle-proxy.sh +++ b/DevProxy/toggle-proxy.sh @@ -4,18 +4,26 @@ toggle=$1 ip=$2 port=$3 -network_services=$(networksetup -listallnetworkservices | tail -n +2) +# Skip the header line and disabled services (prefixed with *), which networksetup can't configure. +network_services=$(networksetup -listallnetworkservices | tail -n +2 | grep -v '^\*') + +status=0 if [[ "$toggle" == "on" ]]; then while IFS= read -r service; do - networksetup -setsecurewebproxy "$service" $ip $port - networksetup -setwebproxy "$service" $ip $port + [[ -z "$service" ]] && continue + networksetup -setsecurewebproxy "$service" "$ip" "$port" || status=1 + networksetup -setwebproxy "$service" "$ip" "$port" || status=1 done <<<"$network_services" elif [[ "$toggle" == "off" ]]; then while IFS= read -r service; do - networksetup -setsecurewebproxystate "$service" off - networksetup -setwebproxystate "$service" off + [[ -z "$service" ]] && continue + networksetup -setsecurewebproxystate "$service" off || status=1 + networksetup -setwebproxystate "$service" off || status=1 done <<<"$network_services" else echo "Set the first argument to on or off." -fi \ No newline at end of file + status=1 +fi + +exit $status From 9f75e95fd57203be44db8ad5bce53e0ba2dabaae Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 5 Nov 2026 12:03:40 +0100 Subject: [PATCH 03/22] Harden system proxy recovery per review feedback - Clear system-proxy ownership on live instances after a forced reset - Report failed orphan restores distinctly and keep records for retry - Continue restoring remaining macOS services after a failure - Fail toggle-proxy.sh when listing network services fails - Parse standalone reset args with System.CommandLine Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy/Commands/StopCommand.cs | 25 +++++++++--- DevProxy/Commands/SystemProxyCommand.cs | 31 ++++++++++++++- DevProxy/Program.cs | 16 +++++++- DevProxy/Proxy/SystemProxyManager.cs | 52 +++++++++++++++++-------- DevProxy/toggle-proxy.sh | 6 ++- 5 files changed, 106 insertions(+), 24 deletions(-) diff --git a/DevProxy/Commands/StopCommand.cs b/DevProxy/Commands/StopCommand.cs index 0d8c3636..08bda9a3 100644 --- a/DevProxy/Commands/StopCommand.cs +++ b/DevProxy/Commands/StopCommand.cs @@ -42,7 +42,7 @@ private async Task RunAsync(ParseResult parseResult, CancellationToken canc // Reconcile any system-proxy registrations left behind by crashed // instances first — this must run before LoadAllStatesAsync, which prunes // (deletes) the stale state files it depends on. - var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(cancellationToken); + var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(cancellationToken: cancellationToken); var states = await StateManager.LoadAllStatesAsync(cancellationToken); if (states.Count == 0 && reconciliation.OrphanedPids.Count == 0) @@ -61,7 +61,10 @@ private async Task RunAsync(ParseResult parseResult, CancellationToken canc } } - ReportReconciledOrphans(reconciliation); + if (!ReportReconciledOrphans(reconciliation)) + { + exitCode = 1; + } return exitCode; } @@ -84,7 +87,12 @@ private static async Task StopByPidAsync(int pid, bool force, CancellationT var liveOwner = await StateManager.FindSystemProxyInstanceAsync(cancellationToken); if (liveOwner is null) { - new SystemProxyManager(NullLogger.Instance).Disable(); + if (new SystemProxyManager(NullLogger.Instance).Restore() is SystemProxyRestoreResult.Failed) + { + // Keep the state record so a later stop or start retries. + await Console.Error.WriteLineAsync($"Couldn't restore the system proxy left by crashed Dev Proxy (PID: {pid}). Run 'devproxy system-proxy reset' or see https://go.devproxy.net?go=proxy-reset."); + return 1; + } Console.WriteLine($"Restored system proxy left by crashed Dev Proxy (PID: {pid})."); } else @@ -100,14 +108,21 @@ private static async Task StopByPidAsync(int pid, bool force, CancellationT return 1; } - private static void ReportReconciledOrphans(SystemProxyManager.OrphanReconciliation reconciliation) + private static bool ReportReconciledOrphans(SystemProxyManager.OrphanReconciliation reconciliation) { + if (reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Failed) + { + Console.Error.WriteLine($"Couldn't restore the system proxy left by crashed Dev Proxy (PID: {string.Join(", ", reconciliation.OrphanedPids)}). Run 'devproxy system-proxy reset' or see https://go.devproxy.net?go=proxy-reset."); + return false; + } + foreach (var pid in reconciliation.OrphanedPids) { - Console.WriteLine(reconciliation.SystemProxyRestored + Console.WriteLine(reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Restored ? $"Restored system proxy left by crashed Dev Proxy (PID: {pid})." : $"Removed stale record for crashed Dev Proxy (PID: {pid}); system proxy is owned by a running instance."); } + return true; } private static async Task StopInstanceAsync(ProxyInstanceState state, bool force, CancellationToken cancellationToken) diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index 623ee6a7..ab5bd7c6 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -45,7 +45,27 @@ private Task ResetAsync(ParseResult parseResult, CancellationToken cancella /// internal static async Task RunResetStandaloneAsync(string[] args) { - var force = args.Any(a => a is "--force" or "-f"); + // Parse with a minimal command tree mirroring the registered command so values + // like '--force false' and invalid arguments are handled the same way. + var forceOption = new Option("--force", "-f"); + var resetCommand = new Command("reset") { forceOption }; + var rootCommand = new RootCommand { new Command("system-proxy") { resetCommand } }; + foreach (var name in new[] { DevProxyCommand.OutputOptionName, DevProxyCommand.LogLevelOptionName }) + { + rootCommand.Options.Add(new Option(name) { Recursive = true }); + } + rootCommand.Options.Add(new Option(DevProxyCommand.NoColorOptionName) { Recursive = true, Arity = ArgumentArity.Zero }); + + var parseResult = rootCommand.Parse(args); + if (parseResult.Errors.Count > 0) + { + foreach (var error in parseResult.Errors) + { + await Console.Error.WriteLineAsync(error.Message); + } + return 1; + } + var force = parseResult.GetValue(forceOption); using var loggerFactory = LoggerFactory.Create(builder => { @@ -89,6 +109,15 @@ private static async Task ResetCoreAsync(bool force, ILogger s.AsSystemProxy)) + { + state.AsSystemProxy = false; + await StateManager.SaveStateAsync(state, cancellationToken); + } + // The settings are restored, so records of dead instances that registered as the // system proxy are stale. Remove them so they don't trigger another restore later. foreach (var orphan in await StateManager.GetOrphanedSystemProxyStatesAsync(cancellationToken)) diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index f19d0308..1c18fe9b 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -54,9 +54,23 @@ static async Task ReconcileOrphanedSystemProxiesAsync(bool isJsonOutput) { var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(); + if (reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Failed) + { + var error = $"Couldn't restore the system proxy left by a crashed Dev Proxy instance (PID: {string.Join(", ", reconciliation.OrphanedPids)}). Run 'devproxy system-proxy reset' or see https://go.devproxy.net?go=proxy-reset."; + if (isJsonOutput) + { + await Console.Out.WriteLineAsync(FormatJsonLogEntry("error", error)); + } + else + { + await Console.Error.WriteLineAsync(error); + } + return; + } + foreach (var pid in reconciliation.OrphanedPids) { - var message = reconciliation.SystemProxyRestored + var message = reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Restored ? $"Recovered system proxy left by a crashed Dev Proxy instance (PID: {pid})." : $"Removed stale system-proxy registration left by a crashed Dev Proxy instance (PID: {pid}) while keeping the current system proxy owner unchanged."; if (isJsonOutput) diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 038452b9..7df9b263 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -316,19 +316,22 @@ private static void CaptureMacOS(SystemProxySnapshot snapshot) private bool RestoreMacOS(IEnumerable services) { - try + // Keep going after a failure so one broken service (for example, one that was + // removed while Dev Proxy was running) doesn't leave the others without a proxy. + var succeeded = true; + foreach (var command in services.SelectMany(MacOSNetworkSetup.GetRestoreCommands)) { - foreach (var command in services.SelectMany(MacOSNetworkSetup.GetRestoreCommands)) + try { _ = RunNetworkSetup(command); } - return true; - } - catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException) - { - _logger.LogError(ex, "Failed to restore the system proxy via networksetup."); - return false; + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException) + { + _logger.LogError(ex, "Failed to restore the system proxy via networksetup {Arguments}.", string.Join(' ', command)); + succeeded = false; + } } + return succeeded; } private static string RunNetworkSetup(params string[] arguments) @@ -428,14 +431,27 @@ internal static ProcessStartInfo CreateToggleScriptStartInfo(string bashScriptPa // Static helpers for orphan reconciliation (crash-cleanup path). // ------------------------------------------------------------------ + /// + /// What happened to the OS proxy settings while reconciling orphaned registrations. + /// + internal enum OrphanRestoreOutcome + { + /// The OS proxy settings were restored. + Restored, + /// A live instance owns the system proxy, so the settings were left alone. + OwnedByLiveInstance, + /// Restoring the settings failed. The recovery records were kept for a retry. + Failed + } + /// /// The outcome of reconciling orphaned system-proxy registrations. /// /// PIDs of dead instances that left a system-proxy registration behind. - /// Whether the OS proxy settings were restored. + /// What happened to the OS proxy settings. internal readonly record struct OrphanReconciliation( IReadOnlyList OrphanedPids, - bool SystemProxyRestored); + OrphanRestoreOutcome Outcome); /// /// Finds the PID of a live process that owns the system proxy: a running detached @@ -461,7 +477,7 @@ internal readonly record struct OrphanReconciliation( /// Restores the OS proxy (unless a live instance still owns it) and removes /// the stale state records. Safe to call when there are no orphans. /// - public static async Task ReconcileOrphanedSystemProxiesAsync(CancellationToken cancellationToken = default) + public static async Task ReconcileOrphanedSystemProxiesAsync(ILogger? logger = null, CancellationToken cancellationToken = default) { var orphanedPids = (await StateManager.GetOrphanedSystemProxyStatesAsync(cancellationToken)) .Select(o => o.Pid) @@ -475,14 +491,18 @@ public static async Task ReconcileOrphanedSystemProxiesAsy if (orphanedPids.Count == 0) { - return new([], false); + return new([], OrphanRestoreOutcome.Restored); } - var restored = false; + var outcome = OrphanRestoreOutcome.OwnedByLiveInstance; if (await FindLiveSystemProxyOwnerAsync(cancellationToken) is null) { - restored = new SystemProxyManager(NullLogger.Instance).Restore() - is SystemProxyRestoreResult.RestoredPrevious or SystemProxyRestoreResult.Disabled; + if (new SystemProxyManager(logger ?? NullLogger.Instance).Restore() is SystemProxyRestoreResult.Failed) + { + // Keep the state records (and the snapshot) so the next start or stop retries. + return new(orphanedPids, OrphanRestoreOutcome.Failed); + } + outcome = OrphanRestoreOutcome.Restored; } foreach (var pid in orphanedPids) @@ -490,6 +510,6 @@ public static async Task ReconcileOrphanedSystemProxiesAsy await StateManager.DeleteStateAsync(pid, cancellationToken); } - return new(orphanedPids, restored); + return new(orphanedPids, outcome); } } diff --git a/DevProxy/toggle-proxy.sh b/DevProxy/toggle-proxy.sh index 50b3f284..5082cd61 100644 --- a/DevProxy/toggle-proxy.sh +++ b/DevProxy/toggle-proxy.sh @@ -5,7 +5,11 @@ ip=$2 port=$3 # Skip the header line and disabled services (prefixed with *), which networksetup can't configure. -network_services=$(networksetup -listallnetworkservices | tail -n +2 | grep -v '^\*') +if ! all_services=$(networksetup -listallnetworkservices); then + echo "Failed to list network services." + exit 1 +fi +network_services=$(echo "$all_services" | tail -n +2 | grep -v '^\*') status=0 From d14a4894f6797a4981502c4ed492042c3a4db7c5 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 5 Nov 2026 12:11:35 +0100 Subject: [PATCH 04/22] Restore macOS snapshot after partial disable failure; harden standalone reset parsing Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy/Commands/DevProxyCommand.cs | 20 +++++++++++++++++--- DevProxy/Commands/SystemProxyCommand.cs | 7 +++---- DevProxy/Proxy/SystemProxyManager.cs | 6 ++++-- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index af668b8f..9ef4f5a6 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -143,9 +143,23 @@ public static bool IsSystemProxyResetCommand } var args = Environment.GetCommandLineArgs(); - field = args.Length > 2 && - string.Equals(args[1], "system-proxy", StringComparison.OrdinalIgnoreCase) && - string.Equals(args[2], "reset", StringComparison.OrdinalIgnoreCase) && + // Global options can appear anywhere, so skip them (and their values) to find + // the command path. + var tokens = new List(); + for (var i = 1; i < args.Length; i++) + { + if (args[i] is OutputOptionName or LogLevelOptionName) + { + i++; + } + else if (args[i] is not NoColorOptionName) + { + tokens.Add(args[i]); + } + } + field = tokens.Count > 1 && + string.Equals(tokens[0], "system-proxy", StringComparison.OrdinalIgnoreCase) && + string.Equals(tokens[1], "reset", StringComparison.OrdinalIgnoreCase) && !args.Any(arg => helpOptions.Contains(arg)); _isSystemProxyResetCommandResolved = true; return field; diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index ab5bd7c6..ec03c008 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using DevProxy.Abstractions.Proxy; using DevProxy.Logging; using DevProxy.Proxy; using DevProxy.State; @@ -50,10 +51,8 @@ internal static async Task RunResetStandaloneAsync(string[] args) var forceOption = new Option("--force", "-f"); var resetCommand = new Command("reset") { forceOption }; var rootCommand = new RootCommand { new Command("system-proxy") { resetCommand } }; - foreach (var name in new[] { DevProxyCommand.OutputOptionName, DevProxyCommand.LogLevelOptionName }) - { - rootCommand.Options.Add(new Option(name) { Recursive = true }); - } + rootCommand.Options.Add(new Option(DevProxyCommand.OutputOptionName) { Recursive = true }); + rootCommand.Options.Add(new Option(DevProxyCommand.LogLevelOptionName) { Recursive = true }); rootCommand.Options.Add(new Option(DevProxyCommand.NoColorOptionName) { Recursive = true, Arity = ArgumentArity.Zero }); var parseResult = rootCommand.Parse(args); diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 7df9b263..972dc52f 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -148,9 +148,11 @@ internal SystemProxyRestoreResult Restore() { succeeded = RunToggleScript("off"); restoredPrevious = snapshot?.MacOS is not null; - if (succeeded && restoredPrevious) + // Restore even if turning off failed for some services, so the services that + // did turn off get their previous proxy back. Either failure keeps the snapshot. + if (restoredPrevious && !RestoreMacOS(snapshot!.MacOS!)) { - succeeded = RestoreMacOS(snapshot!.MacOS!); + succeeded = false; } } From 57007bc1b8a29bbf53df17b25abc77adace8b46a Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 5 Nov 2026 12:20:27 +0100 Subject: [PATCH 05/22] Detect system-proxy reset via System.CommandLine parsing Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 20 ++++++++++++++++ DevProxy/Commands/DevProxyCommand.cs | 18 +-------------- DevProxy/Commands/SystemProxyCommand.cs | 28 +++++++++++++++++++---- 3 files changed, 44 insertions(+), 22 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 9ea84fd3..f08592e0 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -143,3 +143,23 @@ public void Load_CorruptFile_ReturnsNull() } } } + +public class SystemProxyResetDetectionTests +{ + [Theory] + [InlineData("system-proxy", "reset")] + [InlineData("system-proxy", "reset", "--force")] + [InlineData("--output=json", "system-proxy", "reset")] + [InlineData("system-proxy", "--no-color", "reset")] + [InlineData("--log-level", "debug", "system-proxy", "reset", "--bogus")] + public void IsResetInvocation_ReturnsTrue(params string[] args) => + Assert.True(DevProxy.Commands.SystemProxyCommand.IsResetInvocation(args)); + + [Theory] + [InlineData("system-proxy")] + [InlineData("reset")] + [InlineData("stop")] + [InlineData] + public void IsResetInvocation_ReturnsFalse(params string[] args) => + Assert.False(DevProxy.Commands.SystemProxyCommand.IsResetInvocation(args)); +} diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 9ef4f5a6..8be9a69a 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -143,23 +143,7 @@ public static bool IsSystemProxyResetCommand } var args = Environment.GetCommandLineArgs(); - // Global options can appear anywhere, so skip them (and their values) to find - // the command path. - var tokens = new List(); - for (var i = 1; i < args.Length; i++) - { - if (args[i] is OutputOptionName or LogLevelOptionName) - { - i++; - } - else if (args[i] is not NoColorOptionName) - { - tokens.Add(args[i]); - } - } - field = tokens.Count > 1 && - string.Equals(tokens[0], "system-proxy", StringComparison.OrdinalIgnoreCase) && - string.Equals(tokens[1], "reset", StringComparison.OrdinalIgnoreCase) && + field = SystemProxyCommand.IsResetInvocation(args.Skip(1).ToArray()) && !args.Any(arg => helpOptions.Contains(arg)); _isSystemProxyResetCommandResolved = true; return field; diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index ec03c008..3c500e68 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -41,20 +41,38 @@ private Task ResetAsync(ParseResult parseResult, CancellationToken cancella ResetCoreAsync(parseResult.GetValue(_forceOption), _systemProxyLogger, cancellationToken); /// - /// Runs system-proxy reset without building the application host, so a broken - /// configuration or plugin can't prevent restoring network access. + /// Builds a minimal command tree mirroring the registered system-proxy reset + /// command and the global options, so the standalone path parses arguments the same way. /// - internal static async Task RunResetStandaloneAsync(string[] args) + private static (RootCommand RootCommand, Option ForceOption) CreateStandaloneResetParser() { - // Parse with a minimal command tree mirroring the registered command so values - // like '--force false' and invalid arguments are handled the same way. var forceOption = new Option("--force", "-f"); var resetCommand = new Command("reset") { forceOption }; var rootCommand = new RootCommand { new Command("system-proxy") { resetCommand } }; rootCommand.Options.Add(new Option(DevProxyCommand.OutputOptionName) { Recursive = true }); rootCommand.Options.Add(new Option(DevProxyCommand.LogLevelOptionName) { Recursive = true }); rootCommand.Options.Add(new Option(DevProxyCommand.NoColorOptionName) { Recursive = true, Arity = ArgumentArity.Zero }); + return (rootCommand, forceOption); + } + /// + /// Returns whether the arguments (without the executable) invoke system-proxy reset, + /// wherever global options appear and however their values are attached. + /// + internal static bool IsResetInvocation(string[] args) + { + var commandResult = CreateStandaloneResetParser().RootCommand.Parse(args).CommandResult; + return commandResult.Command.Name == "reset" && + commandResult.Parent is System.CommandLine.Parsing.CommandResult { Command.Name: "system-proxy" }; + } + + /// + /// Runs system-proxy reset without building the application host, so a broken + /// configuration or plugin can't prevent restoring network access. + /// + internal static async Task RunResetStandaloneAsync(string[] args) + { + var (rootCommand, forceOption) = CreateStandaloneResetParser(); var parseResult = rootCommand.Parse(args); if (parseResult.Errors.Count > 0) { From 6e20a0b5b2def857488723ff58f21069a6c5bb53 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 5 Nov 2026 12:29:06 +0100 Subject: [PATCH 06/22] Leave parsed help to the full command tree Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 1 + DevProxy/Commands/SystemProxyCommand.cs | 8 +++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index f08592e0..b1241040 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -159,6 +159,7 @@ public void IsResetInvocation_ReturnsTrue(params string[] args) => [InlineData("system-proxy")] [InlineData("reset")] [InlineData("stop")] + [InlineData("system-proxy", "reset", "--force", "--help")] [InlineData] public void IsResetInvocation_ReturnsFalse(params string[] args) => Assert.False(DevProxy.Commands.SystemProxyCommand.IsResetInvocation(args)); diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index 3c500e68..a0811c95 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -61,7 +61,13 @@ private static (RootCommand RootCommand, Option ForceOption) CreateStandal /// internal static bool IsResetInvocation(string[] args) { - var commandResult = CreateStandaloneResetParser().RootCommand.Parse(args).CommandResult; + var parseResult = CreateStandaloneResetParser().RootCommand.Parse(args); + // Leave help (including help in a response file) to the full command tree. + if (parseResult.Action is System.CommandLine.Help.HelpAction) + { + return false; + } + var commandResult = parseResult.CommandResult; return commandResult.Command.Name == "reset" && commandResult.Parent is System.CommandLine.Parsing.CommandResult { Command.Name: "system-proxy" }; } From ec80e69de90bd38a0587bf1808fd80a2caacd4ad Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 08:03:27 +0100 Subject: [PATCH 07/22] Fix system-proxy command compatibility after upstream merge Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 13 ++++ DevProxy/Commands/SystemProxyCommand.cs | 80 ++++++++++++++++------- 2 files changed, 68 insertions(+), 25 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index b1241040..5afc2953 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -146,6 +146,19 @@ public void Load_CorruptFile_ReturnsNull() public class SystemProxyResetDetectionTests { + [Theory] + [InlineData("--bogus")] + [InlineData("--output", "invalid")] + [InlineData("--log-level", "invalid")] + [InlineData("--output=json", "--bogus")] + public async Task RunResetStandalone_InvalidArguments_ReturnsUsageError(params string[] args) + { + var exitCode = await DevProxy.Commands.SystemProxyCommand.RunResetStandaloneAsync( + ["system-proxy", "reset", .. args]); + + Assert.Equal(2, exitCode); + } + [Theory] [InlineData("system-proxy", "reset")] [InlineData("system-proxy", "reset", "--force")] diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index 187d131e..e3ae9600 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -3,25 +3,30 @@ // See the LICENSE file in the project root for more information. using DevProxy.Abstractions.Proxy; +using DevProxy.Abstractions.Utils; using DevProxy.Logging; using DevProxy.Proxy; using DevProxy.State; using System.CommandLine; +using System.CommandLine.Parsing; +using System.Text.Json; namespace DevProxy.Commands; sealed class SystemProxyCommand : Command { private readonly ILogger _systemProxyLogger; + private readonly ILogger _logger; private readonly Option _forceOption = new("--force", "-f") { Description = "Reset the system proxy even if a running Dev Proxy instance owns it" }; - public SystemProxyCommand(ILogger systemProxyLogger) : + public SystemProxyCommand(ILogger systemProxyLogger, ILogger logger) : base("system-proxy", "Manage the system proxy settings changed by Dev Proxy") { _systemProxyLogger = systemProxyLogger; + _logger = logger; var resetCommand = new Command("reset", "Restore the system proxy settings that Dev Proxy changed. Use after Dev Proxy was killed or crashed."); resetCommand.Add(_forceOption); @@ -29,16 +34,18 @@ public SystemProxyCommand(ILogger systemProxyLogger) : Add(resetCommand); HelpExamples.Add(this, [ - "devproxy system-proxy reset Restore system proxy settings", + ("devproxy system-proxy reset", "Restore system proxy settings"), ]); HelpExamples.Add(resetCommand, [ - "devproxy system-proxy reset Restore system proxy settings", - "devproxy system-proxy reset --force Restore even if Dev Proxy is running", + ("devproxy system-proxy reset", "Restore system proxy settings"), + ("devproxy system-proxy reset --force", "Restore even if Dev Proxy is running"), ]); } private Task ResetAsync(ParseResult parseResult, CancellationToken cancellationToken) => - ResetCoreAsync(parseResult.GetValue(_forceOption), _systemProxyLogger, cancellationToken); + ResetCoreAsync(parseResult.GetValue(_forceOption), + parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName) ?? OutputFormat.Text, + _logger, _systemProxyLogger, cancellationToken); /// /// Builds a minimal command tree mirroring the registered system-proxy reset @@ -80,55 +87,66 @@ internal static async Task RunResetStandaloneAsync(string[] args) { var (rootCommand, forceOption) = CreateStandaloneResetParser(); var parseResult = rootCommand.Parse(args); - if (parseResult.Errors.Count > 0) - { - foreach (var error in parseResult.Errors) - { - await Console.Error.WriteLineAsync(error.Message); - } - return 1; - } - var force = parseResult.GetValue(forceOption); + var outputFormat = parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName) ?? OutputFormat.Text; + var logLevel = parseResult.GetValueOrDefault(DevProxyCommand.LogLevelOptionName) ?? LogLevel.Information; using var loggerFactory = LoggerFactory.Create(builder => { _ = builder - .SetMinimumLevel(LogLevel.Information) + .SetMinimumLevel(logLevel) .AddConsole(consoleOptions => { - consoleOptions.FormatterName = ProxyConsoleFormatter.DefaultCategoryName; + consoleOptions.FormatterName = outputFormat == OutputFormat.Json + ? JsonConsoleFormatter.FormatterName + : ProxyConsoleFormatter.DefaultCategoryName; consoleOptions.LogToStandardErrorThreshold = LogLevel.Warning; }) .AddConsoleFormatter(formatterOptions => + { + formatterOptions.IncludeScopes = false; + formatterOptions.ShowTimestamps = false; + }) + .AddConsoleFormatter(formatterOptions => { formatterOptions.IncludeScopes = false; formatterOptions.ShowTimestamps = false; }); }); + var logger = loggerFactory.CreateLogger(); + if (parseResult.Errors.Count > 0) + { + foreach (var error in parseResult.Errors) + { + logger.LogError("{Message}", error.Message); + } + return 2; + } - return await ResetCoreAsync(force, loggerFactory.CreateLogger(), CancellationToken.None); + return await ResetCoreAsync(parseResult.GetValue(forceOption), outputFormat, logger, + loggerFactory.CreateLogger(), CancellationToken.None); } - private static async Task ResetCoreAsync(bool force, ILogger logger, CancellationToken cancellationToken) + private static async Task ResetCoreAsync(bool force, OutputFormat outputFormat, + ILogger logger, ILogger systemProxyLogger, CancellationToken cancellationToken) { if (!OperatingSystem.IsWindows() && !OperatingSystem.IsMacOS()) { - Console.WriteLine("Dev Proxy doesn't change the system proxy settings on this operating system. Nothing to reset."); + LogResult("Dev Proxy doesn't change the system proxy settings on this operating system. Nothing to reset.", outputFormat, logger); return 0; } var liveOwner = await SystemProxyManager.FindLiveSystemProxyOwnerAsync(cancellationToken); if (liveOwner is not null && !force) { - await Console.Error.WriteLineAsync($"Dev Proxy (PID: {liveOwner}) is running as the system proxy."); - await Console.Error.WriteLineAsync("Use 'devproxy stop' to stop it, or 'devproxy system-proxy reset --force' to reset anyway."); + logger.LogError("Dev Proxy (PID: {Pid}) is running as the system proxy.", liveOwner); + logger.LogError("Use 'devproxy stop' to stop it, or 'devproxy system-proxy reset --force' to reset anyway."); return 1; } - var result = new SystemProxyManager(logger).Restore(); + var result = new SystemProxyManager(systemProxyLogger).Restore(); if (result is SystemProxyRestoreResult.Failed) { - await Console.Error.WriteLineAsync("Couldn't restore the system proxy settings. To reset them manually, see https://go.devproxy.net?go=proxy-reset."); + logger.LogError("Couldn't restore the system proxy settings. To reset them manually, see https://go.devproxy.net?go=proxy-reset."); return 1; } @@ -148,9 +166,21 @@ private static async Task ResetCoreAsync(bool force, ILogger logger) + { + if (outputFormat == OutputFormat.Json) + { + logger.LogStructuredOutput(JsonSerializer.Serialize(new { message }, ProxyUtils.JsonSerializerOptions)); + } + else + { + logger.LogInformation("{Message}", message); + } + } } From abb3efc6fd9d0f0c5ca757ddee5fd3f7e2b8c811 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 08:18:46 +0100 Subject: [PATCH 08/22] Preserve system proxy recovery records and verify ownership Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/StateManagerPidReuseTests.cs | 24 +++++ DevProxy.Tests/SystemProxyManagerTests.cs | 112 ++++++++++++++++++++ DevProxy/Commands/StopCommand.cs | 20 ++-- DevProxy/Proxy/SystemProxyManager.cs | 14 +-- DevProxy/Proxy/SystemProxySnapshot.cs | 11 +- DevProxy/State/StateManager.cs | 14 ++- 6 files changed, 175 insertions(+), 20 deletions(-) diff --git a/DevProxy.Tests/StateManagerPidReuseTests.cs b/DevProxy.Tests/StateManagerPidReuseTests.cs index 2a413c27..f78ca394 100644 --- a/DevProxy.Tests/StateManagerPidReuseTests.cs +++ b/DevProxy.Tests/StateManagerPidReuseTests.cs @@ -13,6 +13,30 @@ namespace DevProxy.Tests; [Collection("management-environment")] public class StateManagerPidReuseTests { + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task StateLookups_PreserveOrphanedSystemProxyUntilRecovery(bool asSystemProxy) + { + var pid = Random.Shared.Next(int.MaxValue / 2, int.MaxValue); + var path = StateManager.GetInstanceStateFilePath(pid); + Assert.False(File.Exists(path)); + try + { + await StateManager.SaveStateAsync(new() { Pid = pid, AsSystemProxy = asSystemProxy }); + + _ = await StateManager.FindSystemProxyInstanceAsync(); + Assert.True(File.Exists(path)); + + Assert.Null(await StateManager.LoadStateByPidAsync(pid)); + Assert.Equal(asSystemProxy, File.Exists(path)); + } + finally + { + File.Delete(path); + } + } + [Fact] public void ProcessStartTime_RoundTripsThroughJson() { diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 5afc2953..e236596e 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -3,6 +3,8 @@ // See the LICENSE file in the project root for more information. using DevProxy.Proxy; +using DevProxy.State; +using Microsoft.Extensions.Logging.Abstractions; using Xunit; @@ -10,6 +12,97 @@ namespace DevProxy.Tests; public class SystemProxyManagerTests { + [Fact] + public void Disable_AfterSuccessfulRestore_DoesNotRestoreAgain() + { + var folder = Directory.CreateTempSubdirectory("devproxy-cleanup-"); + try + { + var path = Path.Combine(folder.FullName, "snapshot.json"); + var manager = new SystemProxyManager(NullLogger.Instance, path); + manager.SaveSnapshot(snapshot => snapshot.Windows = new() { ProxyEnable = 1, ProxyServer = "corp:8080" }); + var restoreCalls = 0; + void Restore() + { + restoreCalls++; + SystemProxySnapshotStore.Delete(path); + } + + manager.Disable(Restore); + manager.Disable(Restore); + + Assert.Equal(1, restoreCalls); + } + finally + { + folder.Delete(recursive: true); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Disable_AfterResetOrTakeover_LeavesSettingsAlone(bool takeover) + { + var folder = Directory.CreateTempSubdirectory("devproxy-cleanup-"); + try + { + var path = Path.Combine(folder.FullName, "snapshot.json"); + var manager = new SystemProxyManager(NullLogger.Instance, path); + manager.SaveSnapshot(_ => { }); + if (takeover) + { + SystemProxySnapshotStore.Save(path, new() { Pid = int.MaxValue }); + } + else + { + SystemProxySnapshotStore.Delete(path); + } + var restoreCalls = 0; + + manager.Disable(() => restoreCalls++); + manager.Disable(() => restoreCalls++); + + Assert.Equal(0, restoreCalls); + } + finally + { + folder.Delete(recursive: true); + } + } + + [Fact] + public void SaveSnapshot_Takeover_UpdatesIdentityAndPreservesPreviousSettings() + { + var folder = Directory.CreateTempSubdirectory("devproxy-takeover-"); + try + { + var path = Path.Combine(folder.FullName, "snapshot.json"); + SystemProxySnapshotStore.Save(path, new() + { + Pid = int.MaxValue, + ProcessStartTime = DateTimeOffset.UnixEpoch, + Windows = new() { ProxyEnable = 1, ProxyServer = "corp:8080" }, + }); + var manager = new SystemProxyManager(NullLogger.Instance, path); + var captured = false; + + manager.SaveSnapshot(_ => captured = true); + + var snapshot = SystemProxySnapshotStore.Load(path); + Assert.NotNull(snapshot); + Assert.False(captured); + Assert.Equal(Environment.ProcessId, snapshot.Pid); + Assert.NotNull(snapshot.ProcessStartTime); + Assert.True(snapshot.IsOwnerAlive()); + Assert.Equal("corp:8080", snapshot.Windows?.ProxyServer); + } + finally + { + folder.Delete(recursive: true); + } + } + [Fact] public void CreateToggleScriptStartInfo_PreservesPathAndArgumentsContainingSpaces() { @@ -103,6 +196,7 @@ public void SaveLoadDelete_RoundTripsSnapshot() var snapshot = new SystemProxySnapshot { Pid = 1234, + ProcessStartTime = DateTimeOffset.UnixEpoch.AddSeconds(1), CreatedAt = DateTimeOffset.UnixEpoch, Windows = new() { ProxyEnable = 1, ProxyServer = "corp:8080" }, MacOS = [new() { Service = "Wi-Fi", Web = new() { Enabled = true, Server = "corp", Port = 8080 } }], @@ -113,6 +207,7 @@ public void SaveLoadDelete_RoundTripsSnapshot() Assert.NotNull(loaded); Assert.Equal(1234, loaded.Pid); + Assert.Equal(snapshot.ProcessStartTime, loaded.ProcessStartTime); Assert.Equal(1, loaded.Windows?.ProxyEnable); Assert.Equal("corp:8080", loaded.Windows?.ProxyServer); var service = Assert.Single(loaded.MacOS!); @@ -128,6 +223,23 @@ public void SaveLoadDelete_RoundTripsSnapshot() } } + public class SystemProxySnapshotOwnershipTests + { + [Theory] + [InlineData(false)] + [InlineData(true)] + public void IsOwnerAlive_VerifiesStartTime(bool reusedPid) + { + var snapshot = new SystemProxySnapshot + { + Pid = Environment.ProcessId, + ProcessStartTime = StateManager.GetCurrentProcessStartTime()!.Value.AddMinutes(reusedPid ? -30 : 0), + }; + + Assert.Equal(!reusedPid, snapshot.IsOwnerAlive()); + } + } + [Fact] public void Load_CorruptFile_ReturnsNull() { diff --git a/DevProxy/Commands/StopCommand.cs b/DevProxy/Commands/StopCommand.cs index 52057424..f487fc65 100644 --- a/DevProxy/Commands/StopCommand.cs +++ b/DevProxy/Commands/StopCommand.cs @@ -71,20 +71,14 @@ private async Task RunAsync(ParseResult parseResult, CancellationToken canc private static async Task StopByPidAsync(int pid, bool force, CancellationToken cancellationToken) { - // Capture a potential orphaned system-proxy record before LoadStateByPidAsync - // prunes (deletes) the stale state file for a dead PID. + // Recover an orphan before looking up live state so failed recovery keeps + // its registration available for a later retry. var orphan = (await StateManager.GetOrphanedSystemProxyStatesAsync(cancellationToken)) .Find(o => o.Pid == pid); - var state = await StateManager.LoadStateByPidAsync(pid, cancellationToken); - if (state is not null) - { - return await StopInstanceAsync(state, force, cancellationToken); - } - if (orphan is not null) { - var liveOwner = await StateManager.FindSystemProxyInstanceAsync(cancellationToken); + var liveOwner = await SystemProxyManager.FindLiveSystemProxyOwnerAsync(cancellationToken); if (liveOwner is null) { if (new SystemProxyManager(NullLogger.Instance).Restore() is SystemProxyRestoreResult.Failed) @@ -97,13 +91,19 @@ private static async Task StopByPidAsync(int pid, bool force, CancellationT } else { - Console.WriteLine($"Removed stale record for crashed Dev Proxy (PID: {pid}); system proxy is owned by a running instance (PID: {liveOwner.Pid})."); + Console.WriteLine($"Removed stale record for crashed Dev Proxy (PID: {pid}); system proxy is owned by a running instance (PID: {liveOwner})."); } await StateManager.DeleteStateAsync(orphan, cancellationToken); return 0; } + var state = await StateManager.LoadStateByPidAsync(pid, cancellationToken); + if (state is not null) + { + return await StopInstanceAsync(state, force, cancellationToken); + } + Console.WriteLine($"No running Dev Proxy instance with PID {pid}."); return 1; } diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 88c31373..ef77efda 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -105,11 +105,12 @@ public void Enable(string? ipAddress, int port) } } - public void Disable() + public void Disable() => Disable(() => _ = Restore()); + + internal void Disable(Action restore) { if (_savedSnapshot) { - _savedSnapshot = false; // The snapshot is gone or belongs to another process when 'system-proxy reset' // already restored the settings or another instance took over. Restoring now // would undo that, so leave the settings alone. @@ -119,7 +120,7 @@ public void Disable() } } - _ = Restore(); + restore(); } /// @@ -171,7 +172,7 @@ internal SystemProxyRestoreResult Restore() : SystemProxyRestoreResult.Disabled; } - private void SaveSnapshot(Action capture) + internal void SaveSnapshot(Action capture) { try { @@ -184,6 +185,7 @@ private void SaveSnapshot(Action capture) capture(snapshot); } snapshot.Pid = Environment.ProcessId; + snapshot.ProcessStartTime = StateManager.GetCurrentProcessStartTime(); SystemProxySnapshotStore.Save(_snapshotPath, snapshot); _savedSnapshot = true; } @@ -469,7 +471,7 @@ internal readonly record struct OrphanReconciliation( } var snapshot = SystemProxySnapshotStore.Load(SystemProxySnapshotStore.DefaultPath); - return snapshot is not null && StateManager.IsProcessRunning(snapshot.Pid) + return snapshot is not null && snapshot.IsOwnerAlive() ? snapshot.Pid : null; } @@ -488,7 +490,7 @@ public static async Task ReconcileOrphanedSystemProxiesAsy // foreground instance) is also an orphan. int? snapshotOnlyPid = null; var snapshot = SystemProxySnapshotStore.Load(SystemProxySnapshotStore.DefaultPath); - if (snapshot is not null && !StateManager.IsProcessRunning(snapshot.Pid) && !orphanedPids.Contains(snapshot.Pid)) + if (snapshot is not null && !snapshot.IsOwnerAlive() && !orphanedPids.Contains(snapshot.Pid)) { snapshotOnlyPid = snapshot.Pid; orphanedPids.Add(snapshot.Pid); diff --git a/DevProxy/Proxy/SystemProxySnapshot.cs b/DevProxy/Proxy/SystemProxySnapshot.cs index acb3b0cc..fc644f1b 100644 --- a/DevProxy/Proxy/SystemProxySnapshot.cs +++ b/DevProxy/Proxy/SystemProxySnapshot.cs @@ -11,7 +11,7 @@ namespace DevProxy.Proxy; /// /// The OS proxy settings that were in place before Dev Proxy registered itself as the -/// system proxy, plus the PID of the instance that did it. Persisted to disk so the +/// system proxy, plus the process identity of the instance that did it. Persisted to disk so the /// settings can be restored even if that instance is killed or crashes. /// internal sealed class SystemProxySnapshot @@ -19,6 +19,15 @@ internal sealed class SystemProxySnapshot [JsonPropertyName("pid")] public int Pid { get; set; } + [JsonPropertyName("processStartTime")] + public DateTimeOffset? ProcessStartTime { get; set; } + + internal bool IsOwnerAlive() => StateManager.IsInstanceAlive(new ProxyInstanceState + { + Pid = Pid, + ProcessStartTime = ProcessStartTime, + }); + [JsonPropertyName("createdAt")] public DateTimeOffset CreatedAt { get; set; } diff --git a/DevProxy/State/StateManager.cs b/DevProxy/State/StateManager.cs index c1981970..e39f9ebb 100644 --- a/DevProxy/State/StateManager.cs +++ b/DevProxy/State/StateManager.cs @@ -137,7 +137,8 @@ public static Task SaveStateAsync(ProxyInstanceState state, CancellationToken ca } /// - /// Loads all live detached instance states, cleaning up stale state files. + /// Loads all live detached instance states, cleaning up stale state files except + /// system-proxy recovery records, which reconciliation removes after recovery. /// Also checks the legacy state.json for backward compatibility. /// public static async Task> LoadAllStatesAsync(CancellationToken cancellationToken = default) @@ -195,8 +196,8 @@ public static async Task> LoadAllStatesAsync(Cancellati /// public static async Task FindSystemProxyInstanceAsync(CancellationToken cancellationToken = default) { - var states = await LoadAllStatesAsync(cancellationToken); - return states.Find(s => s.AsSystemProxy); + var states = await LoadRunningStatesAsync(cancellationToken); + return states.Find(s => s.AsSystemProxy && IsInstanceAlive(s)); } /// @@ -461,6 +462,13 @@ internal static bool IsProcessRunning(int pid) // an unrelated process that reused the PID if (!IsInstanceAlive(state)) { + // Only successful system-proxy reconciliation may remove its recovery + // record. Diagnostics and failed recovery must leave it available to retry. + if (state.AsSystemProxy) + { + return null; + } + // Clean up stale state file await DeleteStateFileIfMatchesAsync(filePath, state, cancellationToken); DeleteTokenIfProcessGone(state.Pid); From a5aecfa39e855a4bf3be333a0c3704e61d0ce338 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 08:26:09 +0100 Subject: [PATCH 09/22] Check snapshot process identity before deleting stale state Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy/Proxy/SystemProxyManager.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index ef77efda..67665279 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -517,9 +517,13 @@ public static async Task ReconcileOrphanedSystemProxiesAsy await StateManager.DeleteStateAsync(orphan, cancellationToken); } - if (snapshotOnlyPid is int pid) + if (snapshotOnlyPid is int pid && snapshot is not null) { - await StateManager.DeleteStateAsync(pid, cancellationToken); + await StateManager.DeleteStateAsync(new ProxyInstanceState + { + Pid = pid, + ProcessStartTime = snapshot.ProcessStartTime, + }, cancellationToken); } return new(orphanedPids, outcome); From 719262200605ab85867450582f4dda55a3cf51bf Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 15:33:47 +0100 Subject: [PATCH 10/22] Gate proxy recovery on parsed start and trust snapshot owner - Run startup recovery only when the parsed arguments (including response files) start the proxy, so read-only commands like 'devproxy --output json status' don't change OS proxy settings. - Treat the snapshot's process identity as the system proxy owner when a snapshot exists, so a crashed newer owner is recoverable even if an older detached instance is still running. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/DevProxyCommandTests.cs | 41 +++++++++++ DevProxy.Tests/SystemProxyManagerTests.cs | 49 +++++++++++++ DevProxy/Commands/DevProxyCommand.cs | 89 +++++++++++++++++++++++ DevProxy/Program.cs | 10 +-- DevProxy/Proxy/SystemProxyManager.cs | 23 +++--- 5 files changed, 197 insertions(+), 15 deletions(-) diff --git a/DevProxy.Tests/DevProxyCommandTests.cs b/DevProxy.Tests/DevProxyCommandTests.cs index ffcba30f..9a6ed3a8 100644 --- a/DevProxy.Tests/DevProxyCommandTests.cs +++ b/DevProxy.Tests/DevProxyCommandTests.cs @@ -52,3 +52,44 @@ public void ApplyDiscoverOption_False_KeepsRecordingEnabledFromOtherSources() Assert.True(config.Record); } } + +public class DevProxyCommandStartInvocationTests +{ + [Theory] + [InlineData(true)] + [InlineData(true, "--port", "0", "--as-system-proxy", "false")] + [InlineData(true, "--output", "json", "--log-level", "debug")] + [InlineData(true, "--output=json", "-u", "https://a.example/*", "https://b.example/*")] + [InlineData(true, "--mocks-file", "mocks.json", "--no-mocks")] + [InlineData(true, "--record", "--watch-pids", "1", "2")] + [InlineData(false, "status")] + [InlineData(false, "--output", "json", "status", "--pid", "1")] + [InlineData(false, "--config-file", "devproxyrc.json", "--output", "json", "status")] + [InlineData(false, "--log-level=debug", "system-proxy", "reset")] + [InlineData(false, "--record", "stop")] + [InlineData(false, "mocks", "from-http-responses")] + [InlineData(false, "--help")] + [InlineData(false, "--port", "0", "-h")] + [InlineData(false, "--version")] + [InlineData(false, "@missing-response-file.rsp")] + public void IsStartInvocation_UsesParsedCommand(bool expected, params string[] args) => + Assert.Equal(expected, DevProxyCommand.IsStartInvocation(args)); + + [Theory] + [InlineData(true, "--port 0\n--output json")] + [InlineData(false, "--output json\nstatus")] + [InlineData(false, "--port 0\n--help")] + public void IsStartInvocation_ExpandsResponseFiles(bool expected, string contents) + { + var path = Path.GetTempFileName(); + try + { + File.WriteAllText(path, contents); + Assert.Equal(expected, DevProxyCommand.IsStartInvocation([$"@{path}"])); + } + finally + { + File.Delete(path); + } + } +} diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index e236596e..fc91b9a8 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -289,3 +289,52 @@ public void IsResetInvocation_ReturnsTrue(params string[] args) => public void IsResetInvocation_ReturnsFalse(params string[] args) => Assert.False(DevProxy.Commands.SystemProxyCommand.IsResetInvocation(args)); } + +[Collection("management-environment")] +public class SystemProxyOwnerLookupTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task FindLiveSystemProxyOwner_PrefersSnapshotOverOlderDetachedOwner(bool withDeadSnapshotOwner) + { + var folder = Directory.CreateTempSubdirectory("devproxy-owner-"); + var statePath = StateManager.GetInstanceStateFilePath(Environment.ProcessId); + Assert.False(File.Exists(statePath)); + try + { + // A live detached instance that registered as the system proxy before a newer one took over. + await StateManager.SaveStateAsync(new() + { + Pid = Environment.ProcessId, + ProcessStartTime = StateManager.GetCurrentProcessStartTime(), + AsSystemProxy = true, + }); + var snapshotPath = Path.Combine(folder.FullName, "snapshot.json"); + if (withDeadSnapshotOwner) + { + SystemProxySnapshotStore.Save(snapshotPath, new() + { + Pid = int.MaxValue, + ProcessStartTime = DateTimeOffset.UnixEpoch, + }); + } + + var owner = await SystemProxyManager.FindLiveSystemProxyOwnerAsync(snapshotPath); + + if (withDeadSnapshotOwner) + { + Assert.Null(owner); + } + else + { + Assert.NotNull(owner); + } + } + finally + { + File.Delete(statePath); + folder.Delete(recursive: true); + } + } +} diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index c9f284d1..517fad4e 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -207,6 +207,95 @@ public static bool IsDetachedMode } } + /// + /// Returns whether the arguments (without the executable) start the proxy, rather than + /// invoking a subcommand, showing help or the version, or failing to parse. Parses the + /// arguments, including response files, wherever options appear and however their + /// values are attached. Runs before plugins load, so tokens that aren't a built-in + /// option or the value of an unknown (plugin) option are treated as a subcommand. + /// + internal static bool IsStartInvocation(string[] args) + { + // Mirrors the arity of the root options registered in ConfigureCommand. Values are + // parsed as strings so that invalid values don't affect where tokens are consumed. + static Option Value(string name, params string[] aliases) => new(name, aliases); + static Option Values(string name, params string[] aliases) => new(name, aliases) + { + AllowMultipleArgumentsPerToken = true, + Arity = ArgumentArity.ZeroOrMore + }; + static Option Flag(string name, params string[] aliases) => new(name, aliases); + + var rootCommand = new RootCommand { TreatUnmatchedTokensAsErrors = false }; + Option[] options = + [ + Value(ApiPortOptionName), + Value(ApiIpAddressOptionName), + Flag(AsSystemProxyOptionName), + Value(ConfigFileOptionName, "-c"), + Flag(DetachedOptionName, "-d"), + Flag(DiscoverOptionName), + Values(EnvOptionName, "-e"), + Flag(InstallCertOptionName), + Flag(InternalDaemonOptionName), + Value(IpAddressOptionName), + Value(LogLevelOptionName), + new Option(NoColorOptionName) { Arity = ArgumentArity.Zero }, + Flag(NoFirstRunOptionName), + Flag(NoWatchOptionName), + Value(OutputOptionName), + Value(PortOptionName, "-p"), + Flag(RecordOptionName), + Value(TimeoutOptionName, "-t"), + Values(UrlsToWatchOptionName, "-u"), + Values(WatchPidsOptionName), + Values(WatchProcessNamesOptionName), + Flag(WatchProcessTreeOptionName), + ]; + foreach (var option in options) + { + rootCommand.Options.Add(option); + } + + var parseResult = rootCommand.Parse(args); + // Help, version and parse errors (such as a missing response file) have an action. + if (parseResult.Action is not null) + { + return false; + } + + var knownTokens = new HashSet(ReferenceEqualityComparer.Instance); + foreach (var option in rootCommand.Options) + { + if (parseResult.GetResult(option) is OptionResult { Implicit: false } optionResult) + { + if (optionResult.IdentifierToken is not null) + { + _ = knownTokens.Add(optionResult.IdentifierToken); + } + knownTokens.UnionWith(optionResult.Tokens); + } + } + + var afterUnknownOption = false; + foreach (var token in parseResult.Tokens) + { + if (knownTokens.Contains(token)) + { + afterUnknownOption = false; + } + else if (token.Value.StartsWith('-')) + { + afterUnknownOption = true; + } + else if (!afterUnknownOption) + { + return false; + } + } + return true; + } + /// /// Determines if the root command (proxy itself) is being invoked. /// Returns true when no subcommand is specified (only options or no args). diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index 2672fb65..bbe41cb3 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -569,11 +569,11 @@ static async Task RunProxyAsync(string[] args, DevProxyConfigOptions option } // Recover from a system-proxy registration left behind by a previous instance -// that was killed or crashed. Detached daemons skip this because the parent -// process that spawned them already did it. -if (DevProxyCommand.IsRootCommand && - !DevProxyCommand.IsInternalDaemon && - !args.Any(a => a is "-h" or "-?" or "--help" or "--version")) +// that was killed or crashed. Only when starting the proxy, so other commands +// don't change the OS proxy settings. Detached daemons skip this because the +// parent process that spawned them already did it. +if (!DevProxyCommand.IsInternalDaemon && + DevProxyCommand.IsStartInvocation(args)) { await ReconcileOrphanedSystemProxiesAsync(IsJsonOutputRequested(args)); } diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 67665279..66490a89 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -458,22 +458,25 @@ internal readonly record struct OrphanReconciliation( OrphanRestoreOutcome Outcome); /// - /// Finds the PID of a live process that owns the system proxy: a running detached - /// instance, or the (foreground or detached) instance recorded in the snapshot file. + /// Finds the PID of a live process that owns the system proxy. The (foreground or + /// detached) instance recorded in the snapshot file is authoritative, because the + /// latest instance to take over the system proxy rewrites it. Without a snapshot, + /// falls back to a running detached instance registered as the system proxy. /// Returns null when no live process owns it. /// - internal static async Task FindLiveSystemProxyOwnerAsync(CancellationToken cancellationToken = default) + internal static Task FindLiveSystemProxyOwnerAsync(CancellationToken cancellationToken = default) => + FindLiveSystemProxyOwnerAsync(SystemProxySnapshotStore.DefaultPath, cancellationToken); + + internal static async Task FindLiveSystemProxyOwnerAsync(string snapshotPath, CancellationToken cancellationToken = default) { - var liveInstance = await StateManager.FindSystemProxyInstanceAsync(cancellationToken); - if (liveInstance is not null) + var snapshot = SystemProxySnapshotStore.Load(snapshotPath); + if (snapshot is not null) { - return liveInstance.Pid; + return snapshot.IsOwnerAlive() ? snapshot.Pid : null; } - var snapshot = SystemProxySnapshotStore.Load(SystemProxySnapshotStore.DefaultPath); - return snapshot is not null && snapshot.IsOwnerAlive() - ? snapshot.Pid - : null; + var liveInstance = await StateManager.FindSystemProxyInstanceAsync(cancellationToken); + return liveInstance?.Pid; } /// From bf45876f4f55413cba6d3b102dc67a57920a3be7 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 16:25:27 +0100 Subject: [PATCH 11/22] Address review feedback on system proxy ownership and start detection - Retire superseded system-proxy ownership records (identity-checked) on takeover and after a successful restore, so stopping or recovering a superseded instance can't undo restored settings - Detect --output json with the config-options parser so attached values and response files are recognized - Register built-in subcommands in the early start-detection parser so multi-value and plugin options can't consume subcommand names Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/DevProxyCommandTests.cs | 5 ++ DevProxy.Tests/SystemProxyManagerTests.cs | 38 +++++++++++++++ DevProxy/Commands/DevProxyCommand.cs | 21 +++++++- DevProxy/Commands/SystemProxyCommand.cs | 19 ++------ DevProxy/Program.cs | 14 ++---- DevProxy/Proxy/SystemProxyManager.cs | 59 +++++++++++++++++++++++ DevProxy/State/StateManager.cs | 22 +++++++++ 7 files changed, 151 insertions(+), 27 deletions(-) diff --git a/DevProxy.Tests/DevProxyCommandTests.cs b/DevProxy.Tests/DevProxyCommandTests.cs index 9a6ed3a8..baa3c150 100644 --- a/DevProxy.Tests/DevProxyCommandTests.cs +++ b/DevProxy.Tests/DevProxyCommandTests.cs @@ -67,6 +67,11 @@ public class DevProxyCommandStartInvocationTests [InlineData(false, "--config-file", "devproxyrc.json", "--output", "json", "status")] [InlineData(false, "--log-level=debug", "system-proxy", "reset")] [InlineData(false, "--record", "stop")] + [InlineData(false, "--urls-to-watch", "https://example.com/*", "status")] + [InlineData(false, "--env", "FOO=bar", "status")] + [InlineData(false, "--watch-pids", "1", "stop")] + [InlineData(false, "--no-mocks", "status")] + [InlineData(false, "--mocks-file", "mocks.json", "status")] [InlineData(false, "mocks", "from-http-responses")] [InlineData(false, "--help")] [InlineData(false, "--port", "0", "-h")] diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index fc91b9a8..daa8ae36 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Text.Json; using DevProxy.Proxy; using DevProxy.State; using Microsoft.Extensions.Logging.Abstractions; @@ -290,6 +291,43 @@ public void IsResetInvocation_ReturnsFalse(params string[] args) => Assert.False(DevProxy.Commands.SystemProxyCommand.IsResetInvocation(args)); } +[Collection("management-environment")] +public class SystemProxyTakeoverTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task SaveSnapshot_Takeover_RetiresPreviousOwnerRecord(bool reusedPid) + { + var folder = Directory.CreateTempSubdirectory("devproxy-takeover-"); + var pid = Random.Shared.Next(int.MaxValue / 2, int.MaxValue); + var statePath = StateManager.GetInstanceStateFilePath(pid); + Assert.False(File.Exists(statePath)); + try + { + var snapshotPath = Path.Combine(folder.FullName, "snapshot.json"); + SystemProxySnapshotStore.Save(snapshotPath, new() { Pid = pid, ProcessStartTime = DateTimeOffset.UnixEpoch }); + // With a reused PID, the record belongs to a different process than the snapshot owner. + await StateManager.SaveStateAsync(new() + { + Pid = pid, + ProcessStartTime = reusedPid ? DateTimeOffset.UnixEpoch.AddDays(1) : DateTimeOffset.UnixEpoch, + AsSystemProxy = true, + }); + + new SystemProxyManager(NullLogger.Instance, snapshotPath).SaveSnapshot(_ => { }); + + var state = JsonSerializer.Deserialize(await File.ReadAllTextAsync(statePath)); + Assert.Equal(reusedPid, state!.AsSystemProxy); + } + finally + { + File.Delete(statePath); + folder.Delete(recursive: true); + } + } +} + [Collection("management-environment")] public class SystemProxyOwnerLookupTests { diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 517fad4e..d37fe721 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -207,6 +207,13 @@ public static bool IsDetachedMode } } + // Names of the commands registered in ConfigureCommand. Keep in sync. + internal static readonly string[] BuiltInCommandNames = + [ + "api", "cert", "config", "jwt", "logs", "msgraphdb", "outdated", + "plugin", "status", "stdio", "stop", "system-proxy" + ]; + /// /// Returns whether the arguments (without the executable) start the proxy, rather than /// invoking a subcommand, showing help or the version, or failing to parse. Parses the @@ -256,10 +263,19 @@ internal static bool IsStartInvocation(string[] args) { rootCommand.Options.Add(option); } + // Registering the subcommands stops multi-value options and plugin options from + // consuming their names, e.g. 'devproxy --urls-to-watch https://example.com/* status'. + foreach (var commandName in BuiltInCommandNames) + { + rootCommand.Subcommands.Add(new Command(commandName) { TreatUnmatchedTokensAsErrors = false }); + } + // Without an action, a root command with subcommands requires one of them. + rootCommand.SetAction(_ => { }); var parseResult = rootCommand.Parse(args); - // Help, version and parse errors (such as a missing response file) have an action. - if (parseResult.Action is not null) + // Subcommands, help, version and parse errors (such as a missing response file) + // resolve to a different action. + if (parseResult.Action != rootCommand.Action) { return false; } @@ -822,6 +838,7 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions) .Select(g => g.First())); this.AddOptions(options.OrderByName()); + // Keep BuiltInCommandNames in sync with these commands. var commands = new List { ActivatorUtilities.CreateInstance(_serviceProvider), diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index e3ae9600..82fab985 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -143,6 +143,9 @@ private static async Task ResetCoreAsync(bool force, OutputFormat outputFor return 1; } + // Restore also records that live detached instances no longer own the system proxy + // and removes records of dead ones, so stopping them or recovering after they crash + // doesn't change the restored settings again. var result = new SystemProxyManager(systemProxyLogger).Restore(); if (result is SystemProxyRestoreResult.Failed) { @@ -150,22 +153,6 @@ private static async Task ResetCoreAsync(bool force, OutputFormat outputFor return 1; } - // A forced reset took the system proxy away from live detached instances. Record - // that, so stopping them or recovering after they crash doesn't change the - // restored settings again. - foreach (var state in (await StateManager.LoadAllStatesAsync(cancellationToken)).Where(s => s.AsSystemProxy)) - { - state.AsSystemProxy = false; - await StateManager.SaveStateAsync(state, cancellationToken); - } - - // The settings are restored, so records of dead instances that registered as the - // system proxy are stale. Remove them so they don't trigger another restore later. - foreach (var orphan in await StateManager.GetOrphanedSystemProxyStatesAsync(cancellationToken)) - { - await StateManager.DeleteStateAsync(orphan, cancellationToken); - } - LogResult(result is SystemProxyRestoreResult.RestoredPrevious ? "Restored the system proxy settings from before Dev Proxy started." : "Turned off the system proxy.", outputFormat, logger); diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index bbe41cb3..d2c2a35d 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -422,15 +422,11 @@ static bool IsJsonObject(string line) static bool IsJsonOutputRequested(string[] args) { - for (var i = 0; i < args.Length; i++) - { - if (string.Equals(args[i], DevProxyCommand.OutputOptionName, StringComparison.OrdinalIgnoreCase) && - i + 1 < args.Length) - { - return string.Equals(args[i + 1], "json", StringComparison.OrdinalIgnoreCase); - } - } - return false; + // Use the configuration-options parser so attached values (--output=json) and + // response files are recognized like they are by the full command. + var options = new DevProxyConfigOptions(); + options.ParseOptions(args); + return options.Output == DevProxy.Abstractions.Proxy.OutputFormat.Json; } static string EscapeArgument(string arg) diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 66490a89..1d66e041 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -167,6 +167,7 @@ internal SystemProxyRestoreResult Restore() { SystemProxySnapshotStore.Delete(_snapshotPath); } + RetireSystemProxyRegistrations(); return restoredPrevious ? SystemProxyRestoreResult.RestoredPrevious : SystemProxyRestoreResult.Disabled; @@ -174,6 +175,7 @@ internal SystemProxyRestoreResult Restore() internal void SaveSnapshot(Action capture) { + ProxyInstanceState? previousOwner = null; try { // Keep an existing snapshot: it holds the settings from before Dev Proxy first @@ -184,6 +186,10 @@ internal void SaveSnapshot(Action capture) snapshot = new() { CreatedAt = DateTimeOffset.UtcNow }; capture(snapshot); } + else if (snapshot.Pid != Environment.ProcessId) + { + previousOwner = new() { Pid = snapshot.Pid, ProcessStartTime = snapshot.ProcessStartTime }; + } snapshot.Pid = Environment.ProcessId; snapshot.ProcessStartTime = StateManager.GetCurrentProcessStartTime(); SystemProxySnapshotStore.Save(_snapshotPath, snapshot); @@ -192,9 +198,62 @@ internal void SaveSnapshot(Action capture) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException or InvalidOperationException or System.ComponentModel.Win32Exception) { _logger.LogWarning(ex, "Couldn't save the current system proxy settings. They can't be restored when Dev Proxy stops."); + return; + } + + if (previousOwner is not null) + { + // The previous owner no longer owns the system proxy. Record that, so stopping + // it or recovering after it crashes doesn't undo the settings this instance + // restores when it stops. + try + { + RunSynchronously(StateManager.ClearSystemProxyFlagAsync(previousOwner)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + _logger.LogWarning(ex, "Couldn't record that Dev Proxy (PID: {Pid}) no longer owns the system proxy.", previousOwner.Pid); + } } } + /// + /// Records that no instance owns the system proxy anymore after its settings were + /// restored: live instances that registered as the system proxy are marked as no + /// longer owning it, and records of dead ones are removed. Otherwise, stopping or + /// recovering after any of them would change the restored settings again. + /// + private void RetireSystemProxyRegistrations() + { + try + { + RunSynchronously(RetireSystemProxyRegistrationsAsync()); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + _logger.LogWarning(ex, "Couldn't update the records of Dev Proxy instances registered as the system proxy."); + } + } + + private static async Task RetireSystemProxyRegistrationsAsync() + { + foreach (var state in (await StateManager.LoadAllStatesAsync()).Where(s => s.AsSystemProxy)) + { + await StateManager.ClearSystemProxyFlagAsync(state); + } + + foreach (var orphan in await StateManager.GetOrphanedSystemProxyStatesAsync()) + { + await StateManager.DeleteStateAsync(orphan); + } + } + + // Called from the synchronous ISystemProxyManager members; the host has no + // synchronization context, so blocking here can't deadlock. +#pragma warning disable VSTHRD002 + private static void RunSynchronously(Task task) => task.GetAwaiter().GetResult(); +#pragma warning restore VSTHRD002 + [SupportedOSPlatform("windows")] private static void CaptureWindows(SystemProxySnapshot snapshot) { diff --git a/DevProxy/State/StateManager.cs b/DevProxy/State/StateManager.cs index e39f9ebb..b7397fed 100644 --- a/DevProxy/State/StateManager.cs +++ b/DevProxy/State/StateManager.cs @@ -326,6 +326,28 @@ public static async Task DeleteStateAsync(ProxyInstanceState state, Cancellation DeleteTokenIfProcessGone(state.Pid); } + /// + /// Records that the given instance no longer owns the system proxy, so stopping it or + /// recovering after it crashes doesn't change the OS proxy settings. The on-disk record + /// is re-read and only updated if it still describes the same instance, so a newer + /// instance that reused the PID keeps its own record. + /// + public static async Task ClearSystemProxyFlagAsync(ProxyInstanceState expected, CancellationToken cancellationToken = default) + { + foreach (var filePath in new[] { GetInstanceStateFilePath(expected.Pid), GetStateFilePath() }) + { + var current = await ReadStateFromFileAsync(filePath, cancellationToken); + if (current is { AsSystemProxy: true } && + current.Pid == expected.Pid && + current.ProcessStartTime == expected.ProcessStartTime) + { + current.AsSystemProxy = false; + var json = JsonSerializer.Serialize(current, _jsonOptions); + await PrivateFiles.WriteAllTextAsync(filePath, json, cancellationToken); + } + } + } + /// /// Deletes the state file for the current process. /// From 3a8e891c8fe82b6d435772462ee89e47de12e976 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 08:24:15 +0100 Subject: [PATCH 12/22] Run startup system-proxy recovery only after the start command is parsed Move orphaned system-proxy recovery into the root command action so it runs only once the full command line, including plugin-provided commands, resolves to starting the proxy. Plugin commands such as 'devproxy --no-mocks mocks from-http-responses ...' no longer change OS proxy settings. Remove the pre-parse IsStartInvocation heuristic. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/DevProxyCommandTests.cs | 46 -------- DevProxy/Commands/DevProxyCommand.cs | 143 +++++++------------------ DevProxy/Program.cs | 10 -- 3 files changed, 37 insertions(+), 162 deletions(-) diff --git a/DevProxy.Tests/DevProxyCommandTests.cs b/DevProxy.Tests/DevProxyCommandTests.cs index 13565dcc..f1f79b8d 100644 --- a/DevProxy.Tests/DevProxyCommandTests.cs +++ b/DevProxy.Tests/DevProxyCommandTests.cs @@ -66,49 +66,3 @@ public void ApplyDiscoverOption_False_KeepsRecordingEnabledFromOtherSources() public void IsStdioSubcommand_DetectsSubcommandNotArgumentValues(bool expected, params string[] args) => Assert.Equal(expected, DevProxyCommand.IsStdioSubcommand(args)); } - -public class DevProxyCommandStartInvocationTests -{ - [Theory] - [InlineData(true)] - [InlineData(true, "--port", "0", "--as-system-proxy", "false")] - [InlineData(true, "--output", "json", "--log-level", "debug")] - [InlineData(true, "--output=json", "-u", "https://a.example/*", "https://b.example/*")] - [InlineData(true, "--mocks-file", "mocks.json", "--no-mocks")] - [InlineData(true, "--record", "--watch-pids", "1", "2")] - [InlineData(false, "status")] - [InlineData(false, "--output", "json", "status", "--pid", "1")] - [InlineData(false, "--config-file", "devproxyrc.json", "--output", "json", "status")] - [InlineData(false, "--log-level=debug", "system-proxy", "reset")] - [InlineData(false, "--record", "stop")] - [InlineData(false, "--urls-to-watch", "https://example.com/*", "status")] - [InlineData(false, "--env", "FOO=bar", "status")] - [InlineData(false, "--watch-pids", "1", "stop")] - [InlineData(false, "--no-mocks", "status")] - [InlineData(false, "--mocks-file", "mocks.json", "status")] - [InlineData(false, "mocks", "from-http-responses")] - [InlineData(false, "--help")] - [InlineData(false, "--port", "0", "-h")] - [InlineData(false, "--version")] - [InlineData(false, "@missing-response-file.rsp")] - public void IsStartInvocation_UsesParsedCommand(bool expected, params string[] args) => - Assert.Equal(expected, DevProxyCommand.IsStartInvocation(args)); - - [Theory] - [InlineData(true, "--port 0\n--output json")] - [InlineData(false, "--output json\nstatus")] - [InlineData(false, "--port 0\n--help")] - public void IsStartInvocation_ExpandsResponseFiles(bool expected, string contents) - { - var path = Path.GetTempFileName(); - try - { - File.WriteAllText(path, contents); - Assert.Equal(expected, DevProxyCommand.IsStartInvocation([$"@{path}"])); - } - finally - { - File.Delete(path); - } - } -} diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 6947846f..41be365c 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -251,111 +251,6 @@ public static bool IsDetachedMode } } - // Names of the commands registered in ConfigureCommand. Keep in sync. - internal static readonly string[] BuiltInCommandNames = - [ - "api", "cert", "config", "jwt", "logs", "msgraphdb", "outdated", - "plugin", "status", "stdio", "stop", "system-proxy" - ]; - - /// - /// Returns whether the arguments (without the executable) start the proxy, rather than - /// invoking a subcommand, showing help or the version, or failing to parse. Parses the - /// arguments, including response files, wherever options appear and however their - /// values are attached. Runs before plugins load, so tokens that aren't a built-in - /// option or the value of an unknown (plugin) option are treated as a subcommand. - /// - internal static bool IsStartInvocation(string[] args) - { - // Mirrors the arity of the root options registered in ConfigureCommand. Values are - // parsed as strings so that invalid values don't affect where tokens are consumed. - static Option Value(string name, params string[] aliases) => new(name, aliases); - static Option Values(string name, params string[] aliases) => new(name, aliases) - { - AllowMultipleArgumentsPerToken = true, - Arity = ArgumentArity.ZeroOrMore - }; - static Option Flag(string name, params string[] aliases) => new(name, aliases); - - var rootCommand = new RootCommand { TreatUnmatchedTokensAsErrors = false }; - Option[] options = - [ - Value(ApiPortOptionName), - Value(ApiIpAddressOptionName), - Flag(AsSystemProxyOptionName), - Value(ConfigFileOptionName, "-c"), - Flag(DetachedOptionName, "-d"), - Flag(DiscoverOptionName), - Values(EnvOptionName, "-e"), - Flag(InstallCertOptionName), - Flag(InternalDaemonOptionName), - Value(IpAddressOptionName), - Value(LogLevelOptionName), - new Option(NoColorOptionName) { Arity = ArgumentArity.Zero }, - Flag(NoFirstRunOptionName), - Flag(NoWatchOptionName), - Value(OutputOptionName), - Value(PortOptionName, "-p"), - Flag(RecordOptionName), - Value(TimeoutOptionName, "-t"), - Values(UrlsToWatchOptionName, "-u"), - Values(WatchPidsOptionName), - Values(WatchProcessNamesOptionName), - Flag(WatchProcessTreeOptionName), - ]; - foreach (var option in options) - { - rootCommand.Options.Add(option); - } - // Registering the subcommands stops multi-value options and plugin options from - // consuming their names, e.g. 'devproxy --urls-to-watch https://example.com/* status'. - foreach (var commandName in BuiltInCommandNames) - { - rootCommand.Subcommands.Add(new Command(commandName) { TreatUnmatchedTokensAsErrors = false }); - } - // Without an action, a root command with subcommands requires one of them. - rootCommand.SetAction(_ => { }); - - var parseResult = rootCommand.Parse(args); - // Subcommands, help, version and parse errors (such as a missing response file) - // resolve to a different action. - if (parseResult.Action != rootCommand.Action) - { - return false; - } - - var knownTokens = new HashSet(ReferenceEqualityComparer.Instance); - foreach (var option in rootCommand.Options) - { - if (parseResult.GetResult(option) is OptionResult { Implicit: false } optionResult) - { - if (optionResult.IdentifierToken is not null) - { - _ = knownTokens.Add(optionResult.IdentifierToken); - } - knownTokens.UnionWith(optionResult.Tokens); - } - } - - var afterUnknownOption = false; - foreach (var token in parseResult.Tokens) - { - if (knownTokens.Contains(token)) - { - afterUnknownOption = false; - } - else if (token.Value.StartsWith('-')) - { - afterUnknownOption = true; - } - else if (!afterUnknownOption) - { - return false; - } - } - return true; - } - /// /// Determines if the root command (proxy itself) is being invoked. /// Returns true when no subcommand is specified (only options or no args). @@ -557,6 +452,17 @@ private async Task InvokeAsync(ParseResult parseResult, CancellationToken c { throw new InvalidOperationException("WebApplication instance is not set. Please provide it when invoking the command."); } + + // Recover from a system-proxy registration left behind by a previous instance + // that crashed. This runs only once the command line resolved to starting the + // proxy, so other commands, including plugin commands, don't change the OS proxy + // settings. It must run before anything that loads instance state, which prunes + // the stale records it depends on. Detached daemons skip it because the parent + // process that spawned them already did it. + if (!IsInternalDaemon) + { + await ReconcileOrphanedSystemProxiesAsync(cancellationToken); + } // Environment overrides from config and --env are applied by now, so this // validates and pins the effective token before anything reads it. if (!ApiSecurity.TryInitializeToken(out var tokenError)) @@ -959,7 +865,6 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions) .Select(g => g.First())); this.AddOptions(options.OrderByName()); - // Keep BuiltInCommandNames in sync with these commands. var commands = new List { ActivatorUtilities.CreateInstance(_serviceProvider), @@ -1011,6 +916,32 @@ private void CustomizeHelp() } } + private async Task ReconcileOrphanedSystemProxiesAsync(CancellationToken cancellationToken) + { + var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(cancellationToken: cancellationToken); + if (reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Failed) + { + _logger.LogError( + "Couldn't restore the system proxy left by a crashed Dev Proxy instance (PID: {Pids}). Run 'devproxy system-proxy reset' or see https://go.devproxy.net?go=proxy-reset.", + string.Join(", ", reconciliation.OrphanedPids)); + return; + } + + foreach (var pid in reconciliation.OrphanedPids) + { + if (reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Restored) + { + _logger.LogInformation("Recovered system proxy left by a crashed Dev Proxy instance (PID: {Pid}).", pid); + } + else + { + _logger.LogInformation( + "Removed stale system-proxy registration left by a crashed Dev Proxy instance (PID: {Pid}) while keeping the current system proxy owner unchanged.", + pid); + } + } + } + internal static void ApplyDiscoverOption(IProxyConfiguration proxyConfiguration, bool? isDiscover) { // Discovery mode requires recording, but --discover false must not enable it diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index 11dfd7be..fd7e636e 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -563,16 +563,6 @@ static async Task RunProxyAsync(string[] args, DevProxyConfigOptions option return; } -// Recover from a system-proxy registration left behind by a previous instance -// that was killed or crashed. Only when starting the proxy, so other commands -// don't change the OS proxy settings. Detached daemons skip this because the -// parent process that spawned them already did it. -if (!DevProxyCommand.IsInternalDaemon && - DevProxyCommand.IsStartInvocation(args)) -{ - await ReconcileOrphanedSystemProxiesAsync(IsJsonOutputRequested(args)); -} - var options = new DevProxyConfigOptions(); options.ParseOptions(args); From 358641ec9ca0c0970405dbda16994c01ecdc2eb3 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 10:03:20 +0100 Subject: [PATCH 13/22] Restrict macOS restore to recorded services, keep snapshot until ownership is retired, accept -c in system-proxy reset - With a macOS snapshot, restore only the recorded network services (turning off endpoints without a previous server) instead of disabling the proxy on every current service; use toggle-proxy.sh off only when no snapshot exists. - Retire system-proxy ownership records before deleting the snapshot and report failure (keeping the snapshot) when that fails, so a live instance can't later undo the restored settings. - Accept and ignore --config-file/-c in the standalone 'system-proxy reset' parser so invocations that pass a config file still recover network access. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 14 ++++++++-- DevProxy/Commands/SystemProxyCommand.cs | 5 +++- DevProxy/Proxy/SystemProxyManager.cs | 31 +++++++++++++++-------- DevProxy/Proxy/SystemProxySnapshot.cs | 4 +-- 4 files changed, 38 insertions(+), 16 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index daa8ae36..88ddd7fe 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -172,7 +172,7 @@ public void GetRestoreCommands_RestoresServerAndTurnsDisabledEndpointsOff() } [Fact] - public void GetRestoreCommands_NoPreviousServer_ReturnsNoCommands() + public void GetRestoreCommands_NoPreviousServer_TurnsEndpointsOff() { var settings = new MacOSServiceProxySettings { @@ -181,7 +181,11 @@ public void GetRestoreCommands_NoPreviousServer_ReturnsNoCommands() SecureWeb = null, }; - Assert.Empty(MacOSNetworkSetup.GetRestoreCommands(settings)); + var commands = MacOSNetworkSetup.GetRestoreCommands(settings); + + Assert.Equal(2, commands.Count); + Assert.Equal(["-setwebproxystate", "Wi-Fi", "off"], commands[0]); + Assert.Equal(["-setsecurewebproxystate", "Wi-Fi", "off"], commands[1]); } } @@ -281,6 +285,12 @@ public async Task RunResetStandalone_InvalidArguments_ReturnsUsageError(params s public void IsResetInvocation_ReturnsTrue(params string[] args) => Assert.True(DevProxy.Commands.SystemProxyCommand.IsResetInvocation(args)); + [Theory] + [InlineData("-c", "missing/devproxyrc.json", "system-proxy", "reset")] + [InlineData("--config-file", "missing/devproxyrc.json", "--output", "json", "system-proxy", "reset")] + public void StandaloneResetParser_AcceptsConfigFileWithoutValidatingIt(params string[] args) => + Assert.Empty(DevProxy.Commands.SystemProxyCommand.CreateStandaloneResetParser().RootCommand.Parse(args).Errors); + [Theory] [InlineData("system-proxy")] [InlineData("reset")] diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index 82fab985..d8dd7e6c 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -51,11 +51,14 @@ private Task ResetAsync(ParseResult parseResult, CancellationToken cancella /// Builds a minimal command tree mirroring the registered system-proxy reset /// command and the global options, so the standalone path parses arguments the same way. /// - private static (RootCommand RootCommand, Option ForceOption) CreateStandaloneResetParser() + internal static (RootCommand RootCommand, Option ForceOption) CreateStandaloneResetParser() { var forceOption = new Option("--force", "-f"); var resetCommand = new Command("reset") { forceOption }; var rootCommand = new RootCommand { new Command("system-proxy") { resetCommand } }; + // Accepted only so invocations (or shell aliases) that pass a config file keep working. + // Reset doesn't load or validate it. + rootCommand.Options.Add(new Option(DevProxyCommand.ConfigFileOptionName, "-c")); rootCommand.Options.Add(new Option(DevProxyCommand.OutputOptionName) { Recursive = true }); rootCommand.Options.Add(new Option(DevProxyCommand.LogLevelOptionName) { Recursive = true }); rootCommand.Options.Add(new Option(DevProxyCommand.NoColorOptionName) { Recursive = true, Arity = ArgumentArity.Zero }); diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 1d66e041..9206dd6e 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -41,7 +41,8 @@ internal enum SystemProxyRestoreResult /// Windows → registry ProxyServer Windows → registry ProxyServer/ProxyEnable /// + ProxyEnable = 1 (or ProxyEnable = 0) + WinINET refresh /// + WinINET refresh -/// macOS → toggle-proxy.sh on … macOS → toggle-proxy.sh off + networksetup +/// macOS → toggle-proxy.sh on … macOS → networksetup for the recorded services +/// (toggle-proxy.sh off without a snapshot) /// Linux → log warning Linux → no-op /// /// @@ -147,14 +148,13 @@ internal SystemProxyRestoreResult Restore() } else { - succeeded = RunToggleScript("off"); + // Only touch the services recorded in the snapshot: services added while Dev + // Proxy ran weren't changed by it, so turning their proxy off would lose their + // settings. Without a snapshot, turn the proxy off for every service. restoredPrevious = snapshot?.MacOS is not null; - // Restore even if turning off failed for some services, so the services that - // did turn off get their previous proxy back. Either failure keeps the snapshot. - if (restoredPrevious && !RestoreMacOS(snapshot!.MacOS!)) - { - succeeded = false; - } + succeeded = restoredPrevious + ? RestoreMacOS(snapshot!.MacOS!) + : RunToggleScript("off"); } if (!succeeded) @@ -163,11 +163,18 @@ internal SystemProxyRestoreResult Restore() return SystemProxyRestoreResult.Failed; } + // Retire the registrations before deleting the snapshot. If that fails, a live + // instance would still claim the system proxy and could undo the restored settings + // when it stops or after it crashes, so report failure and keep the snapshot for a retry. + if (!RetireSystemProxyRegistrations()) + { + return SystemProxyRestoreResult.Failed; + } + if (snapshot is not null) { SystemProxySnapshotStore.Delete(_snapshotPath); } - RetireSystemProxyRegistrations(); return restoredPrevious ? SystemProxyRestoreResult.RestoredPrevious : SystemProxyRestoreResult.Disabled; @@ -223,15 +230,17 @@ internal void SaveSnapshot(Action capture) /// longer owning it, and records of dead ones are removed. Otherwise, stopping or /// recovering after any of them would change the restored settings again. /// - private void RetireSystemProxyRegistrations() + private bool RetireSystemProxyRegistrations() { try { RunSynchronously(RetireSystemProxyRegistrationsAsync()); + return true; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - _logger.LogWarning(ex, "Couldn't update the records of Dev Proxy instances registered as the system proxy."); + _logger.LogError(ex, "Couldn't update the records of Dev Proxy instances registered as the system proxy."); + return false; } } diff --git a/DevProxy/Proxy/SystemProxySnapshot.cs b/DevProxy/Proxy/SystemProxySnapshot.cs index fc644f1b..557d25e8 100644 --- a/DevProxy/Proxy/SystemProxySnapshot.cs +++ b/DevProxy/Proxy/SystemProxySnapshot.cs @@ -180,8 +180,7 @@ public static MacOSProxyEndpoint ParseProxyEndpoint(string output) /// /// Builds the networksetup argument lists that put back a service's previous - /// proxy server and state. Assumes the proxy has already been turned off for every - /// service, so endpoints without a previous server need no commands. + /// proxy server and state. Endpoints without a previous server are turned off. /// public static List GetRestoreCommands(MacOSServiceProxySettings settings) { @@ -200,6 +199,7 @@ private static void AddEndpointCommands( { if (endpoint is null || string.IsNullOrEmpty(endpoint.Server) || endpoint.Port <= 0) { + commands.Add([setStateCommand, service, "off"]); return; } From 191f0d29ca96001750bd0f0a69f5c0d7f7cd919c Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 10:11:13 +0100 Subject: [PATCH 14/22] Warn when restoring an authenticated macOS proxy networksetup turns proxy authentication off when it sets a server without credentials, and the password stays in the keychain, so it can't be turned back on. Record whether each endpoint required authentication and, after restoring it, warn the user to turn authentication back on in System Settings. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 27 +++++++++++++++++++ DevProxy/Proxy/SystemProxyManager.cs | 7 +++++ DevProxy/Proxy/SystemProxySnapshot.cs | 33 +++++++++++++++++++++++ 3 files changed, 67 insertions(+) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 88ddd7fe..0aae8b01 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -141,6 +141,33 @@ public void ParseProxyEndpoint_ReadsEnabledServerAndPort() Assert.True(endpoint.Enabled); Assert.Equal("proxy.contoso.com", endpoint.Server); Assert.Equal(3128, endpoint.Port); + Assert.False(endpoint.Authenticated); + } + + [Fact] + public void GetAuthenticatedEndpoints_ReturnsOnlyAuthenticatedEndpointsWithServer() + { + var authenticated = MacOSNetworkSetup.ParseProxyEndpoint( + "Enabled: Yes\nServer: proxy.contoso.com\nPort: 3128\nAuthenticated Proxy Enabled: 1\n"); + var services = new[] + { + new MacOSServiceProxySettings + { + Service = "Wi-Fi", + Web = authenticated, + SecureWeb = new() { Enabled = true, Server = "proxy.contoso.com", Port = 3128 }, + }, + new MacOSServiceProxySettings + { + Service = "Ethernet", + SecureWeb = new() { Authenticated = true, Server = string.Empty, Port = 0 }, + }, + }; + + var (service, _, endpoint) = Assert.Single(MacOSNetworkSetup.GetAuthenticatedEndpoints(services)); + + Assert.Equal("Wi-Fi", service); + Assert.Same(authenticated, endpoint); } [Fact] diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 9206dd6e..7a47475f 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -403,6 +403,13 @@ private bool RestoreMacOS(IEnumerable services) succeeded = false; } } + + foreach (var (service, proxy, endpoint) in MacOSNetworkSetup.GetAuthenticatedEndpoints(services)) + { + _logger.LogWarning( + "Restored the {Proxy} proxy {Server}:{Port} for {Service}, but its password can't be restored. Turn on 'Proxy server requires password' for {Service} in System Settings > Network > Details > Proxies and enter your credentials.", + proxy, endpoint.Server, endpoint.Port, service, service); + } return succeeded; } diff --git a/DevProxy/Proxy/SystemProxySnapshot.cs b/DevProxy/Proxy/SystemProxySnapshot.cs index 557d25e8..a384d52f 100644 --- a/DevProxy/Proxy/SystemProxySnapshot.cs +++ b/DevProxy/Proxy/SystemProxySnapshot.cs @@ -71,6 +71,10 @@ internal sealed class MacOSProxyEndpoint [JsonPropertyName("port")] public int Port { get; set; } + + /// Whether the proxy required authentication. Credentials stay in the keychain and aren't captured. + [JsonPropertyName("authenticated")] + public bool Authenticated { get; set; } } /// @@ -171,6 +175,9 @@ public static MacOSProxyEndpoint ParseProxyEndpoint(string output) case "Port": endpoint.Port = int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var port) ? port : 0; break; + case "Authenticated Proxy Enabled": + endpoint.Authenticated = value == "1"; + break; default: break; } @@ -190,6 +197,32 @@ public static List GetRestoreCommands(MacOSServiceProxySettings settin return commands; } + /// + /// Returns the restored endpoints that required authentication. networksetup can + /// only turn authentication back on with the password, which stays in the keychain, so + /// restoring the server turns authentication off and the user has to turn it back on. + /// + public static List<(string Service, string Proxy, MacOSProxyEndpoint Endpoint)> GetAuthenticatedEndpoints( + IEnumerable services) + { + var endpoints = new List<(string, string, MacOSProxyEndpoint)>(); + foreach (var settings in services) + { + if (IsAuthenticated(settings.Web)) + { + endpoints.Add((settings.Service, "Web (HTTP)", settings.Web!)); + } + if (IsAuthenticated(settings.SecureWeb)) + { + endpoints.Add((settings.Service, "Secure web (HTTPS)", settings.SecureWeb!)); + } + } + return endpoints; + } + + private static bool IsAuthenticated(MacOSProxyEndpoint? endpoint) => + endpoint is { Authenticated: true, Port: > 0 } && !string.IsNullOrEmpty(endpoint.Server); + private static void AddEndpointCommands( List commands, string service, From 6c4f16b49192c950d91b5694ee32eb6d60d12e6a Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 10:33:21 +0100 Subject: [PATCH 15/22] Log system proxy recovery warnings in all reconciliation callers Reconciliation, stop --pid recovery and force stop now use a real logger instead of NullLogger, so warnings such as the authenticated macOS proxy notice reach the user. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/StopCommandTests.cs | 3 ++- DevProxy/Commands/DevProxyCommand.cs | 3 ++- DevProxy/Commands/StopCommand.cs | 16 ++++++----- DevProxy/Commands/SystemProxyCommand.cs | 35 +++++++++++++++---------- DevProxy/Program.cs | 8 +++++- DevProxy/Proxy/SystemProxyManager.cs | 4 +-- 6 files changed, 43 insertions(+), 26 deletions(-) diff --git a/DevProxy.Tests/StopCommandTests.cs b/DevProxy.Tests/StopCommandTests.cs index e3e53aad..557b0a8d 100644 --- a/DevProxy.Tests/StopCommandTests.cs +++ b/DevProxy.Tests/StopCommandTests.cs @@ -5,6 +5,7 @@ using DevProxy.Abstractions.Proxy; using DevProxy.Commands; using DevProxy.Logging; +using Microsoft.Extensions.Logging.Abstractions; using System.CommandLine; using System.Globalization; using System.Text.Json; @@ -24,7 +25,7 @@ public async Task Stop_JsonOutput_NoInstanceWithPid_EmitsStructuredResult() { var logger = new RecordingLogger(); - var exitCode = await CreateRootCommand(new StopCommand(logger)) + var exitCode = await CreateRootCommand(new StopCommand(logger, NullLogger.Instance)) .Parse(["stop", "--pid", UnusedPid.ToString(CultureInfo.InvariantCulture), "--output", "json"]) .InvokeAsync(); diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 41be365c..0455f277 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -918,7 +918,8 @@ private void CustomizeHelp() private async Task ReconcileOrphanedSystemProxiesAsync(CancellationToken cancellationToken) { - var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(cancellationToken: cancellationToken); + var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync( + _serviceProvider.GetRequiredService>(), cancellationToken); if (reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Failed) { _logger.LogError( diff --git a/DevProxy/Commands/StopCommand.cs b/DevProxy/Commands/StopCommand.cs index deb0d861..79be895b 100644 --- a/DevProxy/Commands/StopCommand.cs +++ b/DevProxy/Commands/StopCommand.cs @@ -17,6 +17,7 @@ namespace DevProxy.Commands; internal sealed class StopCommand : Command { private readonly ILogger _logger; + private readonly ILogger _systemProxyLogger; private readonly Option _forceOption = new("--force", "-f") { Description = "Force stop the proxy by killing the process" @@ -27,7 +28,7 @@ internal sealed class StopCommand : Command Description = "Stop a specific Dev Proxy instance by PID" }; - public StopCommand(ILogger logger) : base("stop", """ + public StopCommand(ILogger logger, ILogger systemProxyLogger) : base("stop", """ Stop running Dev Proxy instances. JSON output: one result event per outcome, with pid, status, message and, @@ -37,6 +38,7 @@ Stop running Dev Proxy instances. """) { _logger = logger; + _systemProxyLogger = systemProxyLogger; Add(_forceOption); Add(_pidOption); SetAction(RunAsync); @@ -57,7 +59,7 @@ private async Task RunAsync(ParseResult parseResult, CancellationToken canc // Reconcile any system-proxy registrations left behind by crashed // instances first — this must run before LoadAllStatesAsync, which prunes // (deletes) the stale state files it depends on. - var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(cancellationToken: cancellationToken); + var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(_systemProxyLogger, cancellationToken); var states = await StateManager.LoadAllStatesAsync(cancellationToken); if (states.Count == 0 && reconciliation.OrphanedPids.Count == 0) @@ -84,7 +86,7 @@ private async Task RunAsync(ParseResult parseResult, CancellationToken canc return exitCode; } - private static async Task StopByPidAsync(int pid, bool force, StopReporter reporter, CancellationToken cancellationToken) + private async Task StopByPidAsync(int pid, bool force, StopReporter reporter, CancellationToken cancellationToken) { // Recover an orphan before looking up live state so failed recovery keeps // its registration available for a later retry. @@ -96,7 +98,7 @@ private static async Task StopByPidAsync(int pid, bool force, StopReporter var liveOwner = await SystemProxyManager.FindLiveSystemProxyOwnerAsync(cancellationToken); if (liveOwner is null) { - if (new SystemProxyManager(NullLogger.Instance).Restore() is SystemProxyRestoreResult.Failed) + if (new SystemProxyManager(_systemProxyLogger).Restore() is SystemProxyRestoreResult.Failed) { // Keep the state record so a later stop or start retries. reporter.Report(pid, "failed", $"Couldn't restore the system proxy left by crashed Dev Proxy (PID: {pid}).", RestoreFailedHint); @@ -147,7 +149,7 @@ private static bool ReportReconciledOrphans(SystemProxyManager.OrphanReconciliat return true; } - private static async Task StopInstanceAsync(ProxyInstanceState state, bool force, StopReporter reporter, CancellationToken cancellationToken) + private async Task StopInstanceAsync(ProxyInstanceState state, bool force, StopReporter reporter, CancellationToken cancellationToken) { if (force) { @@ -202,7 +204,7 @@ private static async Task StopInstanceAsync(ProxyInstanceState state, bool } } - private static async Task ForceStopAsync(ProxyInstanceState state, StopReporter reporter, CancellationToken cancellationToken) + private async Task ForceStopAsync(ProxyInstanceState state, StopReporter reporter, CancellationToken cancellationToken) { var identity = GetProcessIdentity(state); if (identity == ProcessIdentity.Unverifiable) @@ -222,7 +224,7 @@ private static async Task ForceStopAsync(ProxyInstanceState state, StopRepo // alone when another live instance owns it. if (isAlive || await StateManager.FindSystemProxyInstanceAsync(cancellationToken) is null) { - new SystemProxyManager(NullLogger.Instance).Disable(); + new SystemProxyManager(_systemProxyLogger).Disable(); } } diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index d8dd7e6c..f754f096 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -93,7 +93,27 @@ internal static async Task RunResetStandaloneAsync(string[] args) var outputFormat = parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName) ?? OutputFormat.Text; var logLevel = parseResult.GetValueOrDefault(DevProxyCommand.LogLevelOptionName) ?? LogLevel.Information; - using var loggerFactory = LoggerFactory.Create(builder => + using var loggerFactory = CreateConsoleLoggerFactory(outputFormat, logLevel); + var logger = loggerFactory.CreateLogger(); + if (parseResult.Errors.Count > 0) + { + foreach (var error in parseResult.Errors) + { + logger.LogError("{Message}", error.Message); + } + return 2; + } + + return await ResetCoreAsync(parseResult.GetValue(forceOption), outputFormat, logger, + loggerFactory.CreateLogger(), CancellationToken.None); + } + + /// + /// Creates console logging for system-proxy work that runs without the application host, + /// formatted like the host's output (text or JSON lines). + /// + internal static ILoggerFactory CreateConsoleLoggerFactory(OutputFormat outputFormat, LogLevel logLevel) => + LoggerFactory.Create(builder => { _ = builder .SetMinimumLevel(logLevel) @@ -115,19 +135,6 @@ internal static async Task RunResetStandaloneAsync(string[] args) formatterOptions.ShowTimestamps = false; }); }); - var logger = loggerFactory.CreateLogger(); - if (parseResult.Errors.Count > 0) - { - foreach (var error in parseResult.Errors) - { - logger.LogError("{Message}", error.Message); - } - return 2; - } - - return await ResetCoreAsync(parseResult.GetValue(forceOption), outputFormat, logger, - loggerFactory.CreateLogger(), CancellationToken.None); - } private static async Task ResetCoreAsync(bool force, OutputFormat outputFormat, ILogger logger, ILogger systemProxyLogger, CancellationToken cancellationToken) diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index fd7e636e..67ef6614 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -54,7 +54,13 @@ static async Task ReconcileOrphanedSystemProxiesAsync(bool isJsonOutput) { - var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(); + // Log through the console like the host would, so warnings raised while restoring + // (for example, an authenticated proxy that needs its password re-entered) reach the user. + using var loggerFactory = SystemProxyCommand.CreateConsoleLoggerFactory( + isJsonOutput ? DevProxy.Abstractions.Proxy.OutputFormat.Json : DevProxy.Abstractions.Proxy.OutputFormat.Text, + LogLevel.Information); + var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync( + loggerFactory.CreateLogger()); if (reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Failed) { var error = $"Couldn't restore the system proxy left by a crashed Dev Proxy instance (PID: {string.Join(", ", reconciliation.OrphanedPids)}). Run 'devproxy system-proxy reset' or see https://go.devproxy.net?go=proxy-reset."; diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 7a47475f..8314abea 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -559,7 +559,7 @@ internal readonly record struct OrphanReconciliation( /// Restores the OS proxy (unless a live instance still owns it) and removes /// the stale state records. Safe to call when there are no orphans. /// - public static async Task ReconcileOrphanedSystemProxiesAsync(ILogger? logger = null, CancellationToken cancellationToken = default) + public static async Task ReconcileOrphanedSystemProxiesAsync(ILogger logger, CancellationToken cancellationToken = default) { var orphans = await StateManager.GetOrphanedSystemProxyStatesAsync(cancellationToken); var orphanedPids = orphans.Select(o => o.Pid).ToList(); @@ -582,7 +582,7 @@ public static async Task ReconcileOrphanedSystemProxiesAsy var outcome = OrphanRestoreOutcome.OwnedByLiveInstance; if (await FindLiveSystemProxyOwnerAsync(cancellationToken) is null) { - if (new SystemProxyManager(logger ?? NullLogger.Instance).Restore() is SystemProxyRestoreResult.Failed) + if (new SystemProxyManager(logger).Restore() is SystemProxyRestoreResult.Failed) { // Keep the state records (and the snapshot) so the next start or stop retries. return new(orphanedPids, OrphanRestoreOutcome.Failed); From be593245d7d2fb690e52832cffc26673c42c70b8 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 12:15:12 +0100 Subject: [PATCH 16/22] Report system proxy restore cleanup failures and capture new macOS services on takeover - stop --force no longer terminates an instance or deletes its record when restoring the system proxy fails - Restore reports failure when the snapshot or orphaned state records can't be removed - Taking over an existing snapshot records services added since it was captured Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 18 ++++++++-- DevProxy/Commands/StopCommand.cs | 10 +++++- DevProxy/Proxy/SystemProxyManager.cs | 40 ++++++++++++++++++++--- DevProxy/Proxy/SystemProxySnapshot.cs | 21 ++++++++++-- DevProxy/State/StateManager.cs | 25 ++++++++++++-- 5 files changed, 102 insertions(+), 12 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 0aae8b01..624a4f57 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -84,19 +84,31 @@ public void SaveSnapshot_Takeover_UpdatesIdentityAndPreservesPreviousSettings() Pid = int.MaxValue, ProcessStartTime = DateTimeOffset.UnixEpoch, Windows = new() { ProxyEnable = 1, ProxyServer = "corp:8080" }, + MacOS = [new() { Service = "Wi-Fi", Web = new() { Enabled = true, Server = "corp", Port = 8080 } }], }); var manager = new SystemProxyManager(NullLogger.Instance, path); - var captured = false; - manager.SaveSnapshot(_ => captured = true); + // The current settings already point at the previous owner, except for a service + // added after the snapshot was captured. + manager.SaveSnapshot(current => + { + current.Windows = new() { ProxyEnable = 1, ProxyServer = "127.0.0.1:8000" }; + current.MacOS = + [ + new() { Service = "Wi-Fi", Web = new() { Enabled = true, Server = "127.0.0.1", Port = 8000 } }, + new() { Service = "Ethernet", Web = new() { Enabled = true, Server = "lan-proxy", Port = 3128 } }, + ]; + }); var snapshot = SystemProxySnapshotStore.Load(path); Assert.NotNull(snapshot); - Assert.False(captured); Assert.Equal(Environment.ProcessId, snapshot.Pid); Assert.NotNull(snapshot.ProcessStartTime); Assert.True(snapshot.IsOwnerAlive()); Assert.Equal("corp:8080", snapshot.Windows?.ProxyServer); + Assert.Equal(["Wi-Fi", "Ethernet"], snapshot.MacOS!.Select(s => s.Service)); + Assert.Equal("corp", snapshot.MacOS![0].Web?.Server); + Assert.Equal("lan-proxy", snapshot.MacOS![1].Web?.Server); } finally { diff --git a/DevProxy/Commands/StopCommand.cs b/DevProxy/Commands/StopCommand.cs index 79be895b..ac505406 100644 --- a/DevProxy/Commands/StopCommand.cs +++ b/DevProxy/Commands/StopCommand.cs @@ -224,7 +224,15 @@ private async Task ForceStopAsync(ProxyInstanceState state, StopReporter re // alone when another live instance owns it. if (isAlive || await StateManager.FindSystemProxyInstanceAsync(cancellationToken) is null) { - new SystemProxyManager(_systemProxyLogger).Disable(); + if (new SystemProxyManager(_systemProxyLogger).Restore() is SystemProxyRestoreResult.Failed) + { + // Keep the process and its state record: without restored settings, they're + // what lets a later stop, start, or reset put the system proxy back. + reporter.Report(state.Pid, "failed", isAlive + ? $"Couldn't restore the system proxy, so Dev Proxy (PID: {state.Pid}) wasn't terminated." + : $"Couldn't restore the system proxy left by Dev Proxy (PID: {state.Pid}).", RestoreFailedHint); + return 1; + } } } diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 8314abea..97bc1d76 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -173,7 +173,17 @@ internal SystemProxyRestoreResult Restore() if (snapshot is not null) { - SystemProxySnapshotStore.Delete(_snapshotPath); + try + { + SystemProxySnapshotStore.Delete(_snapshotPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // The snapshot still names its owner, which would put these settings back + // when it stops, so don't report success. + _logger.LogError(ex, "Restored the system proxy settings, but couldn't remove {Path}. Remove the file, or run 'devproxy system-proxy reset' again to retry the cleanup.", _snapshotPath); + return SystemProxyRestoreResult.Failed; + } } return restoredPrevious ? SystemProxyRestoreResult.RestoredPrevious @@ -193,9 +203,13 @@ internal void SaveSnapshot(Action capture) snapshot = new() { CreatedAt = DateTimeOffset.UtcNow }; capture(snapshot); } - else if (snapshot.Pid != Environment.ProcessId) + else { - previousOwner = new() { Pid = snapshot.Pid, ProcessStartTime = snapshot.ProcessStartTime }; + if (snapshot.Pid != Environment.ProcessId) + { + previousOwner = new() { Pid = snapshot.Pid, ProcessStartTime = snapshot.ProcessStartTime }; + } + MergeNewSettings(snapshot, capture); } snapshot.Pid = Environment.ProcessId; snapshot.ProcessStartTime = StateManager.GetCurrentProcessStartTime(); @@ -224,6 +238,24 @@ internal void SaveSnapshot(Action capture) } } + // Registering configures every current service, including ones added after the + // snapshot was captured. Record their settings too, so restoring puts them back + // instead of leaving them pointing at this instance after it stops. + private void MergeNewSettings(SystemProxySnapshot snapshot, Action capture) + { + var current = new SystemProxySnapshot(); + try + { + capture(current); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException or InvalidOperationException or System.ComponentModel.Win32Exception) + { + _logger.LogWarning(ex, "Couldn't read the current system proxy settings. Settings of network services added since Dev Proxy first registered as the system proxy can't be restored when it stops."); + return; + } + SystemProxySnapshotStore.MergeNewServices(snapshot, current); + } + /// /// Records that no instance owns the system proxy anymore after its settings were /// restored: live instances that registered as the system proxy are marked as no @@ -253,7 +285,7 @@ private static async Task RetireSystemProxyRegistrationsAsync() foreach (var orphan in await StateManager.GetOrphanedSystemProxyStatesAsync()) { - await StateManager.DeleteStateAsync(orphan); + await StateManager.RetireOrphanedStateAsync(orphan); } } diff --git a/DevProxy/Proxy/SystemProxySnapshot.cs b/DevProxy/Proxy/SystemProxySnapshot.cs index a384d52f..d1039875 100644 --- a/DevProxy/Proxy/SystemProxySnapshot.cs +++ b/DevProxy/Proxy/SystemProxySnapshot.cs @@ -115,15 +115,32 @@ public static void Save(string path, SystemProxySnapshot snapshot) #pragma warning restore VSTHRD002 } + /// + /// Deletes the snapshot file. Throws when the file exists but can't be deleted, so the + /// caller doesn't report the settings as restored while the snapshot still names an owner. + /// public static void Delete(string path) { - try + if (File.Exists(path)) { File.Delete(path); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + } + + /// + /// Adds the macOS services in that + /// doesn't record yet. Services added after the snapshot was captured still have their own + /// settings, which taking over the system proxy is about to overwrite. + /// + public static void MergeNewServices(SystemProxySnapshot snapshot, SystemProxySnapshot current) + { + if (snapshot.MacOS is null || current.MacOS is null) { + return; } + + var recorded = snapshot.MacOS.Select(s => s.Service).ToHashSet(StringComparer.Ordinal); + snapshot.MacOS.AddRange(current.MacOS.Where(s => !recorded.Contains(s.Service))); } } diff --git a/DevProxy/State/StateManager.cs b/DevProxy/State/StateManager.cs index b7397fed..7d8e4a73 100644 --- a/DevProxy/State/StateManager.cs +++ b/DevProxy/State/StateManager.cs @@ -326,6 +326,19 @@ public static async Task DeleteStateAsync(ProxyInstanceState state, Cancellation DeleteTokenIfProcessGone(state.Pid); } + /// + /// Removes the state record of a dead instance whose system-proxy registration was + /// reconciled. Like , + /// only removes records that still describe the same instance, but propagates failures: + /// a surviving record would make the next start restore the system proxy again. + /// + public static async Task RetireOrphanedStateAsync(ProxyInstanceState state, CancellationToken cancellationToken = default) + { + await DeleteStateFileIfMatchesAsync(GetInstanceStateFilePath(state.Pid), state, cancellationToken, throwOnFailure: true); + await DeleteStateFileIfMatchesAsync(GetStateFilePath(), state, cancellationToken, throwOnFailure: true); + DeleteTokenIfProcessGone(state.Pid); + } + /// /// Records that the given instance no longer owns the system proxy, so stopping it or /// recovering after it crashes doesn't change the OS proxy settings. The on-disk record @@ -535,14 +548,22 @@ internal static bool IsProcessRunning(int pid) private static async Task DeleteStateFileIfMatchesAsync( string filePath, ProxyInstanceState expected, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + bool throwOnFailure = false) { var current = await ReadStateFromFileAsync(filePath, cancellationToken); if (current is not null && current.Pid == expected.Pid && current.ProcessStartTime == expected.ProcessStartTime) { - DeleteFile(filePath); + if (throwOnFailure) + { + File.Delete(filePath); + } + else + { + DeleteFile(filePath); + } } } From 203d18506a7e9c19f1b92e7d439e72c8b0f58d81 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 13:15:20 +0100 Subject: [PATCH 17/22] Recover detached system proxy only for parsed starts; retire same-PID orphans A detached parent ran startup recovery before the command line was resolved, so detached plugin management commands (e.g. 'mocks from-http-responses') restored the system proxy and deleted the snapshot. The daemon now recovers in the root command's action, like a foreground start, and the parent echoes the outcome from the daemon's log. Orphaned system-proxy records are now deduplicated by PID and process start time, so a legacy and a per-PID record for different processes that shared a PID are both retired after a restore. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 34 ++++++++++ DevProxy/Commands/DevProxyCommand.cs | 19 +++--- DevProxy/Program.cs | 77 ++++++++++------------- DevProxy/Proxy/SystemProxyManager.cs | 2 +- DevProxy/State/StateManager.cs | 6 +- 5 files changed, 82 insertions(+), 56 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 624a4f57..4e006461 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -425,3 +425,37 @@ await StateManager.SaveStateAsync(new() } } } + +[Collection("management-environment")] +public class OrphanedSystemProxyStateTests +{ + [Fact] + public async Task GetOrphanedSystemProxyStates_SamePidDifferentProcesses_ReturnsBoth() + { + var legacyPath = StateManager.GetStateFilePath(); + if (File.Exists(legacyPath)) + { + // Don't touch a real legacy record. + return; + } + var pid = Random.Shared.Next(int.MaxValue / 2, int.MaxValue); + var statePath = StateManager.GetInstanceStateFilePath(pid); + Assert.False(File.Exists(statePath)); + try + { + // A legacy record and a per-PID record for different dead processes that shared a PID. + await StateManager.SaveStateAsync(new() { Pid = pid, ProcessStartTime = DateTimeOffset.UnixEpoch, AsSystemProxy = true }); + File.Copy(statePath, legacyPath); + await StateManager.SaveStateAsync(new() { Pid = pid, ProcessStartTime = DateTimeOffset.UnixEpoch.AddDays(1), AsSystemProxy = true }); + + var orphans = await StateManager.GetOrphanedSystemProxyStatesAsync(); + + Assert.Equal(2, orphans.Count(o => o.Pid == pid)); + } + finally + { + File.Delete(statePath); + File.Delete(legacyPath); + } + } +} diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 75621273..59ea20b9 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -500,12 +500,10 @@ private async Task InvokeAsync(ParseResult parseResult, CancellationToken c // that crashed. This runs only once the command line resolved to starting the // proxy, so other commands, including plugin commands, don't change the OS proxy // settings. It must run before anything that loads instance state, which prunes - // the stale records it depends on. Detached daemons skip it because the parent - // process that spawned them already did it. - if (!IsInternalDaemon) - { - await ReconcileOrphanedSystemProxiesAsync(cancellationToken); - } + // the stale records it depends on. Detached daemons run it too, because only the + // daemon knows whether the command line resolved to starting the proxy. The + // parent process that spawned them echoes the outcome from the daemon's log. + await ReconcileOrphanedSystemProxiesAsync(cancellationToken); // Environment overrides from config and --env are applied by now, so this // validates and pins the effective token before anything reads it. if (!ApiSecurity.TryInitializeToken(out var tokenError)) @@ -960,6 +958,9 @@ private void CustomizeHelp() } } + // Shared by every startup recovery message so a detached parent can find them in the daemon's log. + internal const string CrashedInstanceRecoveryMarker = "left by a crashed Dev Proxy instance"; + private async Task ReconcileOrphanedSystemProxiesAsync(CancellationToken cancellationToken) { var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync( @@ -967,7 +968,7 @@ private async Task ReconcileOrphanedSystemProxiesAsync(CancellationToken cancell if (reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Failed) { _logger.LogError( - "Couldn't restore the system proxy left by a crashed Dev Proxy instance (PID: {Pids}). Run 'devproxy system-proxy reset' or see https://go.devproxy.net?go=proxy-reset.", + "Couldn't restore the system proxy " + CrashedInstanceRecoveryMarker + " (PID: {Pids}). Run 'devproxy system-proxy reset' or see https://go.devproxy.net?go=proxy-reset.", string.Join(", ", reconciliation.OrphanedPids)); return; } @@ -976,12 +977,12 @@ private async Task ReconcileOrphanedSystemProxiesAsync(CancellationToken cancell { if (reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Restored) { - _logger.LogInformation("Recovered system proxy left by a crashed Dev Proxy instance (PID: {Pid}).", pid); + _logger.LogInformation("Recovered system proxy " + CrashedInstanceRecoveryMarker + " (PID: {Pid}).", pid); } else { _logger.LogInformation( - "Removed stale system-proxy registration left by a crashed Dev Proxy instance (PID: {Pid}) while keeping the current system proxy owner unchanged.", + "Removed stale system-proxy registration " + CrashedInstanceRecoveryMarker + " (PID: {Pid}) while keeping the current system proxy owner unchanged.", pid); } } diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index a48a80a3..3ac2e48c 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -52,54 +52,13 @@ Console.SetError(_detachedLogWriter); } -static async Task ReconcileOrphanedSystemProxiesAsync(bool isJsonOutput) -{ - // Log through the console like the host would, so warnings raised while restoring - // (for example, an authenticated proxy that needs its password re-entered) reach the user. - using var loggerFactory = SystemProxyCommand.CreateConsoleLoggerFactory( - isJsonOutput ? DevProxy.Abstractions.Proxy.OutputFormat.Json : DevProxy.Abstractions.Proxy.OutputFormat.Text, - LogLevel.Information); - var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync( - loggerFactory.CreateLogger()); - if (reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Failed) - { - var error = $"Couldn't restore the system proxy left by a crashed Dev Proxy instance (PID: {string.Join(", ", reconciliation.OrphanedPids)}). Run 'devproxy system-proxy reset' or see https://go.devproxy.net?go=proxy-reset."; - if (isJsonOutput) - { - await Console.Out.WriteLineAsync(FormatJsonLogEntry("error", error)); - } - else - { - await Console.Error.WriteLineAsync(error); - } - return; - } - - foreach (var pid in reconciliation.OrphanedPids) - { - var message = reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Restored - ? $"Recovered system proxy left by a crashed Dev Proxy instance (PID: {pid})." - : $"Removed stale system-proxy registration left by a crashed Dev Proxy instance (PID: {pid}) while keeping the current system proxy owner unchanged."; - if (isJsonOutput) - { - await Console.Out.WriteLineAsync(FormatJsonLogEntry("info", message)); - } - else - { - await Console.Out.WriteLineAsync(message); - } - } -} - static async Task StartDetachedProcessAsync(string[] args) { var isJsonOutput = IsJsonOutputRequested(args); - // Recover from a system-proxy registration left behind by a previous - // instance that crashed before restoring the OS proxy. This must run before - // any state-loading call below, which prunes (deletes) the stale state files - // it depends on without restoring the proxy. - await ReconcileOrphanedSystemProxiesAsync(isJsonOutput); + // Recovering a system proxy left by a crashed instance is up to the daemon: only it + // knows whether the command line resolves to starting the proxy rather than to a + // (plugin) management command. Don't prune state here, because the daemon needs it. // Check if an instance is already running as system proxy var systemProxyInstance = await StateManager.FindSystemProxyInstanceAsync(); @@ -212,6 +171,8 @@ await Console.Error.WriteLineAsync( var token = ApiSecurity.ShouldDisplayTokenFor(state) ? (await File.ReadAllTextAsync(ApiSecurity.GetTokenFilePath(state.Pid))).Trim() : null; + await EchoSystemProxyRecoveryAsync(process.Id, isJsonOutput); + if (isJsonOutput) { await Console.Out.WriteLineAsync(FormatJsonResultEntry(new @@ -415,6 +376,34 @@ static bool IsJsonObject(string line) } } +// The daemon recovers a system proxy left by a crashed instance before it starts +// listening, so its log has the outcome by now. Show it like a foreground start would. +static async Task EchoSystemProxyRecoveryAsync(int pid, bool isJsonOutput) +{ + var log = await ReadDaemonLogAsync(pid); + if (string.IsNullOrEmpty(log)) + { + return; + } + + foreach (var line in log.Split('\n')) + { + var trimmed = line.TrimEnd('\r'); + if (!trimmed.Contains(DevProxyCommand.CrashedInstanceRecoveryMarker, StringComparison.Ordinal)) + { + continue; + } + if (isJsonOutput || !trimmed.Contains("Couldn't restore", StringComparison.Ordinal)) + { + await Console.Out.WriteLineAsync(trimmed); + } + else + { + await Console.Error.WriteLineAsync(trimmed); + } + } +} + static async Task ReadDaemonLogAsync(int pid) { try diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 97bc1d76..dea131a6 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -594,7 +594,7 @@ internal readonly record struct OrphanReconciliation( public static async Task ReconcileOrphanedSystemProxiesAsync(ILogger logger, CancellationToken cancellationToken = default) { var orphans = await StateManager.GetOrphanedSystemProxyStatesAsync(cancellationToken); - var orphanedPids = orphans.Select(o => o.Pid).ToList(); + var orphanedPids = orphans.Select(o => o.Pid).Distinct().ToList(); // A snapshot left by a dead instance without a state record (e.g. a crashed // foreground instance) is also an orphan. diff --git a/DevProxy/State/StateManager.cs b/DevProxy/State/StateManager.cs index 7d8e4a73..7babdec4 100644 --- a/DevProxy/State/StateManager.cs +++ b/DevProxy/State/StateManager.cs @@ -253,7 +253,9 @@ public static async Task> GetOrphanedSystemProxyStatesA } var orphaned = new List(); - var seenPids = new HashSet(); + // Dedupe by identity, not PID: the per-PID and legacy records can describe different + // processes with the same PID, and each must be retired after the proxy is restored. + var seen = new HashSet<(int, DateTimeOffset?)>(); var stateFiles = Directory.GetFiles(configFolder, $"{StateFilePrefix}*{StateFileExtension}"); var legacyPath = GetStateFilePath(); @@ -265,7 +267,7 @@ public static async Task> GetOrphanedSystemProxyStatesA if (state is not null && state.AsSystemProxy && !IsInstanceAlive(state) && - seenPids.Add(state.Pid)) + seen.Add((state.Pid, state.ProcessStartTime))) { orphaned.Add(state); } From 9e918ee2ef468d246b6610f7304a34ead85e3059 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 13:25:56 +0100 Subject: [PATCH 18/22] Echo all system proxy recovery messages on detached start Announce startup recovery before its first message and have the detached parent forward every record between the first and last recovery message, so warnings like macOS proxy credentials that need re-entering reach the caller in text and JSON output. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy/Commands/DevProxyCommand.cs | 31 +++++++++++++++++++++- DevProxy/Program.cs | 39 ++++++++++++++++++++++------ 2 files changed, 61 insertions(+), 9 deletions(-) diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 7ebe8333..974ba08c 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -969,8 +969,14 @@ private void CustomizeHelp() private async Task ReconcileOrphanedSystemProxiesAsync(CancellationToken cancellationToken) { + // Announce the recovery before its first message, so the detached parent can echo + // everything it logs (e.g. proxy credentials that couldn't be restored) along with + // the summary. + var recoveryLogger = new FirstEntryAnnouncingLogger( + _serviceProvider.GetRequiredService>(), + () => _logger.LogInformation("Restoring the system proxy " + CrashedInstanceRecoveryMarker + "...")); var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync( - _serviceProvider.GetRequiredService>(), cancellationToken); + recoveryLogger, cancellationToken); if (reconciliation.Outcome is SystemProxyManager.OrphanRestoreOutcome.Failed) { _logger.LogError( @@ -994,6 +1000,29 @@ private async Task ReconcileOrphanedSystemProxiesAsync(CancellationToken cancell } } + private sealed class FirstEntryAnnouncingLogger(ILogger inner, Action announce) : ILogger + { + private bool _announced; + + public IDisposable? BeginScope(TState state) where TState : notnull => inner.BeginScope(state); + + public bool IsEnabled(LogLevel logLevel) => inner.IsEnabled(logLevel); + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (!inner.IsEnabled(logLevel)) + { + return; + } + if (!_announced) + { + _announced = true; + announce(); + } + inner.Log(logLevel, eventId, state, exception, formatter); + } + } + internal static void ApplyDiscoverOption(IProxyConfiguration proxyConfiguration, bool? isDiscover) { // Discovery mode requires recording, but --discover false must not enable it diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index 6d602720..b5f89b40 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -381,7 +381,9 @@ static bool IsJsonObject(string line) } // The daemon recovers a system proxy left by a crashed instance before it starts -// listening, so its log has the outcome by now. Show it like a foreground start would. +// listening, so its log has the outcome by now. Show it like a foreground start would: +// every record from the first to the last recovery message, so that warnings logged +// while restoring (like proxy credentials that need re-entering) aren't hidden. static async Task EchoSystemProxyRecoveryAsync(int pid, bool isJsonOutput) { var log = await ReadDaemonLogAsync(pid); @@ -390,22 +392,43 @@ static async Task EchoSystemProxyRecoveryAsync(int pid, bool isJsonOutput) return; } - foreach (var line in log.Split('\n')) + var lines = log.Split('\n').Select(l => l.TrimEnd('\r')).ToArray(); + var first = Array.FindIndex(lines, IsRecoveryLine); + if (first < 0) { - var trimmed = line.TrimEnd('\r'); - if (!trimmed.Contains(DevProxyCommand.CrashedInstanceRecoveryMarker, StringComparison.Ordinal)) + return; + } + var last = Array.FindLastIndex(lines, IsRecoveryLine); + + var toError = false; + foreach (var line in lines[first..(last + 1)]) + { + if (isJsonOutput) { + await Console.Out.WriteLineAsync(line); continue; } - if (isJsonOutput || !trimmed.Contains("Couldn't restore", StringComparison.Ordinal)) + + // Exception details continue a record on the following lines, so they go to + // the same stream as the record they belong to. + var trimmed = line.TrimStart(); + if (trimmed.StartsWith("info ", StringComparison.Ordinal) || + trimmed.StartsWith("warn ", StringComparison.Ordinal) || + trimmed.StartsWith("dbug ", StringComparison.Ordinal) || + trimmed.StartsWith("trce ", StringComparison.Ordinal)) { - await Console.Out.WriteLineAsync(trimmed); + toError = false; } - else + else if (trimmed.StartsWith("fail ", StringComparison.Ordinal) || + trimmed.StartsWith("crit ", StringComparison.Ordinal)) { - await Console.Error.WriteLineAsync(trimmed); + toError = true; } + await (toError ? Console.Error : Console.Out).WriteLineAsync(line); } + + static bool IsRecoveryLine(string line) => + line.Contains(DevProxyCommand.CrashedInstanceRecoveryMarker, StringComparison.Ordinal); } static async Task ReadDaemonLogAsync(int pid) From 92fbb8cad0b56d60c420670ffd1f0246df7781cd Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 14:08:06 +0100 Subject: [PATCH 19/22] Fix stop --pid PID sharing and JSON reset output at higher log levels - stop --pid: after removing a dead legacy state.json record, keep going and stop a live instance whose per-PID record has the same PID instead of returning success early. - system-proxy reset --output json: keep the logging pipeline at Information so the structured result survives --log-level Warning/None; the JSON formatter still filters diagnostics at the requested level. - Extract the detached-start recovery echo into SystemProxyRecoveryEcho and cover it with tests (text and JSON, incl. the macOS proxy authentication warning). Warnings now go to stderr, matching the foreground console logger. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/StopCommandTests.cs | 55 +++++++++++- DevProxy.Tests/SystemProxyCommandTests.cs | 41 +++++++++ .../SystemProxyRecoveryEchoTests.cs | 88 +++++++++++++++++++ DevProxy/Commands/StopCommand.cs | 12 ++- DevProxy/Commands/SystemProxyCommand.cs | 8 +- DevProxy/Logging/SystemProxyRecoveryEcho.cs | 61 +++++++++++++ DevProxy/Program.cs | 53 +---------- 7 files changed, 262 insertions(+), 56 deletions(-) create mode 100644 DevProxy.Tests/SystemProxyCommandTests.cs create mode 100644 DevProxy.Tests/SystemProxyRecoveryEchoTests.cs create mode 100644 DevProxy/Logging/SystemProxyRecoveryEcho.cs diff --git a/DevProxy.Tests/StopCommandTests.cs b/DevProxy.Tests/StopCommandTests.cs index 557b0a8d..73663df2 100644 --- a/DevProxy.Tests/StopCommandTests.cs +++ b/DevProxy.Tests/StopCommandTests.cs @@ -5,6 +5,8 @@ using DevProxy.Abstractions.Proxy; using DevProxy.Commands; using DevProxy.Logging; +using DevProxy.Proxy; +using DevProxy.State; using Microsoft.Extensions.Logging.Abstractions; using System.CommandLine; using System.Globalization; @@ -25,7 +27,7 @@ public async Task Stop_JsonOutput_NoInstanceWithPid_EmitsStructuredResult() { var logger = new RecordingLogger(); - var exitCode = await CreateRootCommand(new StopCommand(logger, NullLogger.Instance)) + var exitCode = await CreateRootCommand(new StopCommand(logger, NullLogger.Instance)) .Parse(["stop", "--pid", UnusedPid.ToString(CultureInfo.InvariantCulture), "--output", "json"]) .InvokeAsync(); @@ -44,3 +46,54 @@ internal static RootCommand CreateRootCommand(Command command) => command ]; } + +[Collection("management-environment")] +public class StopCommandPidReuseTests +{ + [Fact] + public async Task StopByPid_DeadLegacyRecordSharesPidWithLiveInstance_StopsLiveInstance() + { + var legacyPath = StateManager.GetStateFilePath(); + if (File.Exists(legacyPath) || File.Exists(SystemProxySnapshotStore.DefaultPath)) + { + // Don't touch a real legacy record or system proxy snapshot. + return; + } + var pid = Environment.ProcessId; + var statePath = StateManager.GetInstanceStateFilePath(pid); + Assert.False(File.Exists(statePath)); + try + { + // A dead system-proxy instance's legacy record, and a live instance (this test + // process, with an API that doesn't answer) that later got the same PID. + await StateManager.SaveStateAsync(new() { Pid = pid, ProcessStartTime = DateTimeOffset.UnixEpoch, AsSystemProxy = true }); + File.Move(statePath, legacyPath); + await StateManager.SaveStateAsync(new() + { + Pid = pid, + ProcessStartTime = StateManager.GetCurrentProcessStartTime(), + AsSystemProxy = true, + ApiUrl = "http://127.0.0.1:1", + }); + var logger = new RecordingLogger(); + + var exitCode = await StopCommandTests.CreateRootCommand(new StopCommand(logger, NullLogger.Instance)) + .Parse(["stop", "--pid", pid.ToString(CultureInfo.InvariantCulture), "--output", "json"]) + .InvokeAsync(); + + var statuses = logger.Entries + .Where(e => e.EventId == LogEvents.StructuredOutput) + .Select(e => JsonElement.Parse(e.Message).GetProperty("status").GetString()) + .ToList(); + Assert.Equal(1, exitCode); + Assert.Equal(["staleRecordRemoved", "failed"], statuses); + Assert.False(File.Exists(legacyPath)); + Assert.True(File.Exists(statePath)); + } + finally + { + File.Delete(statePath); + File.Delete(legacyPath); + } + } +} diff --git a/DevProxy.Tests/SystemProxyCommandTests.cs b/DevProxy.Tests/SystemProxyCommandTests.cs new file mode 100644 index 00000000..4edff496 --- /dev/null +++ b/DevProxy.Tests/SystemProxyCommandTests.cs @@ -0,0 +1,41 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using DevProxy.Abstractions.Proxy; +using DevProxy.Commands; +using DevProxy.Logging; +using Microsoft.Extensions.Logging; +using Xunit; + +namespace DevProxy.Tests; + +// Captures the process-wide console, so it mustn't run in parallel with other management tests. +[Collection("management-environment")] +public class SystemProxyCommandTests +{ + [Fact] + public void ConsoleLoggerFactory_JsonOutputAboveInformation_KeepsResultAndDropsDiagnostics() + { + var stdout = new StringWriter(); + var originalOut = Console.Out; + Console.SetOut(stdout); + try + { + using (var loggerFactory = SystemProxyCommand.CreateConsoleLoggerFactory(OutputFormat.Json, LogLevel.Warning)) + { + var logger = loggerFactory.CreateLogger(); + logger.LogInformation("diagnostic-below-level"); + logger.LogStructuredOutput("""{"message":"reset-result"}"""); + } + } + finally + { + Console.SetOut(originalOut); + } + + var output = stdout.ToString(); + Assert.Contains("reset-result", output, StringComparison.Ordinal); + Assert.DoesNotContain("diagnostic-below-level", output, StringComparison.Ordinal); + } +} diff --git a/DevProxy.Tests/SystemProxyRecoveryEchoTests.cs b/DevProxy.Tests/SystemProxyRecoveryEchoTests.cs new file mode 100644 index 00000000..02d4f186 --- /dev/null +++ b/DevProxy.Tests/SystemProxyRecoveryEchoTests.cs @@ -0,0 +1,88 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using DevProxy.Logging; +using Xunit; + +namespace DevProxy.Tests; + +public class SystemProxyRecoveryEchoTests +{ + private const string Restoring = "Restoring the system proxy left by a crashed Dev Proxy instance..."; + private const string AuthWarning = "Restored the HTTP proxy corp.example:8080 for Wi-Fi, but its password can't be restored. Turn on 'Proxy server requires password' for Wi-Fi in System Settings > Network > Details > Proxies and enter your credentials."; + private const string Recovered = "Recovered system proxy left by a crashed Dev Proxy instance (PID: 4242)."; + + [Fact] + public async Task TextOutput_EchoesRecoveryRecordsIncludingAuthWarning() + { + var log = string.Join("\r\n", + " info Dev Proxy is starting", + " info " + Restoring, + " warn " + AuthWarning, + " info " + Recovered, + " info Listening on 127.0.0.1:8000", + ""); + + var (stdout, stderr) = await EchoAsync(log, isJsonOutput: false); + + Assert.Equal([" info " + Restoring, " info " + Recovered], stdout); + Assert.Equal([" warn " + AuthWarning], stderr); + } + + [Fact] + public async Task TextOutput_SendsExceptionDetailsWithTheirRecord() + { + var log = string.Join("\n", + " info " + Restoring, + " fail Failed to restore the system proxy via networksetup -setwebproxy Wi-Fi.", + "System.InvalidOperationException: networksetup failed", + " fail Couldn't restore the system proxy left by a crashed Dev Proxy instance (PID: 4242)."); + + var (stdout, stderr) = await EchoAsync(log, isJsonOutput: false); + + Assert.Equal([" info " + Restoring], stdout); + Assert.Equal(3, stderr.Count); + Assert.Equal("System.InvalidOperationException: networksetup failed", stderr[1]); + } + + [Fact] + public async Task JsonOutput_EchoesRecoveryRecordsIncludingAuthWarningToStdout() + { + string Record(string level, string message) => + $$"""{"type":"log","level":"{{level}}","message":"{{message}}"}"""; + var log = string.Join("\n", + Record("info", "Dev Proxy is starting"), + Record("info", Restoring), + Record("warning", AuthWarning), + Record("info", Recovered), + Record("info", "Listening on 127.0.0.1:8000")); + + var (stdout, stderr) = await EchoAsync(log, isJsonOutput: true); + + Assert.Equal([Record("info", Restoring), Record("warning", AuthWarning), Record("info", Recovered)], stdout); + Assert.Empty(stderr); + } + + [Fact] + public async Task NoRecovery_WritesNothing() + { + var (stdout, stderr) = await EchoAsync(" warn Some plugin warning\n info Listening on 127.0.0.1:8000", isJsonOutput: false); + + Assert.Empty(stdout); + Assert.Empty(stderr); + } + + private static async Task<(List Stdout, List Stderr)> EchoAsync(string log, bool isJsonOutput) + { + using var stdout = new StringWriter(); + using var stderr = new StringWriter(); + + await SystemProxyRecoveryEcho.WriteAsync(log, isJsonOutput, stdout, stderr); + + return (Lines(stdout), Lines(stderr)); + + static List Lines(StringWriter writer) => + [.. writer.ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)]; + } +} diff --git a/DevProxy/Commands/StopCommand.cs b/DevProxy/Commands/StopCommand.cs index ac505406..7d674dba 100644 --- a/DevProxy/Commands/StopCommand.cs +++ b/DevProxy/Commands/StopCommand.cs @@ -92,6 +92,7 @@ private async Task StopByPidAsync(int pid, bool force, StopReporter reporte // its registration available for a later retry. var orphan = (await StateManager.GetOrphanedSystemProxyStatesAsync(cancellationToken)) .Find(o => o.Pid == pid); + var recoveredOrphan = false; if (orphan is not null) { @@ -112,15 +113,22 @@ private async Task StopByPidAsync(int pid, bool force, StopReporter reporte } await StateManager.DeleteStateAsync(orphan, cancellationToken); - return 0; + recoveredOrphan = true; } + // A dead instance's legacy record can share its PID with a newer live instance, + // whose record the identity-checked deletion above keeps. Stop that one too. var state = await StateManager.LoadStateByPidAsync(pid, cancellationToken); - if (state is not null) + if (state is not null && (!recoveredOrphan || StateManager.IsInstanceAlive(state))) { return await StopInstanceAsync(state, force, reporter, cancellationToken); } + if (recoveredOrphan) + { + return 0; + } + reporter.Report(pid, "notRunning", $"No running Dev Proxy instance with PID {pid}."); return 1; } diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index f754f096..8a9e156e 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -115,8 +115,13 @@ internal static async Task RunResetStandaloneAsync(string[] args) internal static ILoggerFactory CreateConsoleLoggerFactory(OutputFormat outputFormat, LogLevel logLevel) => LoggerFactory.Create(builder => { + // Results are logged at Information. For JSON output, let them through and have + // the formatter drop diagnostic messages below the requested level instead. + var pipelineLogLevel = outputFormat == OutputFormat.Json && logLevel > LogLevel.Information + ? LogLevel.Information + : logLevel; _ = builder - .SetMinimumLevel(logLevel) + .SetMinimumLevel(pipelineLogLevel) .AddConsole(consoleOptions => { consoleOptions.FormatterName = outputFormat == OutputFormat.Json @@ -133,6 +138,7 @@ internal static ILoggerFactory CreateConsoleLoggerFactory(OutputFormat outputFor { formatterOptions.IncludeScopes = false; formatterOptions.ShowTimestamps = false; + formatterOptions.MinimumLogLevel = logLevel; }); }); diff --git a/DevProxy/Logging/SystemProxyRecoveryEcho.cs b/DevProxy/Logging/SystemProxyRecoveryEcho.cs new file mode 100644 index 00000000..56828da0 --- /dev/null +++ b/DevProxy/Logging/SystemProxyRecoveryEcho.cs @@ -0,0 +1,61 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using DevProxy.Commands; + +namespace DevProxy.Logging; + +internal static class SystemProxyRecoveryEcho +{ + // The daemon recovers a system proxy left by a crashed instance before it starts + // listening, so its log has the outcome by now. Show it like a foreground start would: + // every record from the first to the last recovery message, so that warnings logged + // while restoring (like proxy credentials that need re-entering) aren't hidden. + public static async Task WriteAsync(string? log, bool isJsonOutput, TextWriter stdout, TextWriter stderr) + { + if (string.IsNullOrEmpty(log)) + { + return; + } + + var lines = log.Split('\n').Select(l => l.TrimEnd('\r')).ToArray(); + var first = Array.FindIndex(lines, IsRecoveryLine); + if (first < 0) + { + return; + } + var last = Array.FindLastIndex(lines, IsRecoveryLine); + + var toError = false; + foreach (var line in lines[first..(last + 1)]) + { + if (isJsonOutput) + { + await stdout.WriteLineAsync(line); + continue; + } + + // Exception details continue a record on the following lines, so they go to + // the same stream as the record they belong to. Warnings and errors go to stderr, + // like they do in the foreground. + var trimmed = line.TrimStart(); + if (trimmed.StartsWith("info ", StringComparison.Ordinal) || + trimmed.StartsWith("dbug ", StringComparison.Ordinal) || + trimmed.StartsWith("trce ", StringComparison.Ordinal)) + { + toError = false; + } + else if (trimmed.StartsWith("warn ", StringComparison.Ordinal) || + trimmed.StartsWith("fail ", StringComparison.Ordinal) || + trimmed.StartsWith("crit ", StringComparison.Ordinal)) + { + toError = true; + } + await (toError ? stderr : stdout).WriteLineAsync(line); + } + + static bool IsRecoveryLine(string line) => + line.Contains(DevProxyCommand.CrashedInstanceRecoveryMarker, StringComparison.Ordinal); + } +} diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index b5f89b40..0125bb8e 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -175,7 +175,7 @@ await Console.Error.WriteLineAsync( var token = ApiSecurity.ShouldDisplayTokenFor(state) ? (await File.ReadAllTextAsync(ApiSecurity.GetTokenFilePath(state.Pid))).Trim() : null; - await EchoSystemProxyRecoveryAsync(process.Id, isJsonOutput); + await DevProxy.Logging.SystemProxyRecoveryEcho.WriteAsync(await ReadDaemonLogAsync(process.Id), isJsonOutput, Console.Out, Console.Error); if (isJsonOutput) { @@ -380,57 +380,6 @@ static bool IsJsonObject(string line) } } -// The daemon recovers a system proxy left by a crashed instance before it starts -// listening, so its log has the outcome by now. Show it like a foreground start would: -// every record from the first to the last recovery message, so that warnings logged -// while restoring (like proxy credentials that need re-entering) aren't hidden. -static async Task EchoSystemProxyRecoveryAsync(int pid, bool isJsonOutput) -{ - var log = await ReadDaemonLogAsync(pid); - if (string.IsNullOrEmpty(log)) - { - return; - } - - var lines = log.Split('\n').Select(l => l.TrimEnd('\r')).ToArray(); - var first = Array.FindIndex(lines, IsRecoveryLine); - if (first < 0) - { - return; - } - var last = Array.FindLastIndex(lines, IsRecoveryLine); - - var toError = false; - foreach (var line in lines[first..(last + 1)]) - { - if (isJsonOutput) - { - await Console.Out.WriteLineAsync(line); - continue; - } - - // Exception details continue a record on the following lines, so they go to - // the same stream as the record they belong to. - var trimmed = line.TrimStart(); - if (trimmed.StartsWith("info ", StringComparison.Ordinal) || - trimmed.StartsWith("warn ", StringComparison.Ordinal) || - trimmed.StartsWith("dbug ", StringComparison.Ordinal) || - trimmed.StartsWith("trce ", StringComparison.Ordinal)) - { - toError = false; - } - else if (trimmed.StartsWith("fail ", StringComparison.Ordinal) || - trimmed.StartsWith("crit ", StringComparison.Ordinal)) - { - toError = true; - } - await (toError ? Console.Error : Console.Out).WriteLineAsync(line); - } - - static bool IsRecoveryLine(string line) => - line.Contains(DevProxyCommand.CrashedInstanceRecoveryMarker, StringComparison.Ordinal); -} - static async Task ReadDaemonLogAsync(int pid) { try From 7e4310b6556881ed7cfc03e08e319301acfc42ce Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Tue, 1 Dec 2026 16:05:48 +0100 Subject: [PATCH 20/22] Fail system-proxy reset when a state record can't be read Retiring system-proxy registrations after a restore now propagates read failures (e.g. a locked state file) instead of skipping the record, so the snapshot is kept for a retry rather than leaving a registration that could undo the restored settings later. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 26 ++++++++++++ DevProxy/Proxy/SystemProxyManager.cs | 16 +++---- DevProxy/State/StateManager.cs | 51 ++++++++++++++++++++--- 3 files changed, 80 insertions(+), 13 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 4e006461..443d1140 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -458,4 +458,30 @@ public async Task GetOrphanedSystemProxyStates_SamePidDifferentProcesses_Returns File.Delete(legacyPath); } } + + [Fact] + public async Task RetiringRegistrations_LockedRecord_Throws() + { + var pid = Random.Shared.Next(int.MaxValue / 2, int.MaxValue); + var statePath = StateManager.GetInstanceStateFilePath(pid); + Assert.False(File.Exists(statePath)); + var state = new ProxyInstanceState { Pid = pid, ProcessStartTime = DateTimeOffset.UnixEpoch, AsSystemProxy = true }; + try + { + await StateManager.SaveStateAsync(state); + + using (new FileStream(statePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + { + _ = await Assert.ThrowsAsync(() => StateManager.LoadSystemProxyRegistrationsAsync()); + _ = await Assert.ThrowsAsync(() => StateManager.ClearSystemProxyFlagAsync(state)); + _ = await Assert.ThrowsAsync(() => StateManager.RetireOrphanedStateAsync(state)); + } + + Assert.Contains(await StateManager.LoadSystemProxyRegistrationsAsync(), s => s.Pid == pid); + } + finally + { + File.Delete(statePath); + } + } } diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index dea131a6..d80b0a2c 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -278,14 +278,16 @@ private bool RetireSystemProxyRegistrations() private static async Task RetireSystemProxyRegistrationsAsync() { - foreach (var state in (await StateManager.LoadAllStatesAsync()).Where(s => s.AsSystemProxy)) + foreach (var state in await StateManager.LoadSystemProxyRegistrationsAsync()) { - await StateManager.ClearSystemProxyFlagAsync(state); - } - - foreach (var orphan in await StateManager.GetOrphanedSystemProxyStatesAsync()) - { - await StateManager.RetireOrphanedStateAsync(orphan); + if (StateManager.IsInstanceAlive(state)) + { + await StateManager.ClearSystemProxyFlagAsync(state); + } + else + { + await StateManager.RetireOrphanedStateAsync(state); + } } } diff --git a/DevProxy/State/StateManager.cs b/DevProxy/State/StateManager.cs index 7babdec4..d122fe42 100644 --- a/DevProxy/State/StateManager.cs +++ b/DevProxy/State/StateManager.cs @@ -276,6 +276,41 @@ public static async Task> GetOrphanedSystemProxyStatesA return orphaned; } + /// + /// Loads every state record that claims the system proxy, whether its process is alive + /// or not, without pruning any files. Unlike the other loaders, a record that exists but + /// can't be read (e.g. it's locked) throws instead of being skipped: retiring the + /// registrations after restoring the system proxy must not miss one, or it could later + /// change the restored settings again. + /// + public static async Task> LoadSystemProxyRegistrationsAsync(CancellationToken cancellationToken = default) + { + var configFolder = GetConfigFolder(); + if (!Directory.Exists(configFolder)) + { + return []; + } + + var registrations = new List(); + var seen = new HashSet<(int, DateTimeOffset?)>(); + + var stateFiles = Directory.GetFiles(configFolder, $"{StateFilePrefix}*{StateFileExtension}"); + var legacyPath = GetStateFilePath(); + var paths = File.Exists(legacyPath) ? [.. stateFiles, legacyPath] : stateFiles; + + foreach (var filePath in paths) + { + var state = await ReadStateFromFileAsync(filePath, cancellationToken, propagateReadFailures: true); + if (state is { AsSystemProxy: true } && + seen.Add((state.Pid, state.ProcessStartTime))) + { + registrations.Add(state); + } + } + + return registrations; + } + /// /// Deletes the state file for a specific PID. /// Also cleans up the legacy state file if it belongs to this PID. @@ -345,13 +380,14 @@ public static async Task RetireOrphanedStateAsync(ProxyInstanceState state, Canc /// Records that the given instance no longer owns the system proxy, so stopping it or /// recovering after it crashes doesn't change the OS proxy settings. The on-disk record /// is re-read and only updated if it still describes the same instance, so a newer - /// instance that reused the PID keeps its own record. + /// instance that reused the PID keeps its own record. Throws if a record exists but + /// can't be read, so the caller doesn't assume the flag was cleared. /// public static async Task ClearSystemProxyFlagAsync(ProxyInstanceState expected, CancellationToken cancellationToken = default) { foreach (var filePath in new[] { GetInstanceStateFilePath(expected.Pid), GetStateFilePath() }) { - var current = await ReadStateFromFileAsync(filePath, cancellationToken); + var current = await ReadStateFromFileAsync(filePath, cancellationToken, propagateReadFailures: true); if (current is { AsSystemProxy: true } && current.Pid == expected.Pid && current.ProcessStartTime == expected.ProcessStartTime) @@ -519,11 +555,14 @@ internal static bool IsProcessRunning(int pid) /// Reads and deserializes a state file without verifying process liveness or /// pruning stale files. Returns null if the file doesn't exist or can't be /// parsed. Use this when the caller needs to inspect records of processes that - /// may no longer be alive (e.g. crash recovery). + /// may no longer be alive (e.g. crash recovery). With , + /// a file that exists but can't be read throws instead of returning null; unparsable + /// content still returns null, because it can't become readable later. /// private static async Task ReadStateFromFileAsync( string filePath, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + bool propagateReadFailures = false) { if (!File.Exists(filePath)) { @@ -539,7 +578,7 @@ internal static bool IsProcessRunning(int pid) { return null; } - catch (IOException) + catch (IOException ex) when (!propagateReadFailures || ex is FileNotFoundException or DirectoryNotFoundException) { return null; } @@ -553,7 +592,7 @@ private static async Task DeleteStateFileIfMatchesAsync( CancellationToken cancellationToken, bool throwOnFailure = false) { - var current = await ReadStateFromFileAsync(filePath, cancellationToken); + var current = await ReadStateFromFileAsync(filePath, cancellationToken, propagateReadFailures: throwOnFailure); if (current is not null && current.Pid == expected.Pid && current.ProcessStartTime == expected.ProcessStartTime) From efd367ac0a082325d85cd3eb826c707425d9f711 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Tue, 1 Dec 2026 17:14:38 +0100 Subject: [PATCH 21/22] Echo recovery warnings from a detached start at any log level Mark every message logged while restoring a crashed instance's system proxy, so 'devproxy --detach --log-level Warning' still shows warnings like the macOS proxy-authentication instructions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../SystemProxyRecoveryEchoTests.cs | 48 +++++++++++++++++++ DevProxy/Commands/DevProxyCommand.cs | 14 +++--- 2 files changed, 56 insertions(+), 6 deletions(-) diff --git a/DevProxy.Tests/SystemProxyRecoveryEchoTests.cs b/DevProxy.Tests/SystemProxyRecoveryEchoTests.cs index 02d4f186..1f19cdbf 100644 --- a/DevProxy.Tests/SystemProxyRecoveryEchoTests.cs +++ b/DevProxy.Tests/SystemProxyRecoveryEchoTests.cs @@ -2,7 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using DevProxy.Commands; using DevProxy.Logging; +using Microsoft.Extensions.Logging; using Xunit; namespace DevProxy.Tests; @@ -64,6 +66,31 @@ string Record(string level, string message) => Assert.Empty(stderr); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task WarningLogLevel_EchoesAuthWarningLoggedDuringRecovery(bool isJsonOutput) + { + // At Warning level, the Information-level announcement and summary aren't logged, + // so the auth warning must be identifiable on its own. + var inner = new CapturingLogger(LogLevel.Warning, isJsonOutput); + var announced = false; + ILogger recoveryLogger = new DevProxyCommand.RecoveryLogger(inner, () => announced = true); + recoveryLogger.LogInformation("Restored the HTTP proxy for Wi-Fi."); + recoveryLogger.LogWarning(AuthWarning); + var log = string.Join("\n", [" warn Some plugin warning", .. inner.Lines, " warn Another plugin warning"]); + + var (stdout, stderr) = await EchoAsync(log, isJsonOutput); + + Assert.True(announced); + var echoed = Assert.Single(isJsonOutput ? stdout : stderr); + var message = isJsonOutput + ? System.Text.Json.JsonElement.Parse(echoed).GetProperty("message").GetString() + : echoed; + Assert.Contains(AuthWarning, message, StringComparison.Ordinal); + Assert.Empty(isJsonOutput ? stderr : stdout); + } + [Fact] public async Task NoRecovery_WritesNothing() { @@ -73,6 +100,27 @@ public async Task NoRecovery_WritesNothing() Assert.Empty(stderr); } + private sealed class CapturingLogger(LogLevel minLevel, bool isJson) : ILogger + { + public List Lines { get; } = []; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => logLevel >= minLevel; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (!IsEnabled(logLevel)) + { + return; + } + var message = formatter(state, exception); + Lines.Add(isJson + ? System.Text.Json.JsonSerializer.Serialize(new { type = "log", level = "warning", message }) + : " warn " + message); + } + } + private static async Task<(List Stdout, List Stderr)> EchoAsync(string log, bool isJsonOutput) { using var stdout = new StringWriter(); diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 2f45eac3..62ccd130 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -961,10 +961,11 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions) private async Task ReconcileOrphanedSystemProxiesAsync(CancellationToken cancellationToken) { - // Announce the recovery before its first message, so the detached parent can echo - // everything it logs (e.g. proxy credentials that couldn't be restored) along with - // the summary. - var recoveryLogger = new FirstEntryAnnouncingLogger( + // Announce the recovery before its first message and mark every message it logs, so + // the detached parent can echo them (e.g. proxy credentials that couldn't be + // restored) along with the summary, even when the log level filters out the + // Information-level announcement and summary. + var recoveryLogger = new RecoveryLogger( _serviceProvider.GetRequiredService>(), () => _logger.LogInformation("Restoring the system proxy " + CrashedInstanceRecoveryMarker + "...")); var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync( @@ -992,7 +993,7 @@ private async Task ReconcileOrphanedSystemProxiesAsync(CancellationToken cancell } } - private sealed class FirstEntryAnnouncingLogger(ILogger inner, Action announce) : ILogger + internal sealed class RecoveryLogger(ILogger inner, Action announce) : ILogger { private bool _announced; @@ -1011,7 +1012,8 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except _announced = true; announce(); } - inner.Log(logLevel, eventId, state, exception, formatter); + inner.Log(logLevel, eventId, state, exception, + (s, e) => $"{formatter(s, e)} (while restoring the system proxy {CrashedInstanceRecoveryMarker})"); } } From bdb31f6fe35ec860d96b44f8244bd80ceaf9c2e4 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Wed, 2 Dec 2026 13:41:31 +0100 Subject: [PATCH 22/22] Fail system proxy reset on an unreadable backup and keep reset usage errors visible Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 27 ++++++++++++++++ DevProxy/Commands/SystemProxyCommand.cs | 30 +++++++++++++----- DevProxy/Proxy/SystemProxyManager.cs | 14 ++++++++- DevProxy/Proxy/SystemProxySnapshot.cs | 38 +++++++++++++++++++---- 4 files changed, 94 insertions(+), 15 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 443d1140..3c1f8bad 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -302,6 +302,33 @@ public void Load_CorruptFile_ReturnsNull() public class SystemProxyResetDetectionTests { + [Fact] + public void Restore_UnreadableSnapshot_FailsAndKeepsIt() + { + var folder = Directory.CreateTempSubdirectory("devproxy-snapshot-"); + try + { + var path = Path.Combine(folder.FullName, "system-proxy-backup.json"); + SystemProxySnapshotStore.Save(path, new() { Pid = int.MaxValue, Windows = new() { ProxyEnable = 1, ProxyServer = "corp:8080" } }); + + using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + { + Assert.ThrowsAny(() => SystemProxySnapshotStore.LoadOrThrowIfUnreadable(path)); + // The snapshot is read before any system settings change, so this is safe to run. + if (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS()) + { + Assert.Equal(SystemProxyRestoreResult.Failed, + new SystemProxyManager(NullLogger.Instance, path).Restore()); + } + } + + Assert.NotNull(SystemProxySnapshotStore.Load(path)); + } + finally + { + folder.Delete(recursive: true); + } + } [Theory] [InlineData("--bogus")] [InlineData("--output", "invalid")] diff --git a/DevProxy/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index 8a9e156e..b7cfb681 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -90,22 +90,36 @@ internal static async Task RunResetStandaloneAsync(string[] args) { var (rootCommand, forceOption) = CreateStandaloneResetParser(); var parseResult = rootCommand.Parse(args); + if (parseResult.Errors.Count > 0) + { + WriteParseErrors(parseResult); + return 2; + } + var outputFormat = parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName) ?? OutputFormat.Text; var logLevel = parseResult.GetValueOrDefault(DevProxyCommand.LogLevelOptionName) ?? LogLevel.Information; using var loggerFactory = CreateConsoleLoggerFactory(outputFormat, logLevel); var logger = loggerFactory.CreateLogger(); - if (parseResult.Errors.Count > 0) + return await ResetCoreAsync(parseResult.GetValue(forceOption), outputFormat, logger, + loggerFactory.CreateLogger(), CancellationToken.None); + } + + // Usage errors must stay visible whatever --log-level requests, like in the full command tree. + private static void WriteParseErrors(ParseResult parseResult) + { + if (DevProxyCommand.IsJsonOutputRequested(parseResult)) { - foreach (var error in parseResult.Errors) - { - logger.LogError("{Message}", error.Message); - } - return 2; + DevProxyCommand.WriteJsonParseErrors(parseResult); + return; } - return await ResetCoreAsync(parseResult.GetValue(forceOption), outputFormat, logger, - loggerFactory.CreateLogger(), CancellationToken.None); + using var loggerFactory = CreateConsoleLoggerFactory(OutputFormat.Text, LogLevel.Error); + var logger = loggerFactory.CreateLogger(); + foreach (var error in parseResult.Errors) + { + logger.LogError("{Message}", error.Message); + } } /// diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index d80b0a2c..2932fd5b 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -136,7 +136,19 @@ internal SystemProxyRestoreResult Restore() return SystemProxyRestoreResult.NotSupported; } - var snapshot = SystemProxySnapshotStore.Load(_snapshotPath); + SystemProxySnapshot? snapshot; + try + { + snapshot = SystemProxySnapshotStore.LoadOrThrowIfUnreadable(_snapshotPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Falling back to turning the proxy off would lose the saved settings, so keep + // the snapshot and the registrations for a retry. + _logger.LogError(ex, "Couldn't read the saved system proxy settings in {Path}. Make sure no other program uses the file, then run 'devproxy system-proxy reset' again.", _snapshotPath); + return SystemProxyRestoreResult.Failed; + } + bool succeeded; bool restoredPrevious; if (OperatingSystem.IsWindows()) diff --git a/DevProxy/Proxy/SystemProxySnapshot.cs b/DevProxy/Proxy/SystemProxySnapshot.cs index fef3d2bd..f2111138 100644 --- a/DevProxy/Proxy/SystemProxySnapshot.cs +++ b/DevProxy/Proxy/SystemProxySnapshot.cs @@ -88,18 +88,44 @@ internal static class SystemProxySnapshotStore public static string DefaultPath => Path.Combine(StateManager.GetConfigFolder(), FileName); + /// + /// Loads the snapshot. Returns null when there's no snapshot, it's corrupt, or it can't be read. + /// public static SystemProxySnapshot? Load(string path) { try { - if (!File.Exists(path)) - { - return null; - } + return LoadOrThrowIfUnreadable(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } - return JsonSerializer.Deserialize(File.ReadAllText(path)); + /// + /// Loads the snapshot. Returns null when there's no snapshot or it's corrupt, and throws + /// or when it exists + /// but can't be read (e.g. another process locks it), so restoring doesn't mistake it for + /// a missing snapshot and discard the settings it holds. + /// + public static SystemProxySnapshot? LoadOrThrowIfUnreadable(string path) + { + string json; + try + { + json = File.ReadAllText(path); + } + catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) + { + return null; + } + + try + { + return JsonSerializer.Deserialize(json); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + catch (JsonException) { return null; }