diff --git a/DevProxy.Abstractions/LanguageModel/LanguageModelClientFactory.cs b/DevProxy.Abstractions/LanguageModel/LanguageModelClientFactory.cs index 324a3b93..44189270 100644 --- a/DevProxy.Abstractions/LanguageModel/LanguageModelClientFactory.cs +++ b/DevProxy.Abstractions/LanguageModel/LanguageModelClientFactory.cs @@ -35,12 +35,23 @@ public static ILanguageModelClient Create(IServiceProvider serviceProvider, ICon // 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() => + 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 - new(new SocketsHttpHandler + var handler = new SocketsHttpHandler { AllowAutoRedirect = false, PooledConnectionLifetime = TimeSpan.FromMinutes(5) - }, disposeHandler: true); + }; #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/StopCommandTests.cs b/DevProxy.Tests/StopCommandTests.cs index 73663df2..451afddd 100644 --- a/DevProxy.Tests/StopCommandTests.cs +++ b/DevProxy.Tests/StopCommandTests.cs @@ -40,6 +40,21 @@ public async Task Stop_JsonOutput_NoInstanceWithPid_EmitsStructuredResult() Assert.Equal($"No running Dev Proxy instance with PID {UnusedPid}.", json.RootElement.GetProperty("message").GetString()); } + [Fact] + public void FindKeptSystemProxyRecord_MatchesOnlyTheStoppedProcess() + { + var processStartTime = DateTimeOffset.UtcNow.AddMinutes(-10); + var stopped = new ProxyInstanceState { Pid = 100, AsSystemProxy = true, ProcessStartTime = processStartTime, StartedAt = processStartTime }; + // A config reload restarts the host in the same process, so only StartedAt changes. + var keptAfterReload = new ProxyInstanceState { Pid = 100, AsSystemProxy = true, ProcessStartTime = processStartTime, StartedAt = processStartTime.AddMinutes(5) }; + var otherInstance = new ProxyInstanceState { Pid = 200, AsSystemProxy = true, ProcessStartTime = processStartTime, StartedAt = processStartTime }; + var reusedPid = new ProxyInstanceState { Pid = 100, AsSystemProxy = true, ProcessStartTime = processStartTime.AddMinutes(5), StartedAt = processStartTime }; + + Assert.Same(keptAfterReload, StopCommand.FindKeptSystemProxyRecord([otherInstance, keptAfterReload], stopped)); + Assert.Null(StopCommand.FindKeptSystemProxyRecord([otherInstance, reusedPid], stopped)); + Assert.Null(StopCommand.FindKeptSystemProxyRecord([], stopped)); + } + internal static RootCommand CreateRootCommand(Command command) => [ new Option(DevProxyCommand.OutputOptionName) { Recursive = true }, diff --git a/DevProxy.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 1832b692..e7a3bad8 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -6,7 +6,9 @@ using DevProxy.Commands; using DevProxy.Proxy; using DevProxy.State; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; +using System.Net; using Xunit; @@ -24,14 +26,15 @@ public void Disable_AfterSuccessfulRestore_DoesNotRestoreAgain() var manager = new SystemProxyManager(NullLogger.Instance, path); manager.SaveSnapshot(snapshot => snapshot.Windows = new() { ProxyEnable = 1, ProxyServer = "corp:8080" }); var restoreCalls = 0; - void Restore() + bool Restore() { restoreCalls++; SystemProxySnapshotStore.Delete(path); + return true; } - manager.Disable(Restore); - manager.Disable(Restore); + _ = manager.Disable(Restore); + _ = manager.Disable(Restore); Assert.Equal(1, restoreCalls); } @@ -62,10 +65,16 @@ public void Disable_AfterResetOrTakeover_LeavesSettingsAlone(bool takeover) } var restoreCalls = 0; - manager.Disable(() => restoreCalls++); - manager.Disable(() => restoreCalls++); + Assert.True(manager.Disable(() => ++restoreCalls > 0)); + Assert.True(manager.Disable(() => ++restoreCalls > 0)); Assert.Equal(0, restoreCalls); + + // After a hot reload, the next host's manager doesn't register again when the + // endpoint is unchanged, but must still leave the settings alone. + var nextRunManager = new SystemProxyManager(NullLogger.Instance, path); + Assert.True(nextRunManager.Disable(() => ++restoreCalls > 0)); + Assert.Equal(0, restoreCalls); } finally { @@ -130,6 +139,395 @@ 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); + } + + [Theory] + [InlineData(8000)] + [InlineData(8001)] + public void SystemProxySession_RestartAfterTakeover_LeavesOtherOwnerAlone(int port) + { + var restarting = false; + var manager = new CountingSystemProxyManager(); + var session = new SystemProxySession(() => restarting); + + session.BeginRun(); + var run = session.Track(manager); + run.Enable("127.0.0.1", 8000); + restarting = true; + run.Disable(); + manager.Ownership = SystemProxyOwnership.TakenOver; + + restarting = false; + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", port); + + Assert.Equal(1, manager.EnableCount); + Assert.True(session.YieldedToOtherOwner); + Assert.False(session.HasRegistration); + Assert.Null(session.AppliedEndpoint); + } + + [Fact] + public void SystemProxySession_RestartAfterReset_RegistersAgain() + { + var restarting = false; + var manager = new CountingSystemProxyManager(); + var session = new SystemProxySession(() => restarting); + + session.BeginRun(); + var run = session.Track(manager); + run.Enable("127.0.0.1", 8000); + restarting = true; + run.Disable(); + manager.Ownership = SystemProxyOwnership.Released; + + restarting = false; + session.BeginRun(); + session.Track(manager).Enable("127.0.0.1", 8000); + + Assert.Equal(2, manager.EnableCount); + Assert.False(session.YieldedToOtherOwner); + Assert.True(session.HasRegistration); + } + + [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); + } + + [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() + { + 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); + } + + [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 RetainedSystemProxyBypass_AfterListenerStopsForRestart_SkipsRetainedEndpoint() + { + var restarting = false; + var session = new SystemProxySession(() => restarting); + var destination = new Uri("https://graph.microsoft.com/v1.0/me"); + var devProxy = new WebProxy("http://127.0.0.1:8000"); + + session.BeginRun(); + var run = session.Track(new CountingSystemProxyManager()); + run.Enable("127.0.0.1", 8000); + restarting = true; + run.Disable(); + + Assert.Null(new RetainedSystemProxyBypass(devProxy, session).GetProxy(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() + { + 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() + { + 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); + } + + [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; + public int EnableCount { get; private set; } + public int DisableCount { get; private set; } + + public void Enable(string? ipAddress, int port) => _ = TryEnable(ipAddress, port); + + public bool TryEnable(string? ipAddress, int port) + { + EnableCount++; + return EnableSucceeds; + } + + public bool DisableSucceeds { get; set; } = true; + public SystemProxyOwnership Ownership { get; set; } = SystemProxyOwnership.Owned; + + public void Disable() => _ = TryDisable(); + + public bool TryDisable() + { + DisableCount++; + return DisableSucceeds; + } + } } public class MacOSNetworkSetupTests diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 64845fda..27f02572 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -711,6 +711,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 ?? @@ -1294,6 +1298,13 @@ private static async Task CheckForNewVersionAsync(UpdateNotification updateNotif } } + // Also reports a registration kept because removing it failed, so stop --force and + // orphan recovery can still clean it up. Doesn't report a registration another + // instance took over, so stopping this one leaves the other's settings alone. + private bool IsSystemProxyRegistration(SystemProxySession? session) => + session?.YieldedToOtherOwner != true && + (_proxyConfiguration.AsSystemProxy || session?.HasRegistration == true); + private async Task WriteInstanceStateAsync(string apiUrl) { // The proxy engine publishes its actually-bound port back to the shared @@ -1315,7 +1326,7 @@ private async Task WriteInstanceStateAsync(string apiUrl) ProcessStartTime = StateManager.GetCurrentProcessStartTime(), ConfigFile = _proxyConfiguration.ConfigFile, Port = _proxyConfiguration.Port, - AsSystemProxy = _proxyConfiguration.AsSystemProxy, + AsSystemProxy = IsSystemProxyRegistration(_app?.Services.GetService()), SuppressTokenOutput = !ApiSecurity.ShouldDisplayToken }; diff --git a/DevProxy/Commands/StopCommand.cs b/DevProxy/Commands/StopCommand.cs index 7d674dba..2429971e 100644 --- a/DevProxy/Commands/StopCommand.cs +++ b/DevProxy/Commands/StopCommand.cs @@ -192,6 +192,18 @@ private async Task StopInstanceAsync(ProxyInstanceState state, bool force, return 1; } + // The instance deletes its own state once it has removed the system proxy. + // A system-proxy record it kept marks a registration it couldn't remove, + // so leave it for orphan recovery. + var orphans = await StateManager.GetOrphanedSystemProxyStatesAsync(cancellationToken); + if (FindKeptSystemProxyRecord(orphans, state) is not null) + { + reporter.Report(state.Pid, "stopped", + $"Dev Proxy (PID: {state.Pid}) stopped, but it couldn't remove the system proxy.", + "Run devproxy stop to restore the system proxy."); + return 0; + } + await StateManager.DeleteStateAsync(state, cancellationToken); reporter.Report(state.Pid, "stopped", $"Dev Proxy (PID: {state.Pid}) stopped."); return 0; @@ -212,6 +224,11 @@ private async Task StopInstanceAsync(ProxyInstanceState state, bool force, } } + // Match the process identity rather than StartedAt, which changes when the instance + // restarts its host after a config reload. + internal static ProxyInstanceState? FindKeptSystemProxyRecord(IEnumerable orphans, ProxyInstanceState stopped) => + orphans.FirstOrDefault(o => o.Pid == stopped.Pid && o.ProcessStartTime == stopped.ProcessStartTime); + private async Task ForceStopAsync(ProxyInstanceState state, StopReporter reporter, CancellationToken cancellationToken) { var identity = GetProcessIdentity(state); diff --git a/DevProxy/Extensions/IServiceCollectionExtensions.cs b/DevProxy/Extensions/IServiceCollectionExtensions.cs index 6dbd696f..21149db4 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(), @@ -66,6 +73,40 @@ 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 (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, @@ -82,7 +123,7 @@ static IServiceCollection AddApplicationServices( // Share the hosted instance so the command can release its startup-output gate. .AddSingleton() .AddHostedService(sp => sp.GetRequiredService()) - .AddKeyedSingleton(LanguageModelClientFactory.HttpClientServiceKey, (_, _) => LanguageModelClientFactory.CreateHttpClient()) + .AddKeyedSingleton(LanguageModelClientFactory.HttpClientServiceKey, (sp, _) => CreateLanguageModelHttpClient(sp)) .AddSingleton(sp => LanguageModelClientFactory.Create(sp, configuration)) .AddSingleton() .AddSingleton() @@ -97,7 +138,10 @@ static IServiceCollection AddApplicationServices( .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) - })); + })) + // Must follow the primary handler factory above so it configures the + // handler that factory creates. + .AddRetainedSystemProxyBypass(); _ = services.AddPlugins(configuration, options); diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index cb652794..8764e3bc 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; @@ -423,7 +424,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 @@ -433,7 +434,7 @@ static WebApplication BuildApplication( _ = builder.Configuration.ConfigureDevProxyConfig(options); try { - return BuildApplicationCore(builder, options, environment, proxyEnvironment); + return BuildApplicationCore(builder, options, environment, proxyEnvironment, systemProxySession); } catch { @@ -445,13 +446,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; @@ -490,11 +492,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(); @@ -540,16 +542,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; } @@ -562,7 +566,12 @@ static async Task RunProxyAsync(string[] args, DevProxyConfigOptions option } } while (shouldRestart); -if (DevProxyCommand.IsRootCommand) +// Don't leave the system proxy pointing at Dev Proxy when a restart failed. +var systemProxyReleased = systemProxySession.Release(new SystemProxyManager(NullLogger.Instance)); + +// When removing the system proxy failed, keep the instance state so orphan recovery +// can remove it later. +if (DevProxyCommand.IsRootCommand && systemProxyReleased) { await StateManager.DeleteStateAsync(); } 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/SystemProxyManager.cs b/DevProxy/Proxy/SystemProxyManager.cs index 5dab9e10..8cb09c3f 100644 --- a/DevProxy/Proxy/SystemProxyManager.cs +++ b/DevProxy/Proxy/SystemProxyManager.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Concurrent; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; @@ -60,7 +61,7 @@ internal enum SystemProxyRestoreResult /// it cannot be exercised on non-Windows hosts. /// /// -internal sealed class SystemProxyManager : ISystemProxyManager +internal sealed class SystemProxyManager : IConfirmingSystemProxyManager { private const string InternetSettingsKey = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings"; @@ -68,8 +69,11 @@ internal sealed class SystemProxyManager : ISystemProxyManager private const int InternetOptionRefresh = 37; private readonly ILogger _logger; + // Snapshot paths this process saved a snapshot to. Tracked per process rather than per + // instance: after a hot reload, the next host's manager doesn't register again when the + // endpoint is unchanged, but it must still leave a reset or takeover alone. + private static readonly ConcurrentDictionary _savedSnapshotPaths = new(StringComparer.Ordinal); private readonly string _snapshotPath; - private bool _savedSnapshot; public SystemProxyManager(ILogger logger) : this(logger, SystemProxySnapshotStore.DefaultPath) @@ -82,48 +86,62 @@ internal SystemProxyManager(ILogger logger, string snapshotP _snapshotPath = snapshotPath; } - 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()) { SaveSnapshot(CaptureWindows); - EnableWindows(SystemProxyAddress.ToHostPort(ipAddress, port)); + return EnableWindows(SystemProxyAddress.ToHostPort(ipAddress, port)); } - else if (OperatingSystem.IsMacOS()) + + if (OperatingSystem.IsMacOS()) { SaveSnapshot(CaptureMacOS); - _ = 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() => Disable(() => _ = Restore()); + public void Disable() => _ = TryDisable(); - internal void Disable(Action restore) + public bool TryDisable() => Disable(() => Restore() != SystemProxyRestoreResult.Failed); + + // The snapshot is gone or belongs to another process when 'system-proxy reset' + // already restored the settings or another instance took over. + public SystemProxyOwnership Ownership { - if (_savedSnapshot) + get { - // The snapshot is gone or belongs to another process when 'system-proxy reset' - // already restored the settings or another instance took over. Restoring now - // would undo that, so leave the settings alone. - if (SystemProxySnapshotStore.Load(_snapshotPath)?.Pid != Environment.ProcessId) + if (!_savedSnapshotPaths.ContainsKey(_snapshotPath)) { - return; + return SystemProxyOwnership.Owned; } - } - restore(); + var snapshot = SystemProxySnapshotStore.Load(_snapshotPath); + if (snapshot?.Pid == Environment.ProcessId) + { + return SystemProxyOwnership.Owned; + } + + return snapshot?.IsOwnerAlive() == true ? SystemProxyOwnership.TakenOver : SystemProxyOwnership.Released; + } } + // Returns false when the system proxy may still point to Dev Proxy. + internal bool Disable(Func restore) => + // Restoring after a reset or takeover would undo it, so leave the settings alone. + Ownership != SystemProxyOwnership.Owned || restore(); + /// /// Puts back the OS proxy settings recorded before Dev Proxy registered itself, or turns /// the system proxy off when nothing was recorded. Safe to call when Dev Proxy never @@ -226,7 +244,7 @@ internal void SaveSnapshot(Action capture) snapshot.Pid = Environment.ProcessId; snapshot.ProcessStartTime = StateManager.GetCurrentProcessStartTime(); SystemProxySnapshotStore.Save(_snapshotPath, snapshot); - _savedSnapshot = true; + _savedSnapshotPaths[_snapshotPath] = true; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException or InvalidOperationException or System.ComponentModel.Win32Exception) { @@ -321,7 +339,7 @@ private static void CaptureWindows(SystemProxySnapshot snapshot) } [SupportedOSPlatform("windows")] - private void EnableWindows(string hostPort) + private bool EnableWindows(string hostPort) { try { @@ -329,16 +347,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; } } diff --git a/DevProxy/Proxy/SystemProxySession.cs b/DevProxy/Proxy/SystemProxySession.cs new file mode 100644 index 00000000..9a9aeb38 --- /dev/null +++ b/DevProxy/Proxy/SystemProxySession.cs @@ -0,0 +1,300 @@ +// 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; + +/// +/// 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); + + /// + /// Removes Dev Proxy as the system proxy. Returns false when the settings may not + /// have been removed. + /// + bool TryDisable(); + + /// + /// Whether this process still owns the system proxy registration it made. + /// + SystemProxyOwnership Ownership { get; } +} + +internal enum SystemProxyOwnership +{ + /// This process owns the registration or hasn't registered. + Owned, + /// + /// The registration was released, for example by system-proxy reset, or its + /// owner exited without restoring the settings. + /// + Released, + /// Another running process took over the registration. + TakenOver, +} + +/// +/// 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 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 (), +/// 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. +/// +/// +/// 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 removing the registration fails, the session keeps it and retries in +/// . Until then, keeps the +/// instance state marked as the system proxy so stop --force and orphan +/// recovery can still clean it up. +/// 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. The bypass keeps covering that endpoint in the meantime. +/// +/// +internal sealed class SystemProxySession(Func isRestarting) +{ + private readonly Lock _lock = new(); + private IConfirmingSystemProxyManager? _currentManager; + // Endpoint confirmed as applied; null when not registered or when the last attempt failed. + private string? _appliedEndpoint; + // 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; + private bool _yieldedToOtherOwner; + + public SystemProxySession() : this(() => ConfigFileWatcher.IsRestarting) + { + } + + /// + /// The endpoint (host:port) the system proxy was confirmed to point to, or null. + /// + public string? AppliedEndpoint + { + get + { + lock (_lock) + { + return _appliedEndpoint; + } + } + } + + /// + /// Returns true when the system proxy may still point to Dev Proxy, including a + /// registration kept because removing it failed. + /// + public bool HasRegistration + { + get + { + lock (_lock) + { + return _registeredEndpoints.Count > 0; + } + } + } + + /// + /// Returns true when a restarted run skipped registering because another running + /// process took over the system proxy, so this instance isn't the system proxy. + /// + public bool YieldedToOtherOwner + { + get + { + lock (_lock) + { + return _yieldedToOtherOwner; + } + } + } + + /// + /// 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) + { + 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 _registeredEndpoints.Any(endpoint => + Uri.TryCreate($"http://{endpoint}", UriKind.Absolute, out var registered) && + string.Equals(registered.Host, proxy.Host, StringComparison.OrdinalIgnoreCase) && + registered.Port == proxy.Port); + } + } + + /// + /// 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(IConfirmingSystemProxyManager 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 (_registeredEndpoints.Count == 0 || _claimedInCurrentRun || _currentManager is null) + { + return; + } + + _ = TryRelease(_currentManager); + } + } + + /// + /// 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. Returns false + /// when the system proxy may still point to Dev Proxy. + /// + public bool Release(IConfirmingSystemProxyManager manager) + { + ArgumentNullException.ThrowIfNull(manager); + + lock (_lock) + { + return _registeredEndpoints.Count == 0 || TryRelease(manager); + } + } + + // Forgets the registration only once removing it succeeded, so a failed attempt + // keeps it for a later retry and for cleanup by other processes. + private bool TryRelease(IConfirmingSystemProxyManager manager) + { + if (!manager.TryDisable()) + { + return false; + } + + _appliedEndpoint = null; + _registeredEndpoints.Clear(); + return true; + } + + private void Enable(IConfirmingSystemProxyManager manager, string? ipAddress, int port) + { + var endpoint = SystemProxyAddress.ToHostPort(ipAddress, port); + lock (_lock) + { + _claimedInCurrentRun = true; + var ownership = manager.Ownership; + // A reload must not take the system proxy back from another running + // instance, so leave its settings alone and stop reporting this instance + // as the system proxy. + _yieldedToOtherOwner = ownership == SystemProxyOwnership.TakenOver; + if (_yieldedToOtherOwner) + { + _appliedEndpoint = null; + _registeredEndpoints.Clear(); + return; + } + + // After a reset, register again like a regular start. + if (string.Equals(_appliedEndpoint, endpoint, StringComparison.Ordinal) && + ownership == SystemProxyOwnership.Owned) + { + return; + } + + _ = _registeredEndpoints.Add(endpoint); + if (manager.TryEnable(ipAddress, port)) + { + _registeredEndpoints.Clear(); + _ = _registeredEndpoints.Add(endpoint); + _appliedEndpoint = endpoint; + } + else + { + _appliedEndpoint = null; + } + } + } + + private void Disable(IConfirmingSystemProxyManager manager) + { + lock (_lock) + { + if (_registeredEndpoints.Count > 0 && isRestarting()) + { + // The listener is stopping, so requests made during shutdown, such as + // report flushes, must bypass the kept registration. + _claimedInCurrentRun = false; + return; + } + + _ = TryRelease(manager); + } + } + + private sealed class TrackedSystemProxyManager(SystemProxySession session, IConfirmingSystemProxyManager manager) : ISystemProxyManager + { + public void Enable(string? ipAddress, int port) => session.Enable(manager, ipAddress, port); + + public void Disable() => session.Disable(manager); + } +} 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