From 0aefab63b9fad1b3894bf3d536aa7b80442a3afa Mon Sep 17 00:00:00 2001 From: waldekmastykarz Date: Sat, 21 Nov 2026 12:14:05 +0100 Subject: [PATCH 01/12] Keep system proxy registered across hot-reload restarts Hot reload restarts the host in-process, which turned the system proxy off and on again for every reload. On macOS, each toggle runs networksetup for every network service, adding a noticeable delay and briefly letting other apps' traffic bypass the proxy. A process-wide SystemProxySession now tracks the applied endpoint across runs: it skips Disable() when the host stops for a restart, skips Enable() when the endpoint is unchanged, applies a new endpoint directly when it changed, releases the registration when a reload turns off asSystemProxy, and disables it after the restart loop ends (for example, a failed restart). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 100 ++++++++++++ DevProxy/Commands/DevProxyCommand.cs | 4 + .../IServiceCollectionExtensions.cs | 9 +- DevProxy/Program.cs | 25 +-- DevProxy/Proxy/SystemProxySession.cs | 151 ++++++++++++++++++ 5 files changed, 279 insertions(+), 10 deletions(-) create mode 100644 DevProxy/Proxy/SystemProxySession.cs diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 659998d1..28910902 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 DevProxy.Abstractions.Proxy; using DevProxy.Proxy; using Xunit; @@ -23,4 +24,103 @@ public void CreateToggleScriptStartInfo_PreservesPathAndArgumentsContainingSpace ["/Applications/Dev Proxy/toggle-proxy.sh", "on", "proxy host", "8897"], startInfo.ArgumentList); } + + [Fact] + public void SystemProxySession_RestartWithSameEndpoint_KeepsSystemProxyRegistered() + { + var restarting = false; + var manager = new CountingSystemProxyManager(); + var session = new SystemProxySession(() => restarting); + + session.BeginRun(); + var run = session.Track(manager); + run.Enable("0.0.0.0", 8000); + restarting = true; + run.Disable(); + + restarting = false; + session.BeginRun(); + run = session.Track(manager); + run.Enable("127.0.0.1", 8000); + session.ReleaseUnclaimed(); + + Assert.Equal(1, manager.EnableCount); + Assert.Equal(0, manager.DisableCount); + + run.Disable(); + + Assert.Equal(1, manager.DisableCount); + Assert.Null(session.AppliedEndpoint); + } + + [Fact] + public void SystemProxySession_RestartWithNewPort_AppliesNewEndpointWithoutDisabling() + { + var restarting = false; + var manager = new CountingSystemProxyManager(); + var session = new SystemProxySession(() => restarting); + + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8000); + restarting = true; + session.Track(manager).Disable(); + + restarting = false; + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8001); + + Assert.Equal(2, manager.EnableCount); + Assert.Equal(0, manager.DisableCount); + Assert.Equal("127.0.0.1:8001", session.AppliedEndpoint); + } + + [Fact] + public void SystemProxySession_RestartWithoutSystemProxy_ReleasesPreviousRegistration() + { + var restarting = false; + var manager = new CountingSystemProxyManager(); + var session = new SystemProxySession(() => restarting); + + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8000); + restarting = true; + session.Track(manager).Disable(); + + restarting = false; + session.BeginRun(); + _ = session.Track(manager); + session.ReleaseUnclaimed(); + + Assert.Equal(1, manager.DisableCount); + Assert.Null(session.AppliedEndpoint); + } + + [Fact] + public void SystemProxySession_FailedRestart_ReleaseDisablesSystemProxy() + { + var manager = new CountingSystemProxyManager(); + var session = new SystemProxySession(() => true); + + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8000); + session.Track(manager).Disable(); + Assert.Equal(0, manager.DisableCount); + + var cleanup = new CountingSystemProxyManager(); + session.Release(cleanup); + session.Release(cleanup); + + Assert.Equal(1, cleanup.DisableCount); + Assert.Null(session.AppliedEndpoint); + } + + private sealed class CountingSystemProxyManager : ISystemProxyManager + { + public int EnableCount { get; private set; } + public int DisableCount { get; private set; } + + public void Enable(string? ipAddress, int port) => EnableCount++; + + public void Disable() => DisableCount++; + } } diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index e46dbe45..f627ee40 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -355,6 +355,10 @@ await PortConflict.CheckAsync(PortKind.Proxy, _proxyConfiguration.IPAddress, _pr return 1; } + // After a hot reload that turned off asSystemProxy, release the system proxy + // the previous run left registered. + _app.Services.GetService()?.ReleaseUnclaimed(); + var serverAddresses = _app.Services.GetRequiredService().Features.Get(); var serverAddress = serverAddresses?.Addresses.FirstOrDefault(); var address = ApiSecurity.GetApiUrl(serverAddress ?? diff --git a/DevProxy/Extensions/IServiceCollectionExtensions.cs b/DevProxy/Extensions/IServiceCollectionExtensions.cs index a64e8bf2..7f51d3d0 100644 --- a/DevProxy/Extensions/IServiceCollectionExtensions.cs +++ b/DevProxy/Extensions/IServiceCollectionExtensions.cs @@ -50,7 +50,14 @@ public static IServiceCollection ConfigureDevProxyServices( static IServiceCollection AddProxyEngine(this IServiceCollection services) { _ = services.AddSingleton(); - _ = services.AddSingleton(); + _ = services.AddSingleton(); + // Route through the process-wide session (when registered) so the system proxy + // stays registered across hot-reload restarts. + _ = services.AddSingleton(sp => + { + var manager = sp.GetRequiredService(); + return sp.GetService()?.Track(manager) ?? manager; + }); _ = services.AddKestrelCertificateAuthority(); _ = services.AddHostedService(sp => new KestrelProxyEngine( sp.GetRequiredService(), diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index 7a07a4c8..87a35a72 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -7,6 +7,7 @@ using DevProxy.Commands; using DevProxy.Proxy; using DevProxy.State; +using Microsoft.Extensions.Logging.Abstractions; using System.Diagnostics; using System.Globalization; using System.Net; @@ -427,7 +428,7 @@ static void WriteUnresolvedEnvironmentVariables(IConfiguration configuration, De } static WebApplication BuildApplication( - DevProxyConfigOptions options, ProcessEnvironment environment, HttpProxyEnvironment proxyEnvironment) + DevProxyConfigOptions options, ProcessEnvironment environment, HttpProxyEnvironment proxyEnvironment, SystemProxySession systemProxySession) { // Don't pass command-line args to WebApplication.CreateBuilder because: // 1. Dev Proxy uses System.CommandLine for CLI parsing, not ASP.NET Core's CommandLineConfigurationProvider @@ -437,7 +438,7 @@ static WebApplication BuildApplication( _ = builder.Configuration.ConfigureDevProxyConfig(options); try { - return BuildApplicationCore(builder, options, environment, proxyEnvironment); + return BuildApplicationCore(builder, options, environment, proxyEnvironment, systemProxySession); } catch { @@ -449,13 +450,14 @@ static WebApplication BuildApplication( } static WebApplication BuildApplicationCore( - WebApplicationBuilder builder, DevProxyConfigOptions options, ProcessEnvironment environment, HttpProxyEnvironment proxyEnvironment) + WebApplicationBuilder builder, DevProxyConfigOptions options, ProcessEnvironment environment, HttpProxyEnvironment proxyEnvironment, SystemProxySession systemProxySession) { environment.Apply(builder.Configuration, options.Env); var changedProxyVariables = proxyEnvironment.GetChangedVariables(); _ = Announcement.ShowOnceAsync(); _ = builder.Logging.ConfigureDevProxyLogging(builder.Configuration, options); var allowedOrigins = ApiSecurity.GetAllowedOrigins(builder.Configuration); + _ = builder.Services.AddSingleton(systemProxySession); _ = builder.Services.ConfigureDevProxyServices(builder.Configuration, options, allowedOrigins); var defaultApiPort = 8897; @@ -494,11 +496,11 @@ static WebApplication BuildApplicationCore( return app; } -static async Task RunProxyAsync(string[] args, DevProxyConfigOptions options, HttpProxyEnvironment proxyEnvironment) +static async Task RunProxyAsync(string[] args, DevProxyConfigOptions options, HttpProxyEnvironment proxyEnvironment, SystemProxySession systemProxySession) { // Keep overrides through host shutdown, but restore inherited values before a hot reload. using var environment = new ProcessEnvironment(); - var app = BuildApplication(options, environment, proxyEnvironment); + var app = BuildApplication(options, environment, proxyEnvironment, systemProxySession); try { var devProxyCommand = app.Services.GetRequiredService(); @@ -526,16 +528,18 @@ static async Task RunProxyAsync(string[] args, DevProxyConfigOptions option int exitCode; bool shouldRestart; var proxyEnvironment = new HttpProxyEnvironment(); +var systemProxySession = new SystemProxySession(); do { try { // Reset the restart flag before each run ConfigFileWatcher.Reset(); - // RunProxyAsync only returns after the host has fully stopped, which - // means the proxy engine's shutdown (including system proxy - // deregistration) has completed — so it's safe to start a new instance. - exitCode = await RunProxyAsync(args, options, proxyEnvironment); + systemProxySession.BeginRun(); + // RunProxyAsync only returns after the host has fully stopped, so it's safe + // to start a new instance. On a restart, the system proxy stays registered + // and the next run only updates it if the endpoint changed. + exitCode = await RunProxyAsync(args, options, proxyEnvironment, systemProxySession); shouldRestart = ConfigFileWatcher.IsRestarting; } @@ -548,6 +552,9 @@ static async Task RunProxyAsync(string[] args, DevProxyConfigOptions option } } while (shouldRestart); +// Don't leave the system proxy pointing at Dev Proxy when a restart failed. +systemProxySession.Release(new SystemProxyManager(NullLogger.Instance)); + if (DevProxyCommand.IsRootCommand) { await StateManager.DeleteStateAsync(); diff --git a/DevProxy/Proxy/SystemProxySession.cs b/DevProxy/Proxy/SystemProxySession.cs new file mode 100644 index 00000000..53a8a298 --- /dev/null +++ b/DevProxy/Proxy/SystemProxySession.cs @@ -0,0 +1,151 @@ +// 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; + +namespace DevProxy.Proxy; + +/// +/// Keeps the system proxy registered across in-process hot-reload restarts. +/// +/// +/// Created once per process, outside the restart loop. Each host run wraps its +/// with , so: +/// +/// +/// stopping the host for a restart keeps the system proxy registered, +/// the next run skips re-registering when the endpoint is unchanged and applies +/// the new endpoint (without turning the proxy off first) when it changed, +/// a restarted run that no longer uses the system proxy releases it once it +/// has started (), +/// the process releases anything still registered after the restart loop ends +/// (), for example when a restart fails. +/// +/// +internal sealed class SystemProxySession(Func isRestarting) +{ + private readonly Lock _lock = new(); + private ISystemProxyManager? _currentManager; + private string? _appliedEndpoint; + private bool _claimedInCurrentRun; + + public SystemProxySession() : this(() => ConfigFileWatcher.IsRestarting) + { + } + + /// + /// The endpoint (host:port) the system proxy currently points to, or null. + /// + public string? AppliedEndpoint + { + get + { + lock (_lock) + { + return _appliedEndpoint; + } + } + } + + /// + /// Marks the start of a host run. Call before each run of the restart loop. + /// + public void BeginRun() + { + lock (_lock) + { + _claimedInCurrentRun = false; + } + } + + /// + /// Wraps the manager of the current host run so its calls go through this session. + /// + public ISystemProxyManager Track(ISystemProxyManager manager) + { + ArgumentNullException.ThrowIfNull(manager); + + lock (_lock) + { + _currentManager = manager; + } + return new TrackedSystemProxyManager(this, manager); + } + + /// + /// Releases a system proxy registration kept from a previous run when the current + /// run started without registering the system proxy (for example, after a reload set + /// asSystemProxy to false). Call once the proxy engine has started. + /// + public void ReleaseUnclaimed() + { + lock (_lock) + { + if (_appliedEndpoint is null || _claimedInCurrentRun || _currentManager is null) + { + return; + } + + _currentManager.Disable(); + _appliedEndpoint = null; + } + } + + /// + /// Releases the system proxy if it's still registered. Call after the restart loop + /// ends, when the host that registered it has already been disposed. + /// + public void Release(ISystemProxyManager manager) + { + ArgumentNullException.ThrowIfNull(manager); + + lock (_lock) + { + if (_appliedEndpoint is null) + { + return; + } + + manager.Disable(); + _appliedEndpoint = null; + } + } + + private void Enable(ISystemProxyManager manager, string? ipAddress, int port) + { + var endpoint = SystemProxyAddress.ToHostPort(ipAddress, port); + lock (_lock) + { + _claimedInCurrentRun = true; + if (string.Equals(_appliedEndpoint, endpoint, StringComparison.Ordinal)) + { + return; + } + + manager.Enable(ipAddress, port); + _appliedEndpoint = endpoint; + } + } + + private void Disable(ISystemProxyManager manager) + { + lock (_lock) + { + if (_appliedEndpoint is not null && isRestarting()) + { + return; + } + + manager.Disable(); + _appliedEndpoint = null; + } + } + + private sealed class TrackedSystemProxyManager(SystemProxySession session, ISystemProxyManager manager) : ISystemProxyManager + { + public void Enable(string? ipAddress, int port) => session.Enable(manager, ipAddress, port); + + public void Disable() => session.Disable(manager); + } +} From e9d879d428bf3a478c4982b2bc6127212741cc1e Mon Sep 17 00:00:00 2001 From: waldekmastykarz Date: Sat, 21 Nov 2026 12:19:42 +0100 Subject: [PATCH 02/12] Only skip re-enabling the system proxy after a confirmed apply Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 46 +++++++++++++++++++++-- DevProxy/Proxy/SystemProxyManager.cs | 43 ++++++++++++--------- DevProxy/Proxy/SystemProxySession.cs | 46 ++++++++++++++++------- 3 files changed, 102 insertions(+), 33 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 28910902..9be560cd 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -2,7 +2,6 @@ // 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.Proxy; using Xunit; @@ -114,12 +113,53 @@ public void SystemProxySession_FailedRestart_ReleaseDisablesSystemProxy() Assert.Null(session.AppliedEndpoint); } - private sealed class CountingSystemProxyManager : ISystemProxyManager + [Fact] + public void SystemProxySession_FailedEnable_RetriesOnRestartAndStillCleansUp() + { + var restarting = false; + var manager = new CountingSystemProxyManager { EnableSucceeds = false }; + var session = new SystemProxySession(() => restarting); + + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8000); + restarting = true; + session.Track(manager).Disable(); + + restarting = false; + manager.EnableSucceeds = true; + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8000); + + Assert.Equal(2, manager.EnableCount); + Assert.Equal(0, manager.DisableCount); + Assert.Equal("127.0.0.1:8000", session.AppliedEndpoint); + + manager.EnableSucceeds = false; + restarting = true; + session.Track(manager).Disable(); + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8001); + Assert.Null(session.AppliedEndpoint); + + var cleanup = new CountingSystemProxyManager(); + session.Release(cleanup); + + Assert.Equal(1, cleanup.DisableCount); + } + + private sealed class CountingSystemProxyManager : IConfirmingSystemProxyManager { + public bool EnableSucceeds { get; set; } = true; public int EnableCount { get; private set; } public int DisableCount { get; private set; } - public void Enable(string? ipAddress, int port) => EnableCount++; + public void Enable(string? ipAddress, int port) => _ = TryEnable(ipAddress, port); + + public bool TryEnable(string? ipAddress, int port) + { + EnableCount++; + return EnableSucceeds; + } public void Disable() => DisableCount++; } diff --git a/DevProxy/Proxy/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 89e37f0b..bf56c444 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -34,33 +34,35 @@ namespace DevProxy.Proxy; /// it cannot be exercised on non-Windows hosts. /// /// -internal sealed class SystemProxyManager(ILogger logger) : ISystemProxyManager +internal sealed class SystemProxyManager(ILogger logger) : IConfirmingSystemProxyManager { private const string InternetSettingsKey = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings"; private const int InternetOptionSettingsChanged = 39; private const int InternetOptionRefresh = 37; - public void Enable(string? ipAddress, int port) + public void Enable(string? ipAddress, int port) => _ = TryEnable(ipAddress, port); + + public bool TryEnable(string? ipAddress, int port) { if (OperatingSystem.IsWindows()) { - EnableWindows(SystemProxyAddress.ToHostPort(ipAddress, port)); + return EnableWindows(SystemProxyAddress.ToHostPort(ipAddress, port)); } - else if (OperatingSystem.IsMacOS()) + + if (OperatingSystem.IsMacOS()) { - RunToggleScript( + return RunToggleScript( "on", SystemProxyAddress.ResolveHost(ipAddress), port.ToString(CultureInfo.InvariantCulture)); } - else - { - logger.LogWarning( - "Configure your operating system to use this proxy's port and address {Address}:{Port}", - SystemProxyAddress.ResolveHost(ipAddress), - port); - } + + logger.LogWarning( + "Configure your operating system to use this proxy's port and address {Address}:{Port}", + SystemProxyAddress.ResolveHost(ipAddress), + port); + return true; } public void Disable() @@ -71,12 +73,12 @@ public void Disable() } else if (OperatingSystem.IsMacOS()) { - RunToggleScript("off"); + _ = RunToggleScript("off"); } } [SupportedOSPlatform("windows")] - private void EnableWindows(string hostPort) + private bool EnableWindows(string hostPort) { try { @@ -84,16 +86,18 @@ private void EnableWindows(string hostPort) if (key is null) { logger.LogError("Could not open the Windows Internet Settings registry key."); - return; + return false; } key.SetValue("ProxyServer", hostPort, RegistryValueKind.String); key.SetValue("ProxyEnable", 1, RegistryValueKind.DWord); NotifyWinInetSettingsChanged(); + return true; } 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."); + return false; } } @@ -134,13 +138,15 @@ 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) + // Returns true when the script exited in time with exit code 0. The script's exit + // code reflects its last networksetup call, so this can't detect partial failures. + 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; + return false; } var startInfo = CreateToggleScriptStartInfo(bashScriptPath, arguments); @@ -152,11 +158,14 @@ private void RunToggleScript(params string[] arguments) if (!process.WaitForExit(TimeSpan.FromSeconds(10))) { process.Kill(); + return false; } + return process.ExitCode == 0; } 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."); + return false; } } diff --git a/DevProxy/Proxy/SystemProxySession.cs b/DevProxy/Proxy/SystemProxySession.cs index 53a8a298..bcfb075d 100644 --- a/DevProxy/Proxy/SystemProxySession.cs +++ b/DevProxy/Proxy/SystemProxySession.cs @@ -6,6 +6,19 @@ namespace DevProxy.Proxy; +/// +/// An that reports whether enabling the system proxy +/// succeeded. +/// +internal interface IConfirmingSystemProxyManager : ISystemProxyManager +{ + /// + /// Registers Dev Proxy as the system proxy. Returns false when the settings may not + /// have been applied. + /// + bool TryEnable(string? ipAddress, int port); +} + /// /// Keeps the system proxy registered across in-process hot-reload restarts. /// @@ -15,8 +28,9 @@ namespace DevProxy.Proxy; /// /// /// stopping the host for a restart keeps the system proxy registered, -/// the next run skips re-registering when the endpoint is unchanged and applies -/// the new endpoint (without turning the proxy off first) when it changed, +/// the next run skips re-registering when the endpoint is unchanged and was +/// applied successfully, and otherwise applies it (without turning the proxy +/// off first), /// a restarted run that no longer uses the system proxy releases it once it /// has started (), /// the process releases anything still registered after the restart loop ends @@ -26,8 +40,11 @@ namespace DevProxy.Proxy; internal sealed class SystemProxySession(Func isRestarting) { private readonly Lock _lock = new(); - private ISystemProxyManager? _currentManager; + private IConfirmingSystemProxyManager? _currentManager; + // Endpoint confirmed as applied; null when not registered or when the last attempt failed. private string? _appliedEndpoint; + // True when the system proxy may point to Dev Proxy, including after a failed attempt. + private bool _registered; private bool _claimedInCurrentRun; public SystemProxySession() : this(() => ConfigFileWatcher.IsRestarting) @@ -35,7 +52,7 @@ public SystemProxySession() : this(() => ConfigFileWatcher.IsRestarting) } /// - /// The endpoint (host:port) the system proxy currently points to, or null. + /// The endpoint (host:port) the system proxy was confirmed to point to, or null. /// public string? AppliedEndpoint { @@ -62,7 +79,7 @@ public void BeginRun() /// /// Wraps the manager of the current host run so its calls go through this session. /// - public ISystemProxyManager Track(ISystemProxyManager manager) + public ISystemProxyManager Track(IConfirmingSystemProxyManager manager) { ArgumentNullException.ThrowIfNull(manager); @@ -82,13 +99,14 @@ public void ReleaseUnclaimed() { lock (_lock) { - if (_appliedEndpoint is null || _claimedInCurrentRun || _currentManager is null) + if (!_registered || _claimedInCurrentRun || _currentManager is null) { return; } _currentManager.Disable(); _appliedEndpoint = null; + _registered = false; } } @@ -102,17 +120,18 @@ public void Release(ISystemProxyManager manager) lock (_lock) { - if (_appliedEndpoint is null) + if (!_registered) { return; } manager.Disable(); _appliedEndpoint = null; + _registered = false; } } - private void Enable(ISystemProxyManager manager, string? ipAddress, int port) + private void Enable(IConfirmingSystemProxyManager manager, string? ipAddress, int port) { var endpoint = SystemProxyAddress.ToHostPort(ipAddress, port); lock (_lock) @@ -123,26 +142,27 @@ private void Enable(ISystemProxyManager manager, string? ipAddress, int port) return; } - manager.Enable(ipAddress, port); - _appliedEndpoint = endpoint; + _registered = true; + _appliedEndpoint = manager.TryEnable(ipAddress, port) ? endpoint : null; } } - private void Disable(ISystemProxyManager manager) + private void Disable(IConfirmingSystemProxyManager manager) { lock (_lock) { - if (_appliedEndpoint is not null && isRestarting()) + if (_registered && isRestarting()) { return; } manager.Disable(); _appliedEndpoint = null; + _registered = false; } } - private sealed class TrackedSystemProxyManager(SystemProxySession session, ISystemProxyManager manager) : ISystemProxyManager + private sealed class TrackedSystemProxyManager(SystemProxySession session, IConfirmingSystemProxyManager manager) : ISystemProxyManager { public void Enable(string? ipAddress, int port) => session.Enable(manager, ipAddress, port); From 7265319e3aa63238aa6538e238413a0aa9bec24a Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 08:19:39 +0100 Subject: [PATCH 03/12] Keep startup HTTP requests off the retained system proxy Before the restarted run binds its listener, DI-created HttpClients (schema validation, update check) skip a system proxy registration kept from the previous run and go direct. Other proxies, such as a separately configured upstream proxy, are used as is. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 56 +++++++++++++++++++ .../IServiceCollectionExtensions.cs | 27 ++++++++- DevProxy/Proxy/RetainedSystemProxyBypass.cs | 39 +++++++++++++ DevProxy/Proxy/SystemProxySession.cs | 37 +++++++++--- 4 files changed, 149 insertions(+), 10 deletions(-) create mode 100644 DevProxy/Proxy/RetainedSystemProxyBypass.cs diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 9be560cd..9c23f021 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 Microsoft.Extensions.DependencyInjection; +using System.Net; using Xunit; @@ -147,6 +149,60 @@ public void SystemProxySession_FailedEnable_RetriesOnRestartAndStillCleansUp() Assert.Equal(1, cleanup.DisableCount); } + [Fact] + public void RetainedSystemProxyBypass_BeforeRestartedRunBinds_SkipsOnlyRetainedEndpoint() + { + var restarting = false; + var manager = new CountingSystemProxyManager(); + var session = new SystemProxySession(() => restarting); + var destination = new Uri("https://example.com/schema.json"); + var devProxy = new WebProxy("http://127.0.0.1:8000"); + var upstream = new WebProxy("http://corp-proxy:3128"); + + session.BeginRun(); + var run = session.Track(manager); + run.Enable("0.0.0.0", 8000); + Assert.Equal(devProxy.Address, new RetainedSystemProxyBypass(devProxy, session).GetProxy(destination)); + + restarting = true; + run.Disable(); + restarting = false; + session.BeginRun(); + + var bypass = new RetainedSystemProxyBypass(devProxy, session); + Assert.Null(bypass.GetProxy(destination)); + Assert.True(bypass.IsBypassed(destination)); + Assert.Equal(upstream.Address, new RetainedSystemProxyBypass(upstream, session).GetProxy(destination)); + + session.Track(manager).Enable("127.0.0.1", 8000); + + Assert.Equal(devProxy.Address, bypass.GetProxy(destination)); + Assert.False(bypass.IsBypassed(destination)); + } + + [Fact] + public void AddRetainedSystemProxyBypass_RoutesDefaultHttpClientThroughBypass() + { + var services = new ServiceCollection(); + _ = services.AddSingleton(new SystemProxySession(() => false)); + _ = services.AddHttpClient().AddRetainedSystemProxyBypass(); + using var provider = services.BuildServiceProvider(); + + var handler = provider.GetRequiredService().CreateHandler(); + while (handler is DelegatingHandler delegatingHandler) + { + handler = delegatingHandler.InnerHandler!; + } + + var proxy = handler switch + { + SocketsHttpHandler socketsHandler => socketsHandler.Proxy, + HttpClientHandler httpClientHandler => httpClientHandler.Proxy, + _ => null + }; + _ = Assert.IsType(proxy); + } + private sealed class CountingSystemProxyManager : IConfirmingSystemProxyManager { public bool EnableSucceeds { get; set; } = true; diff --git a/DevProxy/Extensions/IServiceCollectionExtensions.cs b/DevProxy/Extensions/IServiceCollectionExtensions.cs index 7f51d3d0..abc79b3b 100644 --- a/DevProxy/Extensions/IServiceCollectionExtensions.cs +++ b/DevProxy/Extensions/IServiceCollectionExtensions.cs @@ -73,6 +73,30 @@ static IServiceCollection AddProxyEngine(this IServiceCollection services) return services; } + // Startup requests (schema validation, update check) run before the listener binds, so + // keep them off a system proxy registration retained from the previous run. + internal static IServiceCollection AddRetainedSystemProxyBypass(this IServiceCollection services) => + services.ConfigureHttpClientDefaults(builder => + builder.ConfigurePrimaryHttpMessageHandler((handler, sp) => + { + if (sp.GetService() is not { } session) + { + return; + } + + switch (handler) + { + case SocketsHttpHandler { UseProxy: true, Proxy: null } socketsHandler: + socketsHandler.Proxy = new RetainedSystemProxyBypass(HttpClient.DefaultProxy, session); + break; + case HttpClientHandler { UseProxy: true, Proxy: null } httpClientHandler: + httpClientHandler.Proxy = new RetainedSystemProxyBypass(HttpClient.DefaultProxy, session); + break; + default: + break; + } + })); + static IServiceCollection AddApplicationServices( this IServiceCollection services, ConfigurationManager configuration, @@ -93,7 +117,8 @@ static IServiceCollection AddApplicationServices( .AddSingleton() .AddSingleton() .AddSingleton() - .AddHttpClient(); + .AddHttpClient() + .AddRetainedSystemProxyBypass(); _ = services.AddPlugins(configuration, options); diff --git a/DevProxy/Proxy/RetainedSystemProxyBypass.cs b/DevProxy/Proxy/RetainedSystemProxyBypass.cs new file mode 100644 index 00000000..7419acc9 --- /dev/null +++ b/DevProxy/Proxy/RetainedSystemProxyBypass.cs @@ -0,0 +1,39 @@ +// 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.Net; + +namespace DevProxy.Proxy; + +/// +/// Sends requests directly instead of through a system proxy registration that +/// kept from a previous run while the current run hasn't +/// bound its listener yet. Any other proxy, such as a separately configured upstream +/// proxy, is used as is. +/// +internal sealed class RetainedSystemProxyBypass(IWebProxy inner, SystemProxySession session) : IWebProxy +{ + public ICredentials? Credentials + { + get => inner.Credentials; + set => inner.Credentials = value; + } + + public Uri? GetProxy(Uri destination) + { + var proxy = inner.GetProxy(destination); + return proxy is not null && session.IsRetainedUnboundEndpoint(proxy) ? null : proxy; + } + + public bool IsBypassed(Uri host) + { + if (inner.IsBypassed(host)) + { + return true; + } + + var proxy = inner.GetProxy(host); + return proxy is not null && session.IsRetainedUnboundEndpoint(proxy); + } +} diff --git a/DevProxy/Proxy/SystemProxySession.cs b/DevProxy/Proxy/SystemProxySession.cs index bcfb075d..d49255d7 100644 --- a/DevProxy/Proxy/SystemProxySession.cs +++ b/DevProxy/Proxy/SystemProxySession.cs @@ -33,6 +33,8 @@ internal interface IConfirmingSystemProxyManager : ISystemProxyManager /// off first), /// a restarted run that no longer uses the system proxy releases it once it /// has started (), +/// until the next run binds, its HTTP requests skip the kept registration +/// (), /// the process releases anything still registered after the restart loop ends /// (), for example when a restart fails. /// @@ -43,8 +45,9 @@ internal sealed class SystemProxySession(Func isRestarting) private IConfirmingSystemProxyManager? _currentManager; // Endpoint confirmed as applied; null when not registered or when the last attempt failed. private string? _appliedEndpoint; - // True when the system proxy may point to Dev Proxy, including after a failed attempt. - private bool _registered; + // Endpoint last passed to the OS; set while the system proxy may point to Dev Proxy, + // including after a failed attempt. + private string? _registeredEndpoint; private bool _claimedInCurrentRun; public SystemProxySession() : this(() => ConfigFileWatcher.IsRestarting) @@ -65,6 +68,22 @@ public string? AppliedEndpoint } } + /// + /// Returns true when is a system proxy registration kept from + /// a previous run that the current run hasn't bound yet, so nothing listens there. + /// + public bool IsRetainedUnboundEndpoint(Uri proxy) + { + ArgumentNullException.ThrowIfNull(proxy); + + lock (_lock) + { + return _registeredEndpoint is not null && + !_claimedInCurrentRun && + string.Equals(_registeredEndpoint, $"{proxy.Host}:{proxy.Port}", StringComparison.OrdinalIgnoreCase); + } + } + /// /// Marks the start of a host run. Call before each run of the restart loop. /// @@ -99,14 +118,14 @@ public void ReleaseUnclaimed() { lock (_lock) { - if (!_registered || _claimedInCurrentRun || _currentManager is null) + if (_registeredEndpoint is null || _claimedInCurrentRun || _currentManager is null) { return; } _currentManager.Disable(); _appliedEndpoint = null; - _registered = false; + _registeredEndpoint = null; } } @@ -120,14 +139,14 @@ public void Release(ISystemProxyManager manager) lock (_lock) { - if (!_registered) + if (_registeredEndpoint is null) { return; } manager.Disable(); _appliedEndpoint = null; - _registered = false; + _registeredEndpoint = null; } } @@ -142,7 +161,7 @@ private void Enable(IConfirmingSystemProxyManager manager, string? ipAddress, in return; } - _registered = true; + _registeredEndpoint = endpoint; _appliedEndpoint = manager.TryEnable(ipAddress, port) ? endpoint : null; } } @@ -151,14 +170,14 @@ private void Disable(IConfirmingSystemProxyManager manager) { lock (_lock) { - if (_registered && isRestarting()) + if (_registeredEndpoint is not null && isRestarting()) { return; } manager.Disable(); _appliedEndpoint = null; - _registered = false; + _registeredEndpoint = null; } } From 61d1d0280ad027535c33eb26a7a074817dd4e3c2 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 08:24:59 +0100 Subject: [PATCH 04/12] Normalize endpoints when matching the retained system proxy Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 19 +++++++++++++++++++ DevProxy/Proxy/SystemProxySession.cs | 6 +++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 9c23f021..5527256e 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -180,6 +180,25 @@ public void RetainedSystemProxyBypass_BeforeRestartedRunBinds_SkipsOnlyRetainedE Assert.False(bypass.IsBypassed(destination)); } + [Fact] + public void RetainedSystemProxyBypass_ExpandedIPv6Endpoint_MatchesCompressedProxyAddress() + { + var restarting = false; + var manager = new CountingSystemProxyManager(); + var session = new SystemProxySession(() => restarting); + + session.BeginRun(); + var run = session.Track(manager); + run.Enable("0:0:0:0:0:0:0:1", 8000); + restarting = true; + run.Disable(); + restarting = false; + session.BeginRun(); + + var bypass = new RetainedSystemProxyBypass(new WebProxy("http://[::1]:8000"), session); + Assert.Null(bypass.GetProxy(new Uri("https://example.com/schema.json"))); + } + [Fact] public void AddRetainedSystemProxyBypass_RoutesDefaultHttpClientThroughBypass() { diff --git a/DevProxy/Proxy/SystemProxySession.cs b/DevProxy/Proxy/SystemProxySession.cs index d49255d7..b698e879 100644 --- a/DevProxy/Proxy/SystemProxySession.cs +++ b/DevProxy/Proxy/SystemProxySession.cs @@ -78,9 +78,13 @@ public bool IsRetainedUnboundEndpoint(Uri proxy) lock (_lock) { + // Compare as URIs so different spellings of the same address match + // (for example, an expanded IPv6 address and its compressed form). return _registeredEndpoint is not null && !_claimedInCurrentRun && - string.Equals(_registeredEndpoint, $"{proxy.Host}:{proxy.Port}", StringComparison.OrdinalIgnoreCase); + Uri.TryCreate($"http://{_registeredEndpoint}", UriKind.Absolute, out var registered) && + string.Equals(registered.Host, proxy.Host, StringComparison.OrdinalIgnoreCase) && + registered.Port == proxy.Port; } } From 64fb970d069b19102497210cd239b2b4cd7bae3b Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 09:48:28 +0100 Subject: [PATCH 05/12] Document known system proxy limitations during hot reload Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy/Proxy/SystemProxySession.cs | 12 ++++++++++++ skills/dev-proxy/references/best-practices.md | 1 + 2 files changed, 13 insertions(+) diff --git a/DevProxy/Proxy/SystemProxySession.cs b/DevProxy/Proxy/SystemProxySession.cs index b698e879..9a183c2e 100644 --- a/DevProxy/Proxy/SystemProxySession.cs +++ b/DevProxy/Proxy/SystemProxySession.cs @@ -38,6 +38,18 @@ internal interface IConfirmingSystemProxyManager : ISystemProxyManager /// the process releases anything still registered after the restart loop ends /// (), for example when a restart fails. /// +/// +/// Known limitations: +/// +/// +/// The bypass only covers DI-created s. Clients with their +/// own transport, such as Azure.Identity token requests (for example, from the +/// API Center plugins), still use the OS proxy and can reach the stopped listener +/// until the new run binds. +/// When applying a changed endpoint fails, the OS can keep pointing at the +/// previous run's stopped endpoint until a later run applies it or the process +/// exits. +/// /// internal sealed class SystemProxySession(Func isRestarting) { diff --git a/skills/dev-proxy/references/best-practices.md b/skills/dev-proxy/references/best-practices.md index 00ef6c82..8e812626 100644 --- a/skills/dev-proxy/references/best-practices.md +++ b/skills/dev-proxy/references/best-practices.md @@ -44,6 +44,7 @@ - Dev Proxy supports hot reload of configuration files (v2.1.0+). Modifying the configuration file while Dev Proxy is running automatically detects changes and restarts with the new configuration. - Hot reload works for the main configuration file and plugin-specific configuration files (mock files, CRUD API data files, etc.). - No manual restart needed after making configuration changes — save the file and changes take effect automatically. +- When Dev Proxy is the system proxy, it stays registered during a reload. Known limitations: Azure sign-in requests (for example, from the API Center plugins) made while Dev Proxy restarts can fail, and if Dev Proxy can't apply a changed IP address or port, the system proxy can keep pointing at the old one until the next reload or until Dev Proxy stops. ## curl From f6c87ead325206d10dacbc626ffdf67fbc921d35 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Thu, 26 Nov 2026 14:45:17 +0100 Subject: [PATCH 06/12] Keep bypassing previous proxy endpoint after a failed port change When applying a changed endpoint fails during a reload, the OS can keep pointing at the previous run's endpoint. Track every endpoint the system proxy may point to until an apply succeeds or the registration is released, so the pre-bind bypass skips all of them. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 38 +++++++++++++++++++ DevProxy/Proxy/SystemProxySession.cs | 46 +++++++++++++++-------- 2 files changed, 68 insertions(+), 16 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 5527256e..3eb953d5 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -180,6 +180,44 @@ public void RetainedSystemProxyBypass_BeforeRestartedRunBinds_SkipsOnlyRetainedE Assert.False(bypass.IsBypassed(destination)); } + [Fact] + public void RetainedSystemProxyBypass_AfterFailedPortChange_SkipsPreviousAndAttemptedEndpoints() + { + var restarting = false; + var manager = new CountingSystemProxyManager(); + var session = new SystemProxySession(() => restarting); + var destination = new Uri("https://example.com/schema.json"); + var previous = new RetainedSystemProxyBypass(new WebProxy("http://127.0.0.1:8000"), session); + var attempted = new RetainedSystemProxyBypass(new WebProxy("http://127.0.0.1:8001"), session); + + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8000); + restarting = true; + session.Track(manager).Disable(); + restarting = false; + + manager.EnableSucceeds = false; + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8001); + restarting = true; + session.Track(manager).Disable(); + restarting = false; + + session.BeginRun(); + Assert.Null(previous.GetProxy(destination)); + Assert.Null(attempted.GetProxy(destination)); + + manager.EnableSucceeds = true; + session.Track(manager).Enable("127.0.0.1", 8002); + restarting = true; + session.Track(manager).Disable(); + restarting = false; + + session.BeginRun(); + Assert.NotNull(previous.GetProxy(destination)); + Assert.NotNull(attempted.GetProxy(destination)); + } + [Fact] public void RetainedSystemProxyBypass_ExpandedIPv6Endpoint_MatchesCompressedProxyAddress() { diff --git a/DevProxy/Proxy/SystemProxySession.cs b/DevProxy/Proxy/SystemProxySession.cs index 9a183c2e..d96b7e14 100644 --- a/DevProxy/Proxy/SystemProxySession.cs +++ b/DevProxy/Proxy/SystemProxySession.cs @@ -48,7 +48,7 @@ internal interface IConfirmingSystemProxyManager : ISystemProxyManager /// until the new run binds. /// When applying a changed endpoint fails, the OS can keep pointing at the /// previous run's stopped endpoint until a later run applies it or the process -/// exits. +/// exits. The bypass keeps covering that endpoint in the meantime. /// /// internal sealed class SystemProxySession(Func isRestarting) @@ -57,9 +57,10 @@ internal sealed class SystemProxySession(Func isRestarting) private IConfirmingSystemProxyManager? _currentManager; // Endpoint confirmed as applied; null when not registered or when the last attempt failed. private string? _appliedEndpoint; - // Endpoint last passed to the OS; set while the system proxy may point to Dev Proxy, - // including after a failed attempt. - private string? _registeredEndpoint; + // Endpoints the system proxy may point to: the last confirmed endpoint plus any + // attempted since, because a failed attempt can leave the OS on the previous one. + // Empty when Dev Proxy isn't registered. + private readonly HashSet _registeredEndpoints = new(StringComparer.Ordinal); private bool _claimedInCurrentRun; public SystemProxySession() : this(() => ConfigFileWatcher.IsRestarting) @@ -90,13 +91,17 @@ public bool IsRetainedUnboundEndpoint(Uri proxy) lock (_lock) { + if (_claimedInCurrentRun) + { + return false; + } + // Compare as URIs so different spellings of the same address match // (for example, an expanded IPv6 address and its compressed form). - return _registeredEndpoint is not null && - !_claimedInCurrentRun && - Uri.TryCreate($"http://{_registeredEndpoint}", UriKind.Absolute, out var registered) && + return _registeredEndpoints.Any(endpoint => + Uri.TryCreate($"http://{endpoint}", UriKind.Absolute, out var registered) && string.Equals(registered.Host, proxy.Host, StringComparison.OrdinalIgnoreCase) && - registered.Port == proxy.Port; + registered.Port == proxy.Port); } } @@ -134,14 +139,14 @@ public void ReleaseUnclaimed() { lock (_lock) { - if (_registeredEndpoint is null || _claimedInCurrentRun || _currentManager is null) + if (_registeredEndpoints.Count == 0 || _claimedInCurrentRun || _currentManager is null) { return; } _currentManager.Disable(); _appliedEndpoint = null; - _registeredEndpoint = null; + _registeredEndpoints.Clear(); } } @@ -155,14 +160,14 @@ public void Release(ISystemProxyManager manager) lock (_lock) { - if (_registeredEndpoint is null) + if (_registeredEndpoints.Count == 0) { return; } manager.Disable(); _appliedEndpoint = null; - _registeredEndpoint = null; + _registeredEndpoints.Clear(); } } @@ -177,8 +182,17 @@ private void Enable(IConfirmingSystemProxyManager manager, string? ipAddress, in return; } - _registeredEndpoint = endpoint; - _appliedEndpoint = manager.TryEnable(ipAddress, port) ? endpoint : null; + _ = _registeredEndpoints.Add(endpoint); + if (manager.TryEnable(ipAddress, port)) + { + _registeredEndpoints.Clear(); + _ = _registeredEndpoints.Add(endpoint); + _appliedEndpoint = endpoint; + } + else + { + _appliedEndpoint = null; + } } } @@ -186,14 +200,14 @@ private void Disable(IConfirmingSystemProxyManager manager) { lock (_lock) { - if (_registeredEndpoint is not null && isRestarting()) + if (_registeredEndpoints.Count > 0 && isRestarting()) { return; } manager.Disable(); _appliedEndpoint = null; - _registeredEndpoint = null; + _registeredEndpoints.Clear(); } } From 7a483bca643d7c8e25441f67ea06cc28d3c6221c Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 10:02:04 +0100 Subject: [PATCH 07/12] Bypass retained system proxy for language model HTTP client Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../LanguageModelClientFactory.cs | 101 ++++--- DevProxy.Tests/SystemProxyManagerTests.cs | 15 + .../IServiceCollectionExtensions.cs | 264 +++++++++--------- 3 files changed, 208 insertions(+), 172 deletions(-) diff --git a/DevProxy.Abstractions/LanguageModel/LanguageModelClientFactory.cs b/DevProxy.Abstractions/LanguageModel/LanguageModelClientFactory.cs index 324a3b93..75886537 100644 --- a/DevProxy.Abstractions/LanguageModel/LanguageModelClientFactory.cs +++ b/DevProxy.Abstractions/LanguageModel/LanguageModelClientFactory.cs @@ -1,46 +1,57 @@ -// 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 Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace DevProxy.Abstractions.LanguageModel; - -public static class LanguageModelClientFactory -{ - // Register an HttpClient created with CreateHttpClient() under this key - // so that the container owns and disposes it - public const string HttpClientServiceKey = "DevProxy.LanguageModel"; - - public static ILanguageModelClient Create(IServiceProvider serviceProvider, IConfiguration configuration) - { - ArgumentNullException.ThrowIfNull(serviceProvider); - ArgumentNullException.ThrowIfNull(configuration); - - var lmSection = configuration.GetSection("LanguageModel"); - var config = lmSection?.Get() ?? new(); - - var httpClient = serviceProvider.GetKeyedService(HttpClientServiceKey) ?? CreateHttpClient(); - - return config.Client switch - { - LanguageModelClient.Ollama => ActivatorUtilities.CreateInstance(serviceProvider, httpClient, config), - LanguageModelClient.OpenAI => ActivatorUtilities.CreateInstance(serviceProvider, httpClient, config), - LanguageModelClient.AzureOpenAI => ActivatorUtilities.CreateInstance(serviceProvider, httpClient, config), - _ => ActivatorUtilities.CreateInstance(serviceProvider, httpClient, config) - }; - } - - // Redirects are disabled so that credentials (eg. the api-key header, - // which HttpClient doesn't strip on redirect) aren't forwarded to - // another origin - public static HttpClient CreateHttpClient() => -#pragma warning disable CA2000 // The handler is owned by the long-lived HttpClient - new(new SocketsHttpHandler - { - AllowAutoRedirect = false, - PooledConnectionLifetime = TimeSpan.FromMinutes(5) - }, disposeHandler: true); -#pragma warning restore CA2000 +// 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 Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace DevProxy.Abstractions.LanguageModel; + +public static class LanguageModelClientFactory +{ + // Register an HttpClient created with CreateHttpClient() under this key + // so that the container owns and disposes it + public const string HttpClientServiceKey = "DevProxy.LanguageModel"; + + public static ILanguageModelClient Create(IServiceProvider serviceProvider, IConfiguration configuration) + { + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(configuration); + + var lmSection = configuration.GetSection("LanguageModel"); + var config = lmSection?.Get() ?? new(); + + var httpClient = serviceProvider.GetKeyedService(HttpClientServiceKey) ?? CreateHttpClient(); + + return config.Client switch + { + LanguageModelClient.Ollama => ActivatorUtilities.CreateInstance(serviceProvider, httpClient, config), + LanguageModelClient.OpenAI => ActivatorUtilities.CreateInstance(serviceProvider, httpClient, config), + LanguageModelClient.AzureOpenAI => ActivatorUtilities.CreateInstance(serviceProvider, httpClient, config), + _ => ActivatorUtilities.CreateInstance(serviceProvider, httpClient, config) + }; + } + + // Redirects are disabled so that credentials (eg. the api-key header, + // which HttpClient doesn't strip on redirect) aren't forwarded to + // another origin + public static HttpClient CreateHttpClient() => CreateHttpClient(null); + + // proxy overrides the default (system) proxy; null keeps the default + public static HttpClient CreateHttpClient(System.Net.IWebProxy? proxy) + { +#pragma warning disable CA2000 // The handler is owned by the long-lived HttpClient + var handler = new SocketsHttpHandler + { + AllowAutoRedirect = false, + PooledConnectionLifetime = TimeSpan.FromMinutes(5) + }; +#pragma warning restore CA2000 + if (proxy is not null) + { + handler.Proxy = proxy; + } + + return new(handler, disposeHandler: true); + } } \ No newline at end of file diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 3eb953d5..624d24e0 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -260,6 +260,21 @@ public void AddRetainedSystemProxyBypass_RoutesDefaultHttpClientThroughBypass() _ = Assert.IsType(proxy); } + [Fact] + public void CreateLanguageModelHttpClient_RoutesThroughBypass() + { + var services = new ServiceCollection(); + _ = services.AddSingleton(new SystemProxySession(() => false)); + using var provider = services.BuildServiceProvider(); + + using var client = IServiceCollectionExtensions.CreateLanguageModelHttpClient(provider); + + var field = typeof(HttpMessageInvoker).GetField("_handler", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!; + var handler = Assert.IsType(field.GetValue(client)); + _ = Assert.IsType(handler.Proxy); + Assert.False(handler.AllowAutoRedirect); + } + private sealed class CountingSystemProxyManager : IConfirmingSystemProxyManager { public bool EnableSucceeds { get; set; } = true; diff --git a/DevProxy/Extensions/IServiceCollectionExtensions.cs b/DevProxy/Extensions/IServiceCollectionExtensions.cs index 00c5fa97..262f3989 100644 --- a/DevProxy/Extensions/IServiceCollectionExtensions.cs +++ b/DevProxy/Extensions/IServiceCollectionExtensions.cs @@ -1,128 +1,138 @@ -// 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; -using DevProxy.Abstractions.Data; -using DevProxy.Abstractions.LanguageModel; -using DevProxy.Abstractions.Plugins; -using DevProxy.Abstractions.Proxy; -using DevProxy.Commands; -using DevProxy.Proxy; -using DevProxy.Proxy.Kestrel; -using DevProxy.Proxy.Kestrel.Internal; -using Microsoft.Extensions.Logging; - -#pragma warning disable IDE0130 -namespace Microsoft.Extensions.DependencyInjection; -#pragma warning restore IDE0130 - -static class IServiceCollectionExtensions -{ - public static IServiceCollection ConfigureDevProxyServices( - this IServiceCollection services, - ConfigurationManager configuration, - DevProxyConfigOptions options, - string[] allowedOrigins) - { - _ = services.AddControllers(); - _ = services.AddCors(options => - { - options.AddDefaultPolicy(builder => - { - _ = builder - .WithOrigins(allowedOrigins) - .WithMethods("GET", "POST") - .WithHeaders("Authorization", "Content-Type", "Accept"); - }); - }); - _ = services - .AddApplicationServices(configuration, options) - .AddProxyEngine() - .Configure(options => options.LowercaseUrls = true); - - return services; - } - - // The Kestrel engine is the sole proxy engine. It receives the shared - // CertificateAuthority (registered via AddKestrelCertificateAuthority) plus the - // host's platform trust + system-proxy implementations. - static IServiceCollection AddProxyEngine(this IServiceCollection services) - { - _ = services.AddSingleton(); - _ = services.AddSingleton(); - // Route through the process-wide session (when registered) so the system proxy - // stays registered across hot-reload restarts. - _ = services.AddSingleton(sp => - { - var manager = sp.GetRequiredService(); - return sp.GetService()?.Track(manager) ?? manager; - }); - _ = services.AddKestrelCertificateAuthority(); - _ = services.AddHostedService(sp => new KestrelProxyEngine( - sp.GetRequiredService(), - sp.GetServices(), - sp.GetRequiredService>(), - sp.GetRequiredService(), - sp.GetRequiredService().GlobalData, - sp.GetRequiredService(), - sp.GetRequiredService(), - sp.GetRequiredService(), - sp.GetRequiredService())); - - return services; - } - - // Startup requests (schema validation, update check) run before the listener binds, so - // keep them off a system proxy registration retained from the previous run. - internal static IServiceCollection AddRetainedSystemProxyBypass(this IServiceCollection services) => - services.ConfigureHttpClientDefaults(builder => - builder.ConfigurePrimaryHttpMessageHandler((handler, sp) => - { - if (sp.GetService() is not { } session) - { - return; - } - - switch (handler) - { - case SocketsHttpHandler { UseProxy: true, Proxy: null } socketsHandler: - socketsHandler.Proxy = new RetainedSystemProxyBypass(HttpClient.DefaultProxy, session); - break; - case HttpClientHandler { UseProxy: true, Proxy: null } httpClientHandler: - httpClientHandler.Proxy = new RetainedSystemProxyBypass(HttpClient.DefaultProxy, session); - break; - default: - break; - } - })); - - static IServiceCollection AddApplicationServices( - this IServiceCollection services, - ConfigurationManager configuration, - DevProxyConfigOptions options) - { - _ = services - .AddSingleton(options) - .AddSingleton((IConfigurationRoot)configuration) - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddHostedService() - // Share the hosted instance so the command can release its startup-output gate. - .AddSingleton() - .AddHostedService(sp => sp.GetRequiredService()) - .AddKeyedSingleton(LanguageModelClientFactory.HttpClientServiceKey, (_, _) => LanguageModelClientFactory.CreateHttpClient()) - .AddSingleton(sp => LanguageModelClientFactory.Create(sp, configuration)) - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddHttpClient() - .AddRetainedSystemProxyBypass(); - - _ = services.AddPlugins(configuration, options); - - return services; - } +// 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; +using DevProxy.Abstractions.Data; +using DevProxy.Abstractions.LanguageModel; +using DevProxy.Abstractions.Plugins; +using DevProxy.Abstractions.Proxy; +using DevProxy.Commands; +using DevProxy.Proxy; +using DevProxy.Proxy.Kestrel; +using DevProxy.Proxy.Kestrel.Internal; +using Microsoft.Extensions.Logging; + +#pragma warning disable IDE0130 +namespace Microsoft.Extensions.DependencyInjection; +#pragma warning restore IDE0130 + +static class IServiceCollectionExtensions +{ + public static IServiceCollection ConfigureDevProxyServices( + this IServiceCollection services, + ConfigurationManager configuration, + DevProxyConfigOptions options, + string[] allowedOrigins) + { + _ = services.AddControllers(); + _ = services.AddCors(options => + { + options.AddDefaultPolicy(builder => + { + _ = builder + .WithOrigins(allowedOrigins) + .WithMethods("GET", "POST") + .WithHeaders("Authorization", "Content-Type", "Accept"); + }); + }); + _ = services + .AddApplicationServices(configuration, options) + .AddProxyEngine() + .Configure(options => options.LowercaseUrls = true); + + return services; + } + + // The Kestrel engine is the sole proxy engine. It receives the shared + // CertificateAuthority (registered via AddKestrelCertificateAuthority) plus the + // host's platform trust + system-proxy implementations. + static IServiceCollection AddProxyEngine(this IServiceCollection services) + { + _ = services.AddSingleton(); + _ = services.AddSingleton(); + // Route through the process-wide session (when registered) so the system proxy + // stays registered across hot-reload restarts. + _ = services.AddSingleton(sp => + { + var manager = sp.GetRequiredService(); + return sp.GetService()?.Track(manager) ?? manager; + }); + _ = services.AddKestrelCertificateAuthority(); + _ = services.AddHostedService(sp => new KestrelProxyEngine( + sp.GetRequiredService(), + sp.GetServices(), + sp.GetRequiredService>(), + sp.GetRequiredService(), + sp.GetRequiredService().GlobalData, + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService())); + + return services; + } + + // Startup requests (schema validation, update check) run before the listener binds, so + // keep them off a system proxy registration retained from the previous run. + internal static IServiceCollection AddRetainedSystemProxyBypass(this IServiceCollection services) => + services.ConfigureHttpClientDefaults(builder => + builder.ConfigurePrimaryHttpMessageHandler((handler, sp) => + { + if (CreateRetainedSystemProxyBypass(sp) is not { } bypass) + { + return; + } + + switch (handler) + { + case SocketsHttpHandler { UseProxy: true, Proxy: null } socketsHandler: + socketsHandler.Proxy = bypass; + break; + case HttpClientHandler { UseProxy: true, Proxy: null } httpClientHandler: + httpClientHandler.Proxy = bypass; + break; + default: + break; + } + })); + + // The language-model client builds its own handler (outside IHttpClientFactory), + // so it needs the bypass applied explicitly. + internal static HttpClient CreateLanguageModelHttpClient(IServiceProvider serviceProvider) => + LanguageModelClientFactory.CreateHttpClient(CreateRetainedSystemProxyBypass(serviceProvider)); + + static RetainedSystemProxyBypass? CreateRetainedSystemProxyBypass(IServiceProvider serviceProvider) => + serviceProvider.GetService() is { } session + ? new RetainedSystemProxyBypass(HttpClient.DefaultProxy, session) + : null; + + static IServiceCollection AddApplicationServices( + this IServiceCollection services, + ConfigurationManager configuration, + DevProxyConfigOptions options) + { + _ = services + .AddSingleton(options) + .AddSingleton((IConfigurationRoot)configuration) + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddHostedService() + // Share the hosted instance so the command can release its startup-output gate. + .AddSingleton() + .AddHostedService(sp => sp.GetRequiredService()) + .AddKeyedSingleton(LanguageModelClientFactory.HttpClientServiceKey, (sp, _) => CreateLanguageModelHttpClient(sp)) + .AddSingleton(sp => LanguageModelClientFactory.Create(sp, configuration)) + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddHttpClient() + .AddRetainedSystemProxyBypass(); + + _ = services.AddPlugins(configuration, options); + + return services; + } } \ No newline at end of file From 67f093b8b945ac3ec2e8c9fe6e0335ce210f84bb Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Wed, 2 Dec 2026 13:40:28 +0100 Subject: [PATCH 08/12] Keep system proxy cleanup ownership until removal succeeds Report whether disabling the system proxy succeeded and keep the session registration, the persisted AsSystemProxy flag and the instance state until it does, so final cleanup, stop --force and orphan recovery can still remove it. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Tests/SystemProxyManagerTests.cs | 58 +- DevProxy/Commands/DevProxyCommand.cs | 2225 +++++++++++---------- DevProxy/Program.cs | 1182 +++++------ DevProxy/Proxy/SystemProxyManager.cs | 20 +- DevProxy/Proxy/SystemProxySession.cs | 59 +- 5 files changed, 1821 insertions(+), 1723 deletions(-) diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 624d24e0..8754d471 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -115,6 +115,54 @@ public void SystemProxySession_FailedRestart_ReleaseDisablesSystemProxy() Assert.Null(session.AppliedEndpoint); } + [Fact] + public void SystemProxySession_FailedReleaseUnclaimed_KeepsRegistrationForFinalCleanup() + { + var restarting = false; + var manager = new CountingSystemProxyManager(); + var session = new SystemProxySession(() => restarting); + + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8000); + restarting = true; + session.Track(manager).Disable(); + restarting = false; + + manager.DisableSucceeds = false; + session.BeginRun(); + _ = session.Track(manager); + session.ReleaseUnclaimed(); + + Assert.Equal(1, manager.DisableCount); + Assert.True(session.HasRegistration); + + var failedCleanup = new CountingSystemProxyManager { DisableSucceeds = false }; + Assert.False(session.Release(failedCleanup)); + Assert.True(session.HasRegistration); + + var cleanup = new CountingSystemProxyManager(); + Assert.True(session.Release(cleanup)); + Assert.Equal(1, cleanup.DisableCount); + Assert.False(session.HasRegistration); + } + + [Fact] + public void SystemProxySession_FailedDisableOnStop_KeepsRegistrationForFinalCleanup() + { + var manager = new CountingSystemProxyManager { DisableSucceeds = false }; + var session = new SystemProxySession(() => false); + + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8000); + session.Track(manager).Disable(); + + Assert.True(session.HasRegistration); + + var cleanup = new CountingSystemProxyManager(); + Assert.True(session.Release(cleanup)); + Assert.Equal(1, cleanup.DisableCount); + } + [Fact] public void SystemProxySession_FailedEnable_RetriesOnRestartAndStillCleansUp() { @@ -289,6 +337,14 @@ public bool TryEnable(string? ipAddress, int port) return EnableSucceeds; } - public void Disable() => DisableCount++; + public bool DisableSucceeds { get; set; } = true; + + public void Disable() => _ = TryDisable(); + + public bool TryDisable() + { + DisableCount++; + return DisableSucceeds; + } } } diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index de2c3220..140bbf96 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -1,1111 +1,1114 @@ -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 _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 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; - } - - // After a hot reload that turned off asSystemProxy, release the system proxy - // the previous run left registered. - _app.Services.GetService()?.ReleaseUnclaimed(); - - 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 ipAddressOption = new Option(IpAddressOptionName) - { - Description = "The IP address for the proxy to bind to", - HelpName = "ip-address" - }; - ipAddressOption.Validators.Add(input => - { - if (!System.Net.IPAddress.TryParse(input.Tokens[0].Value, out _)) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid IP address. Example: 127.0.0.1"); - } - }); - - var urlsToWatchOption = new Option?>(UrlsToWatchOptionName, "-u") - { - AllowMultipleArgumentsPerToken = true, - Arity = ArgumentArity.ZeroOrMore, - Description = "The list of URLs to watch for requests", - HelpName = "urls-to-watch", - }; - - var logLevelOption = new Option(LogLevelOptionName) - { - Description = $"Level of messages to log. Allowed values: {string.Join(", ", Enum.GetNames())}", - HelpName = "log-level", - Recursive = true - }; - logLevelOption.Validators.Add(input => - { - if (!Enum.TryParse(input.Tokens[0].Value, true, out _)) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid log level. Allowed values: {string.Join(", ", Enum.GetNames())}"); - } - }); - - var portOption = new Option(PortOptionName, "-p") - { - Description = "The port for the proxy to listen on", - HelpName = "port" - }; - portOption.Validators.Add(ValidatePort); - - var apiPortOption = new Option(ApiPortOptionName) - { - Description = "The port for the Dev Proxy API to listen on", - HelpName = "api-port" - }; - apiPortOption.Validators.Add(ValidatePort); - var apiIpAddressOption = new Option(ApiIpAddressOptionName) - { - Description = "The API bind address (default: 127.0.0.1). Use ::1 for IPv6 loopback. Non-loopback binding requires a trusted network", - HelpName = "api-ip-address" - }; - apiIpAddressOption.Validators.Add(input => - { - if (!System.Net.IPAddress.TryParse(input.Tokens[0].Value, out _)) - { - input.AddError("The API address must be an IP address, for example 127.0.0.1 or ::1."); - } - }); - - var recordOption = new Option(RecordOptionName) - { - Description = "Use this option to record all request logs" - }; - - var reportDirOption = new Option(ReportDirOptionName) - { - Description = "Folder where reporters write report files. Overrides reportsFolder from the config file. Relative paths resolve against the current working directory. Default: the current working directory", - HelpName = "path", - Arity = ArgumentArity.ExactlyOne - }; - reportDirOption.Validators.Add(ValidateReportDir); - - var watchPidsOption = new Option>(WatchPidsOptionName) - { - AllowMultipleArgumentsPerToken = true, - Description = "The IDs of processes to watch for requests", - HelpName = "pids" - }; - - var watchProcessNamesOption = new Option>(WatchProcessNamesOptionName) - { - AllowMultipleArgumentsPerToken = true, - Description = "The names of processes to watch for requests", - HelpName = "process-names", - }; - - var watchProcessTreeOption = new Option(WatchProcessTreeOptionName) - { - Description = "Also watch descendants of processes selected by --watch-pids or --watch-process-names" - }; - - var noFirstRunOption = new Option(NoFirstRunOptionName) - { - Description = "Skip the first run experience" - }; - - var noWatchOption = new Option(NoWatchOptionName) - { - Description = "Disable automatic restart on configuration file changes" - }; - - var discoverOption = new Option(DiscoverOptionName) - { - Description = "Run Dev Proxy in discovery mode" - }; - - var asSystemProxyOption = new Option(AsSystemProxyOptionName) - { - Description = "Register Dev Proxy as the system proxy (default: true, false when CI is set). See https://go.devproxy.net?go=system-proxy", - HelpName = "true|false" - }; - - var installCertOption = CreateInstallCertOption(asSystemProxyOption, _proxyConfiguration); - - var timeoutOption = new Option(TimeoutOptionName, "-t") - { - Description = "Time in seconds after which Dev Proxy exits. Resets when Dev Proxy intercepts a request.", - HelpName = "timeout" - }; - timeoutOption.Validators.Add(input => - { - try - { - if (!long.TryParse(input.Tokens[0].Value, out var timeoutInput) || timeoutInput < 1) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid timeout value. Specify a positive integer (in seconds)."); - } - } - catch (InvalidOperationException ex) - { - input.AddError(ex.Message); - } - }); - - var envOption = new Option(EnvOptionName, "-e") - { - AllowMultipleArgumentsPerToken = true, - Arity = ArgumentArity.ZeroOrMore, - Description = "Environment variables to set for the Dev Proxy process, in name=value format. Also used to replace {name} placeholders in API spec files used by the MinimalPermissions plugins. Changes to HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, or NO_PROXY (including lowercase variants) require a full stop/start; hot reload cannot refresh cached HTTP proxy settings", - HelpName = "env", - }; - envOption.Validators.Add(input => - { - try - { - var envVars = input.GetValue(envOption); - if (envVars is null || envVars.Length == 0) - { - return; - } - - foreach (var envVar in envVars) - { - // Split on first '=' only - var parts = envVar.Split('=', 2); - if (parts.Length != 2 || parts[0].Length == 0) - { - input.AddError($"Invalid environment variable format: '{envVar}'. Expected format is 'name=value'."); - return; - } - } - } - catch (InvalidOperationException ex) - { - input.AddError(ex.Message); - } - }); - - var outputOption = new Option(OutputOptionName) - { - Description = $"Output format. Allowed values: {string.Join(", ", Enum.GetNames())}", - HelpName = "format", - Recursive = true - }; - outputOption.Validators.Add(input => - { - if (input.Tokens.Count == 0) - { - return; - } - if (!Enum.TryParse(input.Tokens[0].Value, true, out _)) - { - input.AddError($"'{input.Tokens[0].Value}' is not a valid output format. Allowed values: {string.Join(", ", Enum.GetNames())}"); - } - }); - - var detachedOption = new Option(DetachedOptionName, "-d") - { - Description = "Run Dev Proxy in the background" - }; - - var internalDaemonOption = new Option(InternalDaemonOptionName) - { - Description = "Internal use only - do not use directly", - Hidden = true - }; - - var noColorOption = new Option(NoColorOptionName) - { - Description = "Disable colored output", - Arity = ArgumentArity.Zero, - Recursive = true - }; - - var options = new List