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/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/StopCommandTests.cs b/DevProxy.Tests/StopCommandTests.cs
index e3e53aad..73663df2 100644
--- a/DevProxy.Tests/StopCommandTests.cs
+++ b/DevProxy.Tests/StopCommandTests.cs
@@ -5,6 +5,9 @@
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;
using System.Text.Json;
@@ -24,7 +27,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();
@@ -43,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/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs
index 659998d1..3c1f8bad 100644
--- a/DevProxy.Tests/SystemProxyManagerTests.cs
+++ b/DevProxy.Tests/SystemProxyManagerTests.cs
@@ -2,7 +2,10 @@
// 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;
using Xunit;
@@ -10,6 +13,109 @@ 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" },
+ MacOS = [new() { Service = "Wi-Fi", Web = new() { Enabled = true, Server = "corp", Port = 8080 } }],
+ });
+ var manager = new SystemProxyManager(NullLogger.Instance, path);
+
+ // 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.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
+ {
+ folder.Delete(recursive: true);
+ }
+ }
+
[Fact]
public void CreateToggleScriptStartInfo_PreservesPathAndArgumentsContainingSpaces()
{
@@ -24,3 +130,385 @@ 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);
+ 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]
+ 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_TurnsEndpointsOff()
+ {
+ var settings = new MacOSServiceProxySettings
+ {
+ Service = "Wi-Fi",
+ Web = new() { Enabled = false, Server = string.Empty, Port = 0 },
+ SecureWeb = null,
+ };
+
+ 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]);
+ }
+}
+
+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,
+ 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 } }],
+ };
+
+ SystemProxySnapshotStore.Save(path, snapshot);
+ var loaded = SystemProxySnapshotStore.Load(path);
+
+ 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!);
+ 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);
+ }
+ }
+
+ 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()
+ {
+ var path = Path.GetTempFileName();
+ try
+ {
+ File.WriteAllText(path, "{ not json");
+ Assert.Null(SystemProxySnapshotStore.Load(path));
+ }
+ finally
+ {
+ File.Delete(path);
+ }
+ }
+}
+
+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")]
+ [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")]
+ [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("-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")]
+ [InlineData("stop")]
+ [InlineData("system-proxy", "reset", "--force", "--help")]
+ [InlineData]
+ 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
+{
+ [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);
+ }
+ }
+}
+
+[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);
+ }
+ }
+
+ [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.Tests/SystemProxyRecoveryEchoTests.cs b/DevProxy.Tests/SystemProxyRecoveryEchoTests.cs
new file mode 100644
index 00000000..1f19cdbf
--- /dev/null
+++ b/DevProxy.Tests/SystemProxyRecoveryEchoTests.cs
@@ -0,0 +1,136 @@
+// 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;
+using DevProxy.Logging;
+using Microsoft.Extensions.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);
+ }
+
+ [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()
+ {
+ 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 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();
+ 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/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs
index a5b04a17..04baa30f 100644
--- a/DevProxy/Commands/DevProxyCommand.cs
+++ b/DevProxy/Commands/DevProxyCommand.cs
@@ -1,1165 +1,1254 @@
-using DevProxy.Abstractions.Plugins;
-using DevProxy.Abstractions.Proxy;
-using DevProxy.Abstractions.Utils;
-using DevProxy.Logging;
-using DevProxy.Proxy;
-using DevProxy.Proxy.Kestrel;
-using DevProxy.State;
-using Microsoft.AspNetCore.Hosting.Server;
-using Microsoft.AspNetCore.Hosting.Server.Features;
-using System.CommandLine;
-using System.CommandLine.Help;
-using System.CommandLine.Invocation;
-using System.CommandLine.Parsing;
-using System.Globalization;
-
-namespace DevProxy.Commands;
-
-sealed class DevProxyCommand : RootCommand
-{
- private readonly IServiceProvider _serviceProvider;
- private readonly IEnumerable _plugins;
- private readonly ILogger _logger;
- private readonly IProxyConfiguration _proxyConfiguration;
- private readonly ISet _urlsToWatch;
- private readonly UpdateNotification _updateNotification;
- private WebApplication? _app;
-
- internal static readonly TimeSpan NewVersionCheckTimeout = TimeSpan.FromSeconds(5);
-
- internal const string PortOptionName = "--port";
- internal const string ApiPortOptionName = "--api-port";
- internal const string ApiIpAddressOptionName = "--api-ip-address";
- internal const string IpAddressOptionName = "--ip-address";
- internal const string LogLevelOptionName = "--log-level";
- internal const string RecordOptionName = "--record";
- internal const string ReportDirOptionName = "--report-dir";
- internal const string WatchPidsOptionName = "--watch-pids";
- internal const string WatchProcessNamesOptionName = "--watch-process-names";
- internal const string WatchProcessTreeOptionName = "--watch-process-tree";
- internal const string ConfigFileOptionName = "--config-file";
- internal static readonly Option ConfigFileOption = new(ConfigFileOptionName, "-c")
- {
- HelpName = "config-file",
- Description = "Path to config file. If not specified, Dev Proxy searches for devproxyrc.jsonc or devproxyrc.json in the current directory, then in a .devproxy/ directory, then under the ~appFolder location. Supports ~appFolder and ~dataFolder tokens, and a leading ~/ for the home directory."
- };
- internal const string NoFirstRunOptionName = "--no-first-run";
- internal const string NoWatchOptionName = "--no-watch";
- internal const string AsSystemProxyOptionName = "--as-system-proxy";
- internal const string InstallCertOptionName = "--install-cert";
- internal const string UrlsToWatchOptionName = "--urls-to-watch";
- internal const string TimeoutOptionName = "--timeout";
- internal const string DiscoverOptionName = "--discover";
- internal const string EnvOptionName = "--env";
- internal const string OutputOptionName = "--output";
- internal const string DetachedOptionName = "--detach";
- internal const string InternalDaemonOptionName = "--_internal-daemon";
- internal const string NoColorOptionName = "--no-color";
-
- private static readonly string[] globalOptions = ["--version"];
- private static readonly string[] helpOptions = ["--help", "-h", "/h", "-?", "/?"];
-
- private static bool _hasGlobalOptionsResolved;
- private static bool _isStdioCommandResolved;
- private static bool _isJwtCommandResolved;
- private static bool _isCertExportCommandResolved;
- private static bool _isRootCommandResolved;
- private static bool _isConfigValidateCommandResolved;
- private static bool _isPluginCommandResolved;
- private static bool _isDetachedModeResolved;
- private static bool _isInternalDaemonResolved;
- private static bool _stdioLogFilePathResolved;
- private static bool _detachedLogFilePathResolved;
-
- public static bool HasGlobalOptions
- {
- get
- {
- if (_hasGlobalOptionsResolved)
- {
- return field;
- }
-
- var args = Environment.GetCommandLineArgs();
- field = args.Any(arg => globalOptions.Contains(arg)) ||
- args.Any(arg => helpOptions.Contains(arg));
- _hasGlobalOptionsResolved = true;
- return field;
- }
- }
-
- public static bool IsStdioCommand
- {
- get
- {
- if (_isStdioCommandResolved)
- {
- return field;
- }
-
- field = IsStdioSubcommand(Environment.GetCommandLineArgs()[1..]);
- _isStdioCommandResolved = true;
- return field;
- }
- }
-
- // Detects the stdio subcommand rather than any argument equal to "stdio"
- // (e.g. `jwt create --name stdio`). Tokens before the subcommand may only be
- // options or their values. args excludes the program name.
- internal static bool IsStdioSubcommand(string[] args)
- {
- var inMultiValueOption = false;
- for (var i = 0; i < args.Length; i++)
- {
- if (string.Equals(args[i], "stdio", StringComparison.Ordinal))
- {
- return true;
- }
-
- if (args[i].StartsWith('-', StringComparison.Ordinal))
- {
- inMultiValueOption = _multiValueRootOptions.Contains(args[i]);
- continue;
- }
-
- var isOptionValue = inMultiValueOption || (i > 0 && args[i - 1].StartsWith('-', StringComparison.Ordinal));
- if (!isOptionValue)
- {
- return false;
- }
- }
-
- return false;
- }
-
- // Root options that accept multiple values per token, so every value
- // following them precedes the subcommand.
- private static readonly HashSet _multiValueRootOptions =
- [
- EnvOptionName,
- "-e",
- UrlsToWatchOptionName,
- "-u",
- WatchPidsOptionName,
- WatchProcessNamesOptionName
- ];
-
- public static bool IsJwtCommand
- {
- get
- {
- if (_isJwtCommandResolved)
- {
- return field;
- }
-
- var args = Environment.GetCommandLineArgs();
- field = args.Length > 1 && string.Equals(args[1], "jwt", StringComparison.OrdinalIgnoreCase);
- _isJwtCommandResolved = true;
- return field;
- }
- }
-
- public static bool IsCertExportCommand
- {
- get
- {
- if (_isCertExportCommandResolved)
- {
- return field;
- }
-
- field = IsCertExportInvocation(Environment.GetCommandLineArgs()[1..]);
- _isCertExportCommandResolved = true;
- return field;
- }
- }
-
- // Logging is configured before plugins register their options and commands, so this only
- // recognizes invocations that parse as cert export using built-in options alone. Anything
- // else (e.g. a plugin option or command) is left to CertCommand, which reroutes logging
- // once the full command line is parsed.
- internal static bool IsCertExportInvocation(string[] args)
- {
- var exportCommand = new Command("export") { TreatUnmatchedTokensAsErrors = false };
- var rootCommand = new RootCommand
- {
- new Command("cert") { exportCommand },
- new Option(ConfigFileOptionName, "-c")
- };
- // The install-cert validator only adds parse errors, which don't affect command detection
- rootCommand.AddOptions(CreateRootOptions(new ProxyConfiguration(new ConfigurationBuilder().Build(), isCi: false)));
-
- var parseResult = rootCommand.Parse(args);
- if (parseResult.CommandResult.Command != exportCommand ||
- parseResult.CommandResult.Parent is not CommandResult certResult)
- {
- return false;
- }
-
- // Every token before export must be cert or a built-in option and its values.
- // Export options are validated by the real parse.
- var recognizedTokens = parseResult.RootCommandResult.Children
- .Concat(certResult.Children)
- .OfType()
- .SelectMany(o => o.IdentifierToken is null ? o.Tokens : o.Tokens.Prepend(o.IdentifierToken))
- .Append(certResult.IdentifierToken)
- .ToHashSet();
- return parseResult.Tokens
- .TakeWhile(t => !ReferenceEquals(t, parseResult.CommandResult.IdentifierToken))
- .All(recognizedTokens.Contains);
- }
-
- public static bool IsConfigValidateCommand
- {
- get
- {
- if (_isConfigValidateCommandResolved)
- {
- return field;
- }
-
- var args = Environment.GetCommandLineArgs();
- field = IsValidateInvocation(args.Skip(1).ToArray());
- _isConfigValidateCommandResolved = true;
- return field;
- }
- }
-
- ///
- /// Returns true when args invoke 'validate' or 'config validate', allowing
- /// global options (like --output) before the command. Help is excluded so
- /// it's rendered by the full command tree.
- ///
- internal static bool IsValidateInvocation(string[] args)
- {
- if (args.Any(arg => helpOptions.Contains(arg)))
- {
- return false;
- }
-
- var commandTokens = new List(2);
- for (var i = 0; i < args.Length && commandTokens.Count < 2; i++)
- {
- var arg = args[i];
- if (string.Equals(arg, OutputOptionName, StringComparison.OrdinalIgnoreCase) ||
- string.Equals(arg, LogLevelOptionName, StringComparison.OrdinalIgnoreCase))
- {
- i++;
- continue;
- }
- if (arg.StartsWith(OutputOptionName + "=", StringComparison.OrdinalIgnoreCase) ||
- arg.StartsWith(OutputOptionName + ":", StringComparison.OrdinalIgnoreCase) ||
- arg.StartsWith(LogLevelOptionName + "=", StringComparison.OrdinalIgnoreCase) ||
- arg.StartsWith(LogLevelOptionName + ":", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(arg, NoColorOptionName, StringComparison.OrdinalIgnoreCase) ||
- (commandTokens.Count > 0 && arg.StartsWith('-', StringComparison.Ordinal)))
- {
- continue;
- }
- if (arg.StartsWith('-', StringComparison.Ordinal))
- {
- // other root options may take values, so we can't tell what follows
- break;
- }
- commandTokens.Add(arg);
- }
-
- return commandTokens.Count > 0 &&
- (string.Equals(commandTokens[0], "validate", StringComparison.OrdinalIgnoreCase) ||
- (commandTokens.Count > 1 &&
- string.Equals(commandTokens[0], "config", StringComparison.OrdinalIgnoreCase) &&
- string.Equals(commandTokens[1], "validate", StringComparison.OrdinalIgnoreCase)));
- }
-
- public static bool IsPluginCommand
- {
- get
- {
- if (_isPluginCommandResolved)
- {
- return field;
- }
-
- var args = Environment.GetCommandLineArgs();
- // skip global options supported by the standalone plugin command
- // so that e.g. `devproxy --output json plugin list` is detected too
- var i = 1;
- while (i < args.Length)
- {
- if (string.Equals(args[i], OutputOptionName, StringComparison.OrdinalIgnoreCase) ||
- string.Equals(args[i], LogLevelOptionName, StringComparison.OrdinalIgnoreCase))
- {
- i += 2;
- }
- else if (args[i].StartsWith($"{OutputOptionName}=", StringComparison.OrdinalIgnoreCase) ||
- args[i].StartsWith($"{OutputOptionName}:", StringComparison.OrdinalIgnoreCase) ||
- args[i].StartsWith($"{LogLevelOptionName}=", StringComparison.OrdinalIgnoreCase) ||
- args[i].StartsWith($"{LogLevelOptionName}:", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(args[i], NoColorOptionName, StringComparison.OrdinalIgnoreCase))
- {
- i++;
- }
- else
- {
- break;
- }
- }
- field = i < args.Length && string.Equals(args[i], "plugin", StringComparison.OrdinalIgnoreCase);
- _isPluginCommandResolved = true;
- return field;
- }
- }
-
- public static bool IsDetachedMode
- {
- get
- {
- if (_isDetachedModeResolved)
- {
- return field;
- }
-
- var args = Environment.GetCommandLineArgs();
- field = args.Contains("--detach") || args.Contains("-d");
- _isDetachedModeResolved = true;
- return field;
- }
- }
-
- ///
- /// Determines if the root command (proxy itself) is being invoked.
- /// Returns true when no subcommand is specified (only options or no args).
- /// A subcommand is detected when the first non-program argument doesn't start with '-'.
- ///
- public static bool IsRootCommand
- {
- get
- {
- if (_isRootCommandResolved)
- {
- return field;
- }
-
- var args = Environment.GetCommandLineArgs();
- // Skip the first argument which is the program name
- // If there are no more arguments, it's the root command
- // If the first argument starts with '-', it's an option (root command)
- // Otherwise, it's a subcommand name
- field = args.Length <= 1 || args[1].StartsWith('-', StringComparison.Ordinal);
- _isRootCommandResolved = true;
- return field;
- }
- }
-
- public static bool IsInternalDaemon
- {
- get
- {
- if (_isInternalDaemonResolved)
- {
- return field;
- }
-
- var args = Environment.GetCommandLineArgs();
- field = args.Contains("--_internal-daemon");
- _isInternalDaemonResolved = true;
- return field;
- }
- }
-
- public static string StdioLogFilePath
- {
- get
- {
- if (_stdioLogFilePathResolved)
- {
- return field ?? string.Empty;
- }
-
- field = Path.Combine(
- Directory.GetCurrentDirectory(),
- $"devproxy-stdio-{DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture)}.log");
- _stdioLogFilePathResolved = true;
- return field;
- }
- }
-
- public static string DetachedLogFilePath
- {
- get
- {
- if (_detachedLogFilePathResolved)
- {
- return field ?? string.Empty;
- }
-
- field = State.StateManager.GenerateLogFilePath();
- _detachedLogFilePathResolved = true;
- return field;
- }
- }
-
- public static bool NoColor => ShouldDisableColor(
- Environment.GetCommandLineArgs(),
- Environment.GetEnvironmentVariable("NO_COLOR"),
- Environment.GetEnvironmentVariable("TERM"));
-
- internal static string ResolveReportDirOption(string value) =>
- Path.GetFullPath(ProxyUtils.ReplacePathTokens(value));
-
- internal static void ValidateReportDir(OptionResult input)
- {
- if (input.Tokens.Count == 0)
- {
- input.AddError("The report directory path is missing. Specify a folder.");
- return;
- }
-
- var value = input.Tokens[0].Value;
- if (string.IsNullOrWhiteSpace(value))
- {
- input.AddError("The report directory path can't be empty.");
- return;
- }
-
- if (File.Exists(ResolveReportDirOption(value)))
- {
- input.AddError($"The report directory path '{value}' points to a file. Specify a folder.");
- }
- }
-
- // Per https://no-color.org, NO_COLOR disables color only when present and not empty.
- internal static bool ShouldDisableColor(string[] args, string? noColorEnv, string? termEnv) =>
- args.Contains(NoColorOptionName) ||
- !string.IsNullOrEmpty(noColorEnv) ||
- string.Equals(termEnv, "dumb", StringComparison.OrdinalIgnoreCase);
-
- public DevProxyCommand(
- IEnumerable plugins,
- ISet urlsToWatch,
- IProxyConfiguration proxyConfiguration,
- IServiceProvider serviceProvider,
- UpdateNotification updateNotification,
- DevProxyConfigOptions options,
- ILogger logger) : base($"Start Dev Proxy\n\nAPI:\n Dev Proxy exposes an authenticated REST API for runtime management.\n Use --api-port (default: {proxyConfiguration.ApiPort}) and --api-ip-address (default: 127.0.0.1).\n The API bind address is independent of --ip-address.\n Run 'devproxy status' for the API URL and token, or 'devproxy api show' for endpoints\n ('devproxy api show --output json' includes request and response schemas).\n Set the DEV_PROXY_API_TOKEN environment variable (at least 32 characters) to use a fixed API token instead of a generated one.")
- {
- _serviceProvider = serviceProvider;
- _plugins = plugins;
- _urlsToWatch = urlsToWatch;
- _proxyConfiguration = proxyConfiguration;
- _updateNotification = updateNotification;
- _logger = logger;
-
- ConfigureCommand(options);
- }
-
- public async Task InvokeAsync(string[] args, WebApplication app)
- {
- _app = app;
- // Use special parsing for stdio command to disable response file expansion (@file)
- // This allows npm package names like @devproxy/mcp to be passed through literally
- var parseResult = IsStdioCommand
- ? StdioCommand.ParseStdioArgs(this, args)
- : Parse(args);
-
- if (parseResult.Action is ParseErrorAction parseErrorAction)
- {
- if (IsJsonOutputRequested(parseResult))
- {
- WriteJsonParseErrors(parseResult);
- return 2;
- }
-
- parseErrorAction.ShowHelp = false;
- }
-
- var exitCode = await parseResult.InvokeAsync(null, app.Lifetime.ApplicationStopping);
-
- // Return exit code 2 for input validation and parse errors to distinguish
- // them from runtime errors (exit code 1), following conventions from
- // curl, git, and others
- if (exitCode != 0 && parseResult.Errors.Count > 0)
- {
- return 2;
- }
-
- return exitCode;
- }
-
- internal static Option CreateInstallCertOption(Option asSystemProxyOption, IProxyConfiguration proxyConfiguration)
- {
- var installCertOption = new Option(InstallCertOptionName)
- {
- Description = "Install and trust the root certificate (default: true, false when CI is set). On Linux, trust it manually",
- HelpName = "true|false"
- };
- installCertOption.Validators.Add(input =>
- {
- try
- {
- var asSystemProxy = input.GetValue(asSystemProxyOption) ?? proxyConfiguration.AsSystemProxy;
- var installCert = input.GetValue(installCertOption) ?? proxyConfiguration.InstallCert;
- if (asSystemProxy && !installCert)
- {
- input.AddError($"Requires option '{AsSystemProxyOptionName}' to be 'false'");
- }
- }
- catch (InvalidOperationException ex)
- {
- input.AddError(ex.Message);
- }
- });
- return installCertOption;
- }
-
- // Reads the raw token rather than the parsed value, because the parsed
- // value isn't available when the parse result has errors
- internal static bool IsJsonOutputRequested(ParseResult parseResult) =>
- parseResult.GetResult(OutputOptionName) is OptionResult { Tokens: [var token, ..] } &&
- string.Equals(token.Value, nameof(OutputFormat.Json), StringComparison.OrdinalIgnoreCase);
-
- internal static void WriteJsonParseErrors(ParseResult parseResult)
- {
- // Usage errors must still be visible when normal logging is disabled,
- // for example by the jwt command or --log-level None.
- using var loggerFactory = LoggerFactory.Create(builder => builder
- .SetMinimumLevel(LogLevel.Error)
- .AddConsole(options =>
- {
- options.FormatterName = JsonConsoleFormatter.FormatterName;
- options.LogToStandardErrorThreshold = LogLevel.Error;
- })
- .AddConsoleFormatter());
- var logger = loggerFactory.CreateLogger();
-
- foreach (var error in parseResult.Errors)
- {
- logger.LogError("{ParseError}", error.Message);
- }
- }
-
- internal static void ValidatePort(OptionResult input)
- {
- var value = input.Tokens.Count > 0 ? input.Tokens[0].Value : null;
- if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var port) || port > System.Net.IPEndPoint.MaxPort)
- {
- input.AddError($"'{value}' is not a valid port. Specify a number between 0 and {System.Net.IPEndPoint.MaxPort}.");
- }
- }
-
- private async Task InvokeAsync(ParseResult parseResult, CancellationToken cancellationToken)
- {
- if (_app is null)
- {
- throw new InvalidOperationException("WebApplication instance is not set. Please provide it when invoking the command.");
- }
- // 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))
- {
- _logger.LogError("{TokenError}", tokenError);
- return 1;
- }
- if (!_plugins.Any())
- {
- _logger.LogError("You haven't configured any plugins. Please add plugins to your configuration file. Dev Proxy will exit.");
- return 1;
- }
- if (_urlsToWatch.Count == 0)
- {
- _logger.LogError("You haven't configured any URLs to watch. Please add URLs to your configuration file or use the --urls-to-watch option. Dev Proxy will exit.");
- return 1;
- }
-
- ConfigureFromOptions(parseResult);
-
- var portConflict =
- await PortConflict.CheckAsync(PortKind.Proxy, _proxyConfiguration.IPAddress, _proxyConfiguration.Port, cancellationToken) ??
- await PortConflict.CheckAsync(PortKind.Api, _proxyConfiguration.ApiIpAddress, _proxyConfiguration.ApiPort, cancellationToken);
- if (portConflict is not null)
- {
- _logger.LogError("{PortConflict}", portConflict);
- return 1;
- }
-
- var optionsLoadedArgs = new OptionsLoadedArgs(parseResult);
- foreach (var plugin in _plugins.Where(p => p.Enabled))
- {
- plugin.OptionsLoaded(optionsLoadedArgs);
- }
-
- // Check for a new version in the background so that startup doesn't wait
- // for the network. Linking to the command's token (the host's
- // ApplicationStopping) cancels the check on shutdown and hot reload.
- using var newVersionCheckCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
- newVersionCheckCts.CancelAfter(NewVersionCheckTimeout);
- var newVersionCheck = CheckForNewVersionInBackgroundAsync(_updateNotification, _proxyConfiguration.NewVersionNotification, _logger, newVersionCheckCts.Token);
-
- try
- {
- await ApiSecurity.SaveTokenAsync(cancellationToken);
- await _app.StartAsync(cancellationToken);
-
- // The proxy binds in a background service, so wait for it before
- // publishing readiness. Otherwise a detached launcher could report a
- // successful start for a proxy that failed to bind. Don't pass the
- // cancellation token: a bind failure stops the host, which would cancel
- // the wait before the failure is reported. The engine always completes
- // Started once the host stops.
- var proxyEngines = _app.Services.GetServices().OfType().ToArray();
- var proxyStarted = (await Task.WhenAll(proxyEngines.Select(e => e.Started))).All(started => started);
- if (!proxyStarted)
- {
- await _app.WaitForShutdownAsync(cancellationToken);
- if (proxyEngines.Any(e => e.PortInUse))
- {
- _logger.LogError("{PortConflict}",
- await PortConflict.GetMessageAsync(PortKind.Proxy, _proxyConfiguration.IPAddress, _proxyConfiguration.Port, CancellationToken.None));
- }
- return 1;
- }
-
- var serverAddresses = _app.Services.GetRequiredService().Features.Get();
- var serverAddress = serverAddresses?.Addresses.FirstOrDefault();
- var address = ApiSecurity.GetApiUrl(serverAddress ??
- new UriBuilder(Uri.UriSchemeHttp, _proxyConfiguration.ApiIpAddress, _proxyConfiguration.ApiPort).Uri.AbsoluteUri);
- _logger.LogInformation("Dev Proxy API listening on {Address}...", address);
-
- if (_proxyConfiguration.Output != OutputFormat.Json)
- {
- ApiSecurity.LogTokenOnce(_logger);
- }
-
- if (!System.Net.IPAddress.IsLoopback(System.Net.IPAddress.Parse(_proxyConfiguration.ApiIpAddress)))
- {
- _logger.LogWarning("The Dev Proxy API is bound to {ApiIpAddress} off-loopback. Bearer tokens are sent over HTTP; use only on trusted networks or through a secure tunnel.", _proxyConfiguration.ApiIpAddress);
- }
-
- await WriteInstanceStateAsync(address);
- // Hotkeys write directly to the console, so release them after startup logging is complete.
- _app.Services.GetRequiredService().CompleteStartupMessages();
-
- await _app.WaitForShutdownAsync(cancellationToken);
-
- return 0;
- }
- catch (TaskCanceledException)
- {
- throw;
- }
- catch (Exception ex) when (PortConflict.IsAddressInUse(ex))
- {
- // The API port was taken between the pre-flight check and binding.
- _logger.LogError("{PortConflict}",
- await PortConflict.GetMessageAsync(PortKind.Api, _proxyConfiguration.ApiIpAddress, _proxyConfiguration.ApiPort, CancellationToken.None));
- return 1;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "An error occurred while running Dev Proxy");
- var inner = ex.InnerException;
-
- while (inner is not null)
- {
- _logger.LogError(inner, "============ Inner exception ============");
- inner = inner.InnerException;
- }
-#if DEBUG
- throw; // so debug tools go straight to the source of the exception when attached
-#else
- return 1;
-#endif
- }
- finally
- {
- // Stop the check before the host is disposed so that it doesn't use
- // the disposed logger or HttpClient. The check never throws.
- await newVersionCheckCts.CancelAsync();
- await newVersionCheck;
- }
- }
-
- private void ConfigureCommand(DevProxyConfigOptions configOptions)
- {
- ConfigFileOption.Validators.Clear();
- ConfigFileOption.Validators.Add(input =>
- {
- var filePath = configOptions.ConfigFile ?? ProxyUtils.ReplacePathTokens(input.Tokens[0].Value);
- if (string.IsNullOrEmpty(filePath))
- {
- return;
- }
-
- if (!File.Exists(filePath))
- {
- input.AddError($"Configuration file '{filePath}' does not exist. Check the file path and try again.");
- }
- });
-
- var options = CreateRootOptions(_proxyConfiguration);
- options.Add(ConfigFileOption);
- options.AddRange(_plugins
- .SelectMany(p => p.GetOptions())
- // remove duplicates by comparing the option names
- .GroupBy(o => o.Name)
- .Select(g => g.First()));
- this.AddOptions(options.OrderByName());
-
- var commands = new List
- {
- ActivatorUtilities.CreateInstance(_serviceProvider),
- ActivatorUtilities.CreateInstance(_serviceProvider),
- ActivatorUtilities.CreateInstance(_serviceProvider),
- ActivatorUtilities.CreateInstance(_serviceProvider),
- ActivatorUtilities.CreateInstance(_serviceProvider),
- ActivatorUtilities.CreateInstance(_serviceProvider),
- ActivatorUtilities.CreateInstance(_serviceProvider),
- ActivatorUtilities.CreateInstance(_serviceProvider),
- ActivatorUtilities.CreateInstance(_serviceProvider),
- ActivatorUtilities.CreateInstance(_serviceProvider),
- ActivatorUtilities.CreateInstance(_serviceProvider),
- ActivatorUtilities.CreateInstance(_serviceProvider)
- };
- var pluginCommands = _plugins.SelectMany(p => p.GetCommands().Select(c => (Plugin: p, Command: c)));
- foreach (var group in pluginCommands.GroupBy(pc => pc.Command.Name))
- {
- var (plugin, command) = group.First();
- HelpDocs.Set(command, DocsLinks.ForPlugin(plugin.GetType()));
- commands.Add(command);
- if (group.Count() > 1)
- {
- _logger.LogWarning(
- "Multiple plugins register the '{CommandName}' command. Only the first registration will be used",
- command.Name);
- }
- }
- this.AddCommands(commands.OrderByName());
-
- HelpExamples.Add(this, [
- ("devproxy", "Start with default config"),
- ("devproxy -c myconfig.json", "Start with custom config"),
- ("devproxy -u \"https://api.example.com/*\"", "Watch specific URLs"),
- ("devproxy --port 9000 --record", "Custom port, record requests"),
- ]);
- HelpExamples.Install(this);
-
- DevProxyHelpAction.Install(this);
-
- SetAction(InvokeAsync);
- }
-
- // Root options except --config-file, whose validator depends on the parsed config options.
- // Shared with IsCertExportInvocation so it consumes option values exactly like the real parser.
- private static List