From d6aeb7cdecea81caaa47715e01a84e8f3646bef1 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Wed, 2 Dec 2026 16:09:13 +0100 Subject: [PATCH 1/2] Allow only one Dev Proxy instance to be the system proxy Foreground starts and hot-reload re-registration now fail with the same error as detached starts when another live process owns the system proxy. The owner is taken from the system proxy snapshot, so foreground owners count too. Closes #2203 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 40 +++++++++++++++++++++++ DevProxy/Commands/DevProxyCommand.cs | 11 +++++++ DevProxy/Program.cs | 8 ++--- DevProxy/Proxy/SystemProxyManager.cs | 24 ++++++++++---- 4 files changed, 73 insertions(+), 10 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 3c1f8bad..a316e75c 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -451,6 +451,46 @@ await StateManager.SaveStateAsync(new() folder.Delete(recursive: true); } } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task FindLiveSystemProxyOwner_IgnoresGivenProcess(bool withSnapshot) + { + var folder = Directory.CreateTempSubdirectory("devproxy-owner-"); + var statePath = StateManager.GetInstanceStateFilePath(Environment.ProcessId); + Assert.False(File.Exists(statePath)); + try + { + // This process owns the system proxy, like an instance restarting for a hot reload. + var snapshotPath = Path.Combine(folder.FullName, "snapshot.json"); + if (withSnapshot) + { + SystemProxySnapshotStore.Save(snapshotPath, new() + { + Pid = Environment.ProcessId, + ProcessStartTime = StateManager.GetCurrentProcessStartTime(), + }); + } + else + { + await StateManager.SaveStateAsync(new() + { + Pid = Environment.ProcessId, + ProcessStartTime = StateManager.GetCurrentProcessStartTime(), + AsSystemProxy = true, + }); + } + + Assert.Null(await SystemProxyManager.FindLiveSystemProxyOwnerAsync(snapshotPath, Environment.ProcessId)); + Assert.Equal(Environment.ProcessId, await SystemProxyManager.FindLiveSystemProxyOwnerAsync(snapshotPath, Environment.ProcessId + 1)); + } + finally + { + File.Delete(statePath); + folder.Delete(recursive: true); + } + } } [Collection("management-environment")] diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 04baa30f..3bbe5072 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -601,6 +601,17 @@ private async Task InvokeAsync(ParseResult parseResult, CancellationToken c ConfigureFromOptions(parseResult); + // Only one instance can be the system proxy. This also runs on every hot reload, + // so a reload doesn't take the system proxy over from an instance that registered + // while this one was restarting. Linux has no system proxy to register. + if (_proxyConfiguration.AsSystemProxy && + (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS()) && + await SystemProxyManager.FindOtherLiveSystemProxyOwnerAsync(cancellationToken) is int systemProxyOwnerPid) + { + _logger.LogError("{SystemProxyOwned}", SystemProxyManager.FormatAlreadyOwnedError(systemProxyOwnerPid)); + return 1; + } + var portConflict = await PortConflict.CheckAsync(PortKind.Proxy, _proxyConfiguration.IPAddress, _proxyConfiguration.Port, cancellationToken) ?? await PortConflict.CheckAsync(PortKind.Api, _proxyConfiguration.ApiIpAddress, _proxyConfiguration.ApiPort, cancellationToken); diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index 0125bb8e..cb652794 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -61,17 +61,17 @@ static async Task StartDetachedProcessAsync(string[] args) // (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(); - if (systemProxyInstance is not null) + var systemProxyOwnerPid = await SystemProxyManager.FindLiveSystemProxyOwnerAsync(); + if (systemProxyOwnerPid is int ownerPid) { if (isJsonOutput) { await Console.Error.WriteLineAsync( - FormatJsonLogEntry("error", $"Dev Proxy is already running as system proxy (PID: {systemProxyInstance.Pid}). Use 'devproxy stop' to stop it first.")); + FormatJsonLogEntry("error", SystemProxyManager.FormatAlreadyOwnedError(ownerPid))); } else { - await Console.Error.WriteLineAsync($"Dev Proxy is already running as system proxy (PID: {systemProxyInstance.Pid})."); + await Console.Error.WriteLineAsync($"Dev Proxy is already running as system proxy (PID: {ownerPid})."); await Console.Error.WriteLineAsync("Use 'devproxy stop' to stop it first."); } return 1; diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 2932fd5b..b100cfd1 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -581,25 +581,37 @@ internal readonly record struct OrphanReconciliation( /// /// 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. + /// instance that registers as the system proxy rewrites it. Without a snapshot, + /// falls back to a running instance registered as the system proxy. /// Returns null when no live process owns it. /// internal static Task FindLiveSystemProxyOwnerAsync(CancellationToken cancellationToken = default) => - FindLiveSystemProxyOwnerAsync(SystemProxySnapshotStore.DefaultPath, cancellationToken); + FindLiveSystemProxyOwnerAsync(SystemProxySnapshotStore.DefaultPath, cancellationToken: cancellationToken); - internal static async Task FindLiveSystemProxyOwnerAsync(string snapshotPath, CancellationToken cancellationToken = default) + /// + /// Finds the PID of a live process other than this one that owns the system proxy, so + /// this process can refuse to register as the system proxy. Ignoring this process + /// lets a hot reload register again. Returns null when no other live process owns it. + /// + internal static Task FindOtherLiveSystemProxyOwnerAsync(CancellationToken cancellationToken = default) => + FindLiveSystemProxyOwnerAsync(SystemProxySnapshotStore.DefaultPath, Environment.ProcessId, cancellationToken); + + internal static async Task FindLiveSystemProxyOwnerAsync(string snapshotPath, int? ignoredPid = null, CancellationToken cancellationToken = default) { var snapshot = SystemProxySnapshotStore.Load(snapshotPath); if (snapshot is not null) { - return snapshot.IsOwnerAlive() ? snapshot.Pid : null; + return snapshot.IsOwnerAlive() && snapshot.Pid != ignoredPid ? snapshot.Pid : null; } - var liveInstance = await StateManager.FindSystemProxyInstanceAsync(cancellationToken); + var liveInstance = (await StateManager.LoadRunningStatesAsync(cancellationToken)) + .Find(s => s.AsSystemProxy && s.Pid != ignoredPid && StateManager.IsInstanceAlive(s)); return liveInstance?.Pid; } + internal static string FormatAlreadyOwnedError(int ownerPid) => + $"Dev Proxy is already running as system proxy (PID: {ownerPid}). Use 'devproxy stop' to stop it first."; + /// /// Reconciles system-proxy registrations left behind by crashed or killed instances. /// Restores the OS proxy (unless a live instance still owns it) and removes From 76872f93c554dd4eb086079a1dc93e3ba9a69ff8 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Wed, 2 Dec 2026 16:16:42 +0100 Subject: [PATCH 2/2] Test the startup guard for the system proxy owner Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 37 +++++++++++++++++++++++ DevProxy/Commands/DevProxyCommand.cs | 28 ++++++++++++++--- DevProxy/Proxy/SystemProxyManager.cs | 8 ----- 3 files changed, 61 insertions(+), 12 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index a316e75c..9d323428 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Text.Json; +using DevProxy.Commands; using DevProxy.Proxy; using DevProxy.State; using Microsoft.Extensions.Logging.Abstractions; @@ -491,6 +492,42 @@ await StateManager.SaveStateAsync(new() folder.Delete(recursive: true); } } + + // The test process plays the live owner recorded in the snapshot. The snapshot is + // authoritative, so the shared instance records aren't read. + [Theory] + [InlineData("other live owner", true)] + [InlineData("hot reload of the owner", false)] + [InlineData("not as system proxy", false)] + [InlineData("platform without a system proxy", false)] + [InlineData("crashed owner", false)] + public async Task FindBlockingSystemProxyOwner_BlocksOnlyForAnotherLiveOwner(string scenario, bool blocks) + { + var folder = Directory.CreateTempSubdirectory("devproxy-owner-"); + try + { + var snapshotPath = Path.Combine(folder.FullName, "snapshot.json"); + var ownerPid = scenario == "crashed owner" ? int.MaxValue : Environment.ProcessId; + SystemProxySnapshotStore.Save(snapshotPath, new() + { + Pid = ownerPid, + ProcessStartTime = scenario == "crashed owner" ? DateTimeOffset.UnixEpoch : StateManager.GetCurrentProcessStartTime(), + }); + + var owner = await DevProxyCommand.FindBlockingSystemProxyOwnerAsync( + asSystemProxy: scenario != "not as system proxy", + platformRegistersSystemProxy: scenario != "platform without a system proxy", + snapshotPath, + currentPid: scenario == "hot reload of the owner" ? Environment.ProcessId : Environment.ProcessId + 1, + CancellationToken.None); + + Assert.Equal(blocks ? ownerPid : (int?)null, owner); + } + finally + { + folder.Delete(recursive: true); + } + } } [Collection("management-environment")] diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 3bbe5072..fc85cc73 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -603,10 +603,13 @@ private async Task InvokeAsync(ParseResult parseResult, CancellationToken c // Only one instance can be the system proxy. This also runs on every hot reload, // so a reload doesn't take the system proxy over from an instance that registered - // while this one was restarting. Linux has no system proxy to register. - if (_proxyConfiguration.AsSystemProxy && - (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS()) && - await SystemProxyManager.FindOtherLiveSystemProxyOwnerAsync(cancellationToken) is int systemProxyOwnerPid) + // while this one was restarting. + if (await FindBlockingSystemProxyOwnerAsync( + _proxyConfiguration.AsSystemProxy, + OperatingSystem.IsWindows() || OperatingSystem.IsMacOS(), + SystemProxySnapshotStore.DefaultPath, + Environment.ProcessId, + cancellationToken) is int systemProxyOwnerPid) { _logger.LogError("{SystemProxyOwned}", SystemProxyManager.FormatAlreadyOwnedError(systemProxyOwnerPid)); return 1; @@ -1025,6 +1028,23 @@ private static List