diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 3c1f8bad..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; @@ -451,6 +452,82 @@ 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); + } + } + + // 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 04baa30f..fc85cc73 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -601,6 +601,20 @@ 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. + 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; + } + var portConflict = await PortConflict.CheckAsync(PortKind.Proxy, _proxyConfiguration.IPAddress, _proxyConfiguration.Port, cancellationToken) ?? await PortConflict.CheckAsync(PortKind.Api, _proxyConfiguration.ApiIpAddress, _proxyConfiguration.ApiPort, cancellationToken); @@ -1014,6 +1028,23 @@ private static List