From 99db3cceeb9c55ae24a39045b7aaddf038501ee2 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Mon, 23 Nov 2026 14:24:33 +0100 Subject: [PATCH 1/6] Add memory leak tests for request handling and hot reload Adds MemoryRetentionTests to DevProxy.Integration.Tests: - Hot reload: runs 20 generations through the real host-building code and config file watcher and checks that previous generations' WebApplication, service provider, command and plugins are collected. - Requests: proxies successful (mocked, passed-through, large bodies) and failed/cancelled requests through the Kestrel engine with the real console formatter, and checks proxy sessions are collected and the managed heap stays within a bound. - Canary tests add a deliberate leak and assert both checks catch it. The hot reload and failed/cancelled request checks are skipped until #2153 and #2151 fix the leaks they detect on main. To build hosts like Program.cs does, the host-building functions move from Program.cs into ProxyHost, unchanged. Closes #2160 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../DevProxy.Integration.Tests.csproj | 11 +- DevProxy.Integration.Tests/FakeOrigin.cs | 21 +- .../MemoryRetentionTests.cs | 610 ++++++++++++++++++ DevProxy/DevProxy.csproj | 1 + DevProxy/Program.cs | 119 +--- DevProxy/ProxyHost.cs | 137 ++++ 6 files changed, 775 insertions(+), 124 deletions(-) create mode 100644 DevProxy.Integration.Tests/MemoryRetentionTests.cs create mode 100644 DevProxy/ProxyHost.cs diff --git a/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj b/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj index c2cb9f1c..d08f70b9 100644 --- a/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj +++ b/DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj @@ -7,8 +7,10 @@ false true - $(NoWarn);CA1707;CA1861 + arrays in assertions are fine in tests. The DevProxy reference brings in the + VS threading analyzers, whose VSTHRD003/VSTHRD202 rules flag test methods that + await helpers or tasks they didn't start. --> + $(NoWarn);CA1707;CA1861;VSTHRD003;VSTHRD202 @@ -31,12 +33,13 @@ - - + + + diff --git a/DevProxy.Integration.Tests/FakeOrigin.cs b/DevProxy.Integration.Tests/FakeOrigin.cs index 034d6201..a5c50395 100644 --- a/DevProxy.Integration.Tests/FakeOrigin.cs +++ b/DevProxy.Integration.Tests/FakeOrigin.cs @@ -29,6 +29,8 @@ namespace DevProxy.Integration.Tests; /// GET /big/{n} → 200, n bytes of 'A' (large finite body) /// GET /json → 200 application/json, a 2-element array /// GET /socket-b → WebSocket sends "rewritten" +/// * /abort → aborts the connection without a response +/// * /delay/{ms} → 200 "delayed" after {ms} milliseconds /// /// internal sealed class FakeOrigin : IAsyncDisposable @@ -50,7 +52,11 @@ private FakeOrigin(WebApplication app, int port, System.Collections.Concurrent.C _received = received; } - public static async Task StartAsync() + /// + /// Whether to record received requests in . Turn off for + /// high-volume tests, where the recording would grow memory with every request. + /// + public static async Task StartAsync(bool recordRequests = true) { var port = NetUtil.GetFreePort(); var builder = WebApplication.CreateEmptyBuilder(new WebApplicationOptions()); @@ -67,7 +73,10 @@ public static async Task StartAsync() var received = new System.Collections.Concurrent.ConcurrentQueue(); app.Use(async (ctx, next) => { - received.Enqueue(new ReceivedRequest(ctx.Request.Method, ctx.Request.Path + ctx.Request.QueryString)); + if (recordRequests) + { + received.Enqueue(new ReceivedRequest(ctx.Request.Method, ctx.Request.Path + ctx.Request.QueryString)); + } await next().ConfigureAwait(false); }); @@ -120,6 +129,14 @@ public static async Task StartAsync() new { id = 2, name = "beta" }, })); + app.Map("/abort", (HttpContext ctx) => ctx.Abort()); + + app.Map("/delay/{ms:int}", async (int ms, HttpContext ctx) => + { + await Task.Delay(ms, ctx.RequestAborted).ConfigureAwait(false); + return Results.Text("delayed"); + }); + app.Map("/socket-b", async context => { if (!context.WebSockets.IsWebSocketRequest) diff --git a/DevProxy.Integration.Tests/MemoryRetentionTests.cs b/DevProxy.Integration.Tests/MemoryRetentionTests.cs new file mode 100644 index 00000000..d3f337e9 --- /dev/null +++ b/DevProxy.Integration.Tests/MemoryRetentionTests.cs @@ -0,0 +1,610 @@ +// 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.Collections.Concurrent; +using System.Globalization; +using System.Net; +using System.Runtime.CompilerServices; +using System.Text; +using DevProxy.Abstractions.Plugins; +using DevProxy.Abstractions.Proxy; +using DevProxy.Commands; +using DevProxy.Logging; +using DevProxy.Plugins.Mocking; +using DevProxy.Proxy; +using DevProxy.Proxy.Kestrel; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Logging.Console; +using Microsoft.Extensions.Options; +using Xunit; +using Xunit.Abstractions; + +namespace DevProxy.Integration.Tests; + +/// +/// Checks that Dev Proxy doesn't keep memory alive across proxied requests and hot +/// reloads. The checks use where the retained objects are +/// reachable, so they're exact, and otherwise compare the managed heap after a forced +/// full collection, which is stable on CI runners where timing isn't. +/// +/// Each check has a canary test that adds a deliberate leak (a plugin that appends +/// every request or generation to a static list) and asserts the check catches it, so +/// the checks can't silently pass because they measure nothing. +/// +public sealed class MemoryRetentionTests(ITestOutputHelper output) +{ + private const string HotReloadSkipReason = + "Every previous hot-reload generation stays reachable on main. Passes with https://github.com/dotnet/dev-proxy/pull/2153."; + + private const string FailedRequestsSkipReason = + "Request logs of failed and cancelled requests stay buffered on main. Passes with https://github.com/dotnet/dev-proxy/pull/2151."; + + private const int HotReloadGenerations = 20; + + // Allows for pools that keep growing towards their peak use long after warm-up. + // Heap snapshots show 10,000-30,000 requests adding 2-4 MB, nearly all of it 4 KB + // blocks in Kestrel's memory pool. A leak of one small object per request would + // stay under it, which is why the tests also track sessions with weak references. + private const long AllowedGrowthBytes = 8 * 1024 * 1024; + + private static readonly HttpClient SharedHttpClient = new(); + private static readonly TestProxyConfiguration ProxyConfig = new(); + + private readonly ITestOutputHelper _output = output; + + [Fact(Skip = HotReloadSkipReason)] + public async Task HotReload_ReleasesPreviousGenerations() + { + var result = await MeasureHotReloadAsync(HotReloadGenerations, leakGenerations: false); + + Assert.True( + result.RetainedGenerations == 0, + $"{result.RetainedGenerations} of {result.Generations} hot-reload generations are still reachable after a full collection ({result.RetainedObjects})."); + } + + [Fact] + public async Task HotReload_DetectsGenerationsHeldByALeak() + { + var result = await MeasureHotReloadAsync(generations: 3, leakGenerations: true); + + Assert.Equal(result.Generations, result.RetainedGenerations); + } + + [Fact] + public async Task Requests_DoNotRetainMemory() + { + var result = await MeasureRequestsAsync( + RequestMix.Successful, warmupRequests: 1_000, measuredRequests: 10_000, leakSessions: false); + + Assert.True( + result.RetainedSessions == 0, + $"{result.RetainedSessions} of {result.TrackedSessions} proxy sessions are still reachable after their requests completed."); + Assert.True( + result.GrowthBytes < AllowedGrowthBytes, + $"The managed heap grew by {result.GrowthBytes:N0} bytes over {result.MeasuredRequests:N0} requests; allowed: {AllowedGrowthBytes:N0}."); + } + + [Fact(Skip = FailedRequestsSkipReason)] + public async Task FailedAndCancelledRequests_DoNotRetainMemory() + { + var result = await MeasureRequestsAsync( + RequestMix.FailedAndCancelled, warmupRequests: 200, measuredRequests: 1_000, leakSessions: false); + + Assert.True( + result.RetainedSessions == 0, + $"{result.RetainedSessions} of {result.TrackedSessions} proxy sessions are still reachable after their requests failed or were cancelled."); + Assert.True( + result.GrowthBytes < AllowedGrowthBytes, + $"The managed heap grew by {result.GrowthBytes:N0} bytes over {result.MeasuredRequests:N0} requests; allowed: {AllowedGrowthBytes:N0}."); + } + + [Fact] + public async Task Requests_DetectSessionsHeldByALeak() + { + var result = await MeasureRequestsAsync( + RequestMix.Successful, warmupRequests: 100, measuredRequests: 1_000, leakSessions: true); + + Assert.Equal(result.TrackedSessions, result.RetainedSessions); + Assert.True( + result.GrowthBytes >= AllowedGrowthBytes, + $"A plugin that keeps every session grew the managed heap by only {result.GrowthBytes:N0} bytes; the check needs at least {AllowedGrowthBytes:N0} to catch it."); + } + + #region Hot reload + + private sealed record HotReloadResult(int Generations, int RetainedGenerations, string RetainedObjects); + + private async Task MeasureHotReloadAsync(int generations, bool leakGenerations) + { + await using var origin = await FakeOrigin.StartAsync(recordRequests: false); + var configDir = Directory.CreateTempSubdirectory("devproxy-memory-"); + var configPath = Path.Combine(configDir.FullName, "devproxyrc.json"); + await File.WriteAllTextAsync(Path.Combine(configDir.FullName, "mocks.json"), MocksFile(origin.Host)); + await File.WriteAllTextAsync(configPath, ConfigFile(origin.Host, generation: 0)); + + string[] args = [DevProxyCommand.ConfigFileOptionName, configPath]; + var options = new DevProxyConfigOptions(); + options.ParseOptions(args); + var proxyEnvironment = new HttpProxyEnvironment(); + + var generationRefs = new List(); + try + { + for (var generation = 1; generation <= generations; generation++) + { + generationRefs.Add(await RunGenerationAsync( + args, options, proxyEnvironment, configPath, origin.Host, generation, leakGenerations)); + } + + await CollectUntilAsync(() => generationRefs.All(g => !g.IsAlive)); + var retained = generationRefs.Where(g => g.IsAlive).ToArray(); + var retainedObjects = string.Join( + ", ", + retained.SelectMany(g => g.AliveObjects()).GroupBy(n => n).Select(g => $"{g.Key} x{g.Count()}")); + + _output.WriteLine($"Hot-reload generations checked: {generations}"); + _output.WriteLine($"Hot-reload generations retained: {retained.Length}"); + if (retained.Length > 0) + { + _output.WriteLine($"Retained objects: {retainedObjects}"); + } + + return new(generations, retained.Length, retainedObjects); + } + finally + { + LeakedGenerations.Clear(); + ConfigFileWatcher.Reset(); + try + { + configDir.Delete(recursive: true); + } + catch (IOException) + { + // A late file watcher can still hold the folder; it's a temp folder. + } + } + } + + /// The deliberate leak for the hot-reload canary. + private static readonly List LeakedGenerations = []; + + private sealed class GenerationRefs(Dictionary objects) + { + public bool IsAlive => objects.Values.Any(r => r.IsAlive); + + public IEnumerable AliveObjects() => objects.Where(o => o.Value.IsAlive).Select(o => o.Key); + } + + /// + /// Runs one generation the way Program.cs does on hot reload: builds the host from + /// the config file, starts it, proxies a few requests, then rewrites the config file + /// and waits for the config watcher to stop the host. Returns only weak references so + /// nothing in this frame keeps the generation alive. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private static async Task RunGenerationAsync( + string[] args, + DevProxyConfigOptions options, + HttpProxyEnvironment proxyEnvironment, + string configPath, + string originHost, + int generation, + bool leakGeneration) + { + ConfigFileWatcher.Reset(); + using var environment = new ProcessEnvironment(); + var app = ProxyHost.BuildApplication(options, environment, proxyEnvironment); + try + { + // Mirror the start-up steps of DevProxyCommand.InvokeAsync that set up plugins, + // without the ones that write state for other Dev Proxy commands to find. + var command = app.Services.GetRequiredService(); + var plugins = app.Services.GetServices().ToArray(); + Assert.NotEmpty(plugins); + var optionsLoadedArgs = new OptionsLoadedArgs(command.Parse(args)); + foreach (var plugin in plugins.Where(p => p.Enabled)) + { + plugin.OptionsLoaded(optionsLoadedArgs); + } + if (leakGeneration) + { + LeakedGenerations.Add(plugins); + } + + var stopping = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var stoppingRegistration = app.Lifetime.ApplicationStopping.Register(() => stopping.TrySetResult()); + + await app.StartAsync(); + var engines = app.Services.GetServices().OfType().ToArray(); + Assert.All(await Task.WhenAll(engines.Select(e => e.Started)), Assert.True); + + var proxyPort = app.Services.GetRequiredService().Port; + await SendGenerationRequestsAsync(proxyPort, originHost); + + // The watcher debounces changes and may start after the first write, so keep + // rewriting until it restarts the host. + for (var attempt = 0; !stopping.Task.IsCompleted; attempt++) + { + Assert.True(attempt < 10, $"Generation {generation} didn't restart after the config file changed."); + await File.WriteAllTextAsync(configPath, ConfigFile(originHost, generation * 100 + attempt)); + _ = await Task.WhenAny(stopping.Task, Task.Delay(TimeSpan.FromSeconds(3))); + } + Assert.True(ConfigFileWatcher.IsRestarting); + + var objects = new Dictionary + { + ["WebApplication"] = new(app), + ["IServiceProvider"] = new(app.Services), + ["DevProxyCommand"] = new(command), + }; + foreach (var plugin in plugins) + { + objects[plugin.Name] = new(plugin); + } + return new(objects); + } + finally + { + await app.StopAsync(); + await app.DisposeAsync(); + } + } + + private static async Task SendGenerationRequestsAsync(int proxyPort, string originHost) + { + using var handler = new HttpClientHandler + { + Proxy = new WebProxy($"http://127.0.0.1:{proxyPort.ToString(CultureInfo.InvariantCulture)}"), + UseProxy = true, + }; + using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) }; + + using (var mocked = await client.GetAsync(new Uri($"http://{originHost}/mocked"))) + { + Assert.Equal(HttpStatusCode.Created, mocked.StatusCode); + } + using (var passthrough = await client.GetAsync(new Uri($"http://{originHost}/get"))) + { + Assert.Equal(HttpStatusCode.OK, passthrough.StatusCode); + } + } + + private static string ConfigFile(string originHost, int generation) => $$""" + { + "plugins": [ + { + "name": "MockResponsePlugin", + "enabled": true, + "pluginPath": "{{JsonEncodedPluginPath()}}", + "configSection": "mocksPlugin" + } + ], + "urlsToWatch": [ + "http://{{originHost}}/*" + ], + "mocksPlugin": { + "mocksFile": "mocks.json" + }, + "port": 0, + "apiPort": 0, + "asSystemProxy": false, + "installCert": false, + "logLevel": "error", + "newVersionNotification": "none", + "generation": {{generation.ToString(CultureInfo.InvariantCulture)}} + } + """; + + private static string MocksFile(string originHost) => $$""" + { + "mocks": [ + { + "request": { "url": "http://{{originHost}}/mocked", "method": "GET" }, + "response": { "statusCode": 201, "body": "mocked" } + } + ] + } + """; + + private static string JsonEncodedPluginPath() => + System.Text.Json.JsonEncodedText.Encode(LocatePluginsDll()).ToString(); + + /// + /// Walks up from the test assembly output to the repo root and resolves the plugins + /// the host's build copies next to it, for the same configuration (Debug/Release). + /// + private static string LocatePluginsDll() + { + var config = +#if DEBUG + "Debug"; +#else + "Release"; +#endif + for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) + { + var candidate = Path.Combine(dir.FullName, "DevProxy", "bin", config, "net10.0", "plugins", "DevProxy.Plugins.dll"); + if (File.Exists(candidate)) + { + return candidate; + } + } + + throw new FileNotFoundException("Couldn't find DevProxy.Plugins.dll in the DevProxy build output. Build DevProxy.sln first."); + } + + #endregion + + #region Requests + + private enum RequestMix + { + /// Mocked and passed-through requests, with large request and response bodies. + Successful, + + /// Requests the origin fails and requests the client cancels. + FailedAndCancelled, + } + + private sealed record RequestsResult( + int MeasuredRequests, long GrowthBytes, int TrackedSessions, int RetainedSessions); + + private const int Concurrency = 8; + private const int TrackedRequests = 200; + private const int RequestBodyBytes = 64 * 1024; + private const int ResponseBodyBytes = 256 * 1024; + + private async Task MeasureRequestsAsync( + RequestMix mix, int warmupRequests, int measuredRequests, bool leakSessions) + { + await using var origin = await FakeOrigin.StartAsync(recordRequests: false); + var urls = KestrelProxyHarness.BuildUrlsToWatch(origin.Host); + + var probe = new SessionProbePlugin(urls, leakSessions); + var mockPlugin = new MockResponsePlugin( + SharedHttpClient, + NullLogger.Instance, + urls, + ProxyConfig, + PluginConfig.FromJson($$""" + { + "mocks": [ + { + "request": { "url": "http://{{origin.Host}}/mocked", "method": "GET" }, + "response": { "statusCode": 201, "body": "mocked" } + } + ] + } + """)); + + // Log through the real console formatter, which buffers each request's log lines + // until the request finishes, into a writer that discards the output. + using var loggerProvider = new FormatterLoggerProvider(new ProxyConsoleFormatter( + Options.Create(new ProxyConsoleFormatterOptions { IncludeScopes = true }))); + using var loggerFactory = LoggerFactory.Create(builder => builder + .SetMinimumLevel(LogLevel.Trace) + .AddProvider(loggerProvider)); + + try + { + await using var proxy = await KestrelProxyHarness.StartAsync( + origin.Host, [probe, mockPlugin], loggerFactory); + + await SendRequestsAsync(proxy, origin.Host, mix, warmupRequests); + var before = await MeasureHeapAsync(); + + await SendRequestsAsync(proxy, origin.Host, mix, measuredRequests); + var after = await MeasureHeapAsync(); + + probe.Tracking = true; + await SendRequestsAsync(proxy, origin.Host, mix, TrackedRequests); + probe.Tracking = false; + + var tracked = probe.TrackedSessions.ToArray(); + await CollectUntilAsync(() => tracked.All(s => !s.IsAlive)); + var retained = tracked.Count(s => s.IsAlive); + + var growth = after - before; + _output.WriteLine($"Request mix: {mix}"); + _output.WriteLine($"Warm-up requests: {warmupRequests:N0}"); + _output.WriteLine($"Measured requests: {measuredRequests:N0}"); + _output.WriteLine($"Managed heap after warm-up: {before:N0} bytes"); + _output.WriteLine($"Managed heap after measured requests: {after:N0} bytes"); + _output.WriteLine($"Bytes retained: {growth:N0} (allowed: {AllowedGrowthBytes:N0})"); + _output.WriteLine($"Sessions tracked: {tracked.Length}, retained: {retained}"); + + return new(measuredRequests, growth, tracked.Length, retained); + } + finally + { + SessionProbePlugin.LeakedSessions.Clear(); + } + } + + private static async Task SendRequestsAsync(KestrelProxyHarness proxy, string originHost, RequestMix mix, int count) + { + // A client per phase, so that closing its connections releases anything the proxy + // keeps per connection before the heap is measured. + using var client = proxy.CreateHttpClient(); + var next = -1; + var workers = Enumerable.Range(0, Concurrency).Select(async _ => + { + int i; + while ((i = Interlocked.Increment(ref next)) < count) + { + await SendRequestAsync(client, originHost, mix, i); + } + }); + await Task.WhenAll(workers); + } + + private static readonly byte[] RequestBody = Encoding.ASCII.GetBytes(new string('B', RequestBodyBytes)); + + private static async Task SendRequestAsync(HttpClient client, string originHost, RequestMix mix, int i) + { + if (mix == RequestMix.Successful) + { + switch (i % 4) + { + case 0: + { + using var response = await client.GetAsync(new Uri($"http://{originHost}/mocked")); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + _ = await response.Content.ReadAsByteArrayAsync(); + break; + } + case 1: + { + using var response = await client.GetAsync(new Uri($"http://{originHost}/get")); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + _ = await response.Content.ReadAsByteArrayAsync(); + break; + } + case 2: + { + using var content = new ByteArrayContent(RequestBody); + using var response = await client.PostAsync(new Uri($"http://{originHost}/echo"), content); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(RequestBodyBytes, (await response.Content.ReadAsByteArrayAsync()).Length); + break; + } + default: + { + using var response = await client.GetAsync(new Uri($"http://{originHost}/big/{ResponseBodyBytes}")); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(ResponseBodyBytes, (await response.Content.ReadAsByteArrayAsync()).Length); + break; + } + } + return; + } + + if (i % 2 == 0) + { + // The origin drops the connection, so the proxy answers with a gateway error. + using var content = new ByteArrayContent(RequestBody); + using var response = await client.PostAsync(new Uri($"http://{originHost}/abort"), content); + Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode); + } + else + { + // The client gives up while the origin is still working on the response. + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + using var content = new ByteArrayContent(RequestBody); + _ = await Assert.ThrowsAnyAsync( + () => client.PostAsync(new Uri($"http://{originHost}/delay/2000"), content, cts.Token)); + } + } + + private static async Task MeasureHeapAsync() + { + // Let the proxy finish tearing down connections the client just closed. + await Task.Delay(250); + _ = GC.GetTotalMemory(forceFullCollection: true); + return GC.GetTotalMemory(forceFullCollection: true); + } + + /// + /// Tracks proxy sessions with weak references while is on. + /// When created to leak, it also keeps every session in a static list: the + /// deliberate leak the canary tests use. + /// + private sealed class SessionProbePlugin(ISet urlsToWatch, bool leak) + : BasePlugin(NullLogger.Instance, urlsToWatch) + { + public static readonly ConcurrentQueue LeakedSessions = new(); + + public override string Name => nameof(SessionProbePlugin); + + public volatile bool Tracking; + + public ConcurrentQueue TrackedSessions { get; } = new(); + + public override Task BeforeRequestAsync(ProxyRequestArgs e, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(e); + if (leak) + { + LeakedSessions.Enqueue(e.ProxySession); + } + if (Tracking) + { + TrackedSessions.Enqueue(new(e.ProxySession)); + } + return Task.CompletedTask; + } + } + + /// + /// Writes log entries through a console formatter like the console logger does, but + /// synchronously and into . + /// + private sealed class FormatterLoggerProvider(ConsoleFormatter formatter) : ILoggerProvider, ISupportExternalScope + { + private IExternalScopeProvider? _scopeProvider; + + public ILogger CreateLogger(string categoryName) => new FormatterLogger(this, categoryName); + + public void SetScopeProvider(IExternalScopeProvider scopeProvider) => _scopeProvider = scopeProvider; + + public void Dispose() + { + } + + private sealed class FormatterLogger(FormatterLoggerProvider provider, string category) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => + provider._scopeProvider?.Push(state); + + public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) + { + var entry = new Microsoft.Extensions.Logging.Abstractions.LogEntry( + logLevel, category, eventId, state, exception, formatter); + provider.Write(entry); + } + } + + private void Write(in Microsoft.Extensions.Logging.Abstractions.LogEntry entry) + { + lock (formatter) + { + formatter.Write(entry, _scopeProvider, TextWriter.Null); + } + } + } + + #endregion + + /// + /// Forces full collections until holds, giving background + /// work that still references the objects (connection teardown, file watchers) a + /// moment to finish. Returns without failing; callers assert what's left. + /// + private static async Task CollectUntilAsync(Func released) + { + for (var attempt = 0; attempt < 20; attempt++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + if (released()) + { + return; + } + await Task.Delay(100); + } + } +} diff --git a/DevProxy/DevProxy.csproj b/DevProxy/DevProxy.csproj index e4f7ee0a..67853334 100644 --- a/DevProxy/DevProxy.csproj +++ b/DevProxy/DevProxy.csproj @@ -51,6 +51,7 @@ + diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index 7a07a4c8..a838ea80 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -9,11 +9,11 @@ using DevProxy.State; using System.Diagnostics; using System.Globalization; -using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; +using static DevProxy.ProxyHost; // Keep management files discoverable even when env overrides change user data paths. _ = StateManager.GetConfigFolder(); @@ -301,29 +301,6 @@ static string FormatJsonResultEntry(object data) return JsonSerializer.Serialize(entry, jsonlOptions); } -/// -/// Formats a log entry matching the JSONL envelope produced by JsonConsoleFormatter: -/// {"type":"log","level":"...","message":"...","timestamp":"..."} -/// -static string FormatJsonLogEntry(string level, string message) -{ -#pragma warning disable CA1869 // Called at most once per process lifetime - var jsonlOptions = new JsonSerializerOptions - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }; -#pragma warning restore CA1869 - var entry = new - { - type = "log", - level, - message, - timestamp = DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture) - }; - return JsonSerializer.Serialize(entry, jsonlOptions); -} - // The daemon logs JSONL, but output it doesn't control (like unhandled // exception stack traces) can end up in its log too. Keep JSON entries as-is // and wrap other runs of lines so the output stays valid JSONL. @@ -390,19 +367,6 @@ static bool IsJsonObject(string line) } } -static bool IsJsonOutputRequested(string[] args) -{ - for (var i = 0; i < args.Length; i++) - { - if (string.Equals(args[i], DevProxyCommand.OutputOptionName, StringComparison.OrdinalIgnoreCase) && - i + 1 < args.Length) - { - return string.Equals(args[i + 1], "json", StringComparison.OrdinalIgnoreCase); - } - } - return false; -} - static string EscapeArgument(string arg) { // Simple escaping for command line arguments @@ -413,87 +377,6 @@ static string EscapeArgument(string arg) return arg; } -static void WriteUnresolvedEnvironmentVariables(IConfiguration configuration, DevProxyConfigOptions options) -{ - var isJson = options.Output == DevProxy.Abstractions.Proxy.OutputFormat.Json || IsJsonOutputRequested(Environment.GetCommandLineArgs()); - foreach (var provider in ((IConfigurationRoot)configuration).Providers.OfType()) - { - foreach (var name in provider.UnresolvedEnvironmentVariables) - { - var message = $"Environment variable {name} referenced in {provider.Path ?? "configuration file"} isn't set. Leaving the placeholder as-is"; - Console.Error.WriteLine(isJson ? FormatJsonLogEntry("warning", message) : message); - } - } -} - -static WebApplication BuildApplication( - DevProxyConfigOptions options, ProcessEnvironment environment, HttpProxyEnvironment proxyEnvironment) -{ - // 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 - // 2. ConfigureDevProxyConfig clears all configuration sources anyway and only uses JSON config files - var builder = WebApplication.CreateBuilder(); - - _ = builder.Configuration.ConfigureDevProxyConfig(options); - try - { - return BuildApplicationCore(builder, options, environment, proxyEnvironment); - } - catch - { - // config values with unresolved placeholders can fail startup before - // they're logged, so report them to help troubleshoot - WriteUnresolvedEnvironmentVariables(builder.Configuration, options); - throw; - } -} - -static WebApplication BuildApplicationCore( - WebApplicationBuilder builder, DevProxyConfigOptions options, ProcessEnvironment environment, HttpProxyEnvironment proxyEnvironment) -{ - 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.ConfigureDevProxyServices(builder.Configuration, options, allowedOrigins); - - var defaultApiPort = 8897; - var apiPort = options.ApiPort ?? - builder.Configuration.GetValue("apiPort", defaultApiPort); - var apiAddressText = options.ApiIpAddress ?? builder.Configuration.GetValue("apiIpAddress", "127.0.0.1"); - if (!IPAddress.TryParse(apiAddressText, out var apiAddress)) - { - throw new InvalidOperationException("apiIpAddress must be an IP address, for example 127.0.0.1 or ::1."); - } - _ = builder.WebHost.ConfigureKestrel(options => - { - options.Listen(apiAddress, apiPort); - }); - - var app = builder.Build(); - - foreach (var provider in ((IConfigurationRoot)builder.Configuration).Providers.OfType()) - { - EnvironmentVariablePlaceholders.LogUnresolvedVariables( - app.Logger, provider.UnresolvedEnvironmentVariables, provider.Path ?? "configuration file"); - } - - if (changedProxyVariables.Length > 0) - { - app.Logger.LogWarning( - "Proxy-routing environment variables changed ({EnvironmentVariables}). HTTP proxy settings are cached and cannot be refreshed by hot reload. Stop Dev Proxy and start it again to apply these changes.", - string.Join(", ", changedProxyVariables)); - } - - _ = app.Use((context, next) => ApiSecurity.CheckOriginAsync(context, next, allowedOrigins)); - _ = app.UseCors(); - _ = app.Use(ApiSecurity.AuthenticateAsync); - _ = app.MapControllers(); - - return app; -} - static async Task RunProxyAsync(string[] args, DevProxyConfigOptions options, HttpProxyEnvironment proxyEnvironment) { // Keep overrides through host shutdown, but restore inherited values before a hot reload. diff --git a/DevProxy/ProxyHost.cs b/DevProxy/ProxyHost.cs new file mode 100644 index 00000000..931d98a4 --- /dev/null +++ b/DevProxy/ProxyHost.cs @@ -0,0 +1,137 @@ +// 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.Utils; +using DevProxy.Commands; +using DevProxy.Proxy; +using System.Globalization; +using System.Net; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace DevProxy; + +/// +/// Builds the web application for one run of the proxy. Program.cs builds a new one +/// for each hot reload, so tests can use this to exercise the same build path. +/// +static class ProxyHost +{ + /// + /// Formats a log entry matching the JSONL envelope produced by JsonConsoleFormatter: + /// {"type":"log","level":"...","message":"...","timestamp":"..."} + /// + internal static string FormatJsonLogEntry(string level, string message) + { +#pragma warning disable CA1869 // Called at most once per process lifetime + var jsonlOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; +#pragma warning restore CA1869 + var entry = new + { + type = "log", + level, + message, + timestamp = DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture) + }; + return JsonSerializer.Serialize(entry, jsonlOptions); + } + + internal static bool IsJsonOutputRequested(string[] args) + { + for (var i = 0; i < args.Length; i++) + { + if (string.Equals(args[i], DevProxyCommand.OutputOptionName, StringComparison.OrdinalIgnoreCase) && + i + 1 < args.Length) + { + return string.Equals(args[i + 1], "json", StringComparison.OrdinalIgnoreCase); + } + } + return false; + } + + internal static void WriteUnresolvedEnvironmentVariables(IConfiguration configuration, DevProxyConfigOptions options) + { + var isJson = options.Output == DevProxy.Abstractions.Proxy.OutputFormat.Json || IsJsonOutputRequested(Environment.GetCommandLineArgs()); + foreach (var provider in ((IConfigurationRoot)configuration).Providers.OfType()) + { + foreach (var name in provider.UnresolvedEnvironmentVariables) + { + var message = $"Environment variable {name} referenced in {provider.Path ?? "configuration file"} isn't set. Leaving the placeholder as-is"; + Console.Error.WriteLine(isJson ? FormatJsonLogEntry("warning", message) : message); + } + } + } + + internal static WebApplication BuildApplication( + DevProxyConfigOptions options, ProcessEnvironment environment, HttpProxyEnvironment proxyEnvironment) + { + // 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 + // 2. ConfigureDevProxyConfig clears all configuration sources anyway and only uses JSON config files + var builder = WebApplication.CreateBuilder(); + + _ = builder.Configuration.ConfigureDevProxyConfig(options); + try + { + return BuildApplicationCore(builder, options, environment, proxyEnvironment); + } + catch + { + // config values with unresolved placeholders can fail startup before + // they're logged, so report them to help troubleshoot + WriteUnresolvedEnvironmentVariables(builder.Configuration, options); + throw; + } + } + + internal static WebApplication BuildApplicationCore( + WebApplicationBuilder builder, DevProxyConfigOptions options, ProcessEnvironment environment, HttpProxyEnvironment proxyEnvironment) + { + 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.ConfigureDevProxyServices(builder.Configuration, options, allowedOrigins); + + var defaultApiPort = 8897; + var apiPort = options.ApiPort ?? + builder.Configuration.GetValue("apiPort", defaultApiPort); + var apiAddressText = options.ApiIpAddress ?? builder.Configuration.GetValue("apiIpAddress", "127.0.0.1"); + if (!IPAddress.TryParse(apiAddressText, out var apiAddress)) + { + throw new InvalidOperationException("apiIpAddress must be an IP address, for example 127.0.0.1 or ::1."); + } + _ = builder.WebHost.ConfigureKestrel(options => + { + options.Listen(apiAddress, apiPort); + }); + + var app = builder.Build(); + + foreach (var provider in ((IConfigurationRoot)builder.Configuration).Providers.OfType()) + { + EnvironmentVariablePlaceholders.LogUnresolvedVariables( + app.Logger, provider.UnresolvedEnvironmentVariables, provider.Path ?? "configuration file"); + } + + if (changedProxyVariables.Length > 0) + { + app.Logger.LogWarning( + "Proxy-routing environment variables changed ({EnvironmentVariables}). HTTP proxy settings are cached and cannot be refreshed by hot reload. Stop Dev Proxy and start it again to apply these changes.", + string.Join(", ", changedProxyVariables)); + } + + _ = app.Use((context, next) => ApiSecurity.CheckOriginAsync(context, next, allowedOrigins)); + _ = app.UseCors(); + _ = app.Use(ApiSecurity.AuthenticateAsync); + _ = app.MapControllers(); + + return app; + } +} From 4e8cc575b998c0052e23fea6b4d4e03e115e7cc4 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Mon, 23 Nov 2026 14:32:01 +0100 Subject: [PATCH 2/6] Fail memory retention checks on an empty session sample Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Integration.Tests/MemoryRetentionTests.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/DevProxy.Integration.Tests/MemoryRetentionTests.cs b/DevProxy.Integration.Tests/MemoryRetentionTests.cs index d3f337e9..affd0a24 100644 --- a/DevProxy.Integration.Tests/MemoryRetentionTests.cs +++ b/DevProxy.Integration.Tests/MemoryRetentionTests.cs @@ -407,6 +407,16 @@ private async Task MeasureRequestsAsync( probe.Tracking = false; var tracked = probe.TrackedSessions.ToArray(); + // Every successful request reaches the proxy; a cancelled one may not, but + // an empty sample would let the checks pass without checking anything. + if (mix == RequestMix.Successful) + { + Assert.Equal(TrackedRequests, tracked.Length); + } + else + { + Assert.NotEmpty(tracked); + } await CollectUntilAsync(() => tracked.All(s => !s.IsAlive)); var retained = tracked.Count(s => s.IsAlive); From 77574d45c7cf467d3a2fe11df75b9abb6c7a227b Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Tue, 24 Nov 2026 11:01:25 +0100 Subject: [PATCH 3/6] Suppress xUnit1004 on memory tests skipped pending fixes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Integration.Tests/MemoryRetentionTests.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/DevProxy.Integration.Tests/MemoryRetentionTests.cs b/DevProxy.Integration.Tests/MemoryRetentionTests.cs index affd0a24..3a9b635d 100644 --- a/DevProxy.Integration.Tests/MemoryRetentionTests.cs +++ b/DevProxy.Integration.Tests/MemoryRetentionTests.cs @@ -57,7 +57,10 @@ public sealed class MemoryRetentionTests(ITestOutputHelper output) private readonly ITestOutputHelper _output = output; + // Skipped until the linked fix merges; remove the skip and the suppression then. +#pragma warning disable xUnit1004 [Fact(Skip = HotReloadSkipReason)] +#pragma warning restore xUnit1004 public async Task HotReload_ReleasesPreviousGenerations() { var result = await MeasureHotReloadAsync(HotReloadGenerations, leakGenerations: false); @@ -89,7 +92,10 @@ public async Task Requests_DoNotRetainMemory() $"The managed heap grew by {result.GrowthBytes:N0} bytes over {result.MeasuredRequests:N0} requests; allowed: {AllowedGrowthBytes:N0}."); } + // Skipped until the linked fix merges; remove the skip and the suppression then. +#pragma warning disable xUnit1004 [Fact(Skip = FailedRequestsSkipReason)] +#pragma warning restore xUnit1004 public async Task FailedAndCancelledRequests_DoNotRetainMemory() { var result = await MeasureRequestsAsync( From d37eb0668ab4016630f0bfdc0387cbcd7b82b05f Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Fri, 27 Nov 2026 09:49:26 +0100 Subject: [PATCH 4/6] Restore CRLF line endings in Program.cs Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy/Program.cs | 924 ++++++++++++++++++++++---------------------- 1 file changed, 462 insertions(+), 462 deletions(-) diff --git a/DevProxy/Program.cs b/DevProxy/Program.cs index eeb8b993..975adc23 100644 --- a/DevProxy/Program.cs +++ b/DevProxy/Program.cs @@ -1,463 +1,463 @@ -// 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.Utils; -using DevProxy.Commands; -using DevProxy.Proxy; -using DevProxy.State; -using System.Diagnostics; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using static DevProxy.ProxyHost; - -// Keep management files discoverable even when env overrides change user data paths. -_ = StateManager.GetConfigFolder(); - -// Handle detached mode - spawn a child process and exit -// Only applies to root command (starting the proxy), not subcommands -if (DevProxyCommand.IsRootCommand && - DevProxyCommand.IsDetachedMode && - !DevProxyCommand.IsInternalDaemon) -{ - var detachedExitCode = await StartDetachedProcessAsync(args); - Environment.Exit(detachedExitCode); - return; -} - -// For daemon mode, redirect Console.Out/Error to the log file -// so that the normal console formatters (ProxyConsoleFormatter, -// MachineConsoleFormatter) write to the file instead of stdout. -// Console.IsOutputRedirected becomes true, which automatically -// strips ANSI color codes from human-readable output. -StreamWriter? _detachedLogWriter = null; -if (DevProxyCommand.IsInternalDaemon) -{ - var logFilePath = DevProxyCommand.DetachedLogFilePath; - var logDir = Path.GetDirectoryName(logFilePath); - if (!string.IsNullOrEmpty(logDir)) - { - PrivateFiles.EnsureDirectory(StateManager.GetConfigFolder()); - PrivateFiles.EnsureDirectory(logDir); - } - -#pragma warning disable CA2000 // Lifetime managed manually; disposed before Environment.Exit - _detachedLogWriter = new StreamWriter(logFilePath, append: false, Encoding.UTF8) { AutoFlush = true }; -#pragma warning restore CA2000 - Console.SetOut(_detachedLogWriter); - Console.SetError(_detachedLogWriter); -} - -static async Task StartDetachedProcessAsync(string[] args) -{ - var isJsonOutput = IsJsonOutputRequested(args); - - // Recover from a system-proxy registration left behind by a previous - // instance that crashed before restoring the OS proxy. This must run before - // any state-loading call below, which prunes (deletes) the stale state files - // it depends on without restoring the proxy. - var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(); - foreach (var orphan in reconciliation.Orphans) - { - var message = reconciliation.SystemProxyDisabled - ? $"Recovered system proxy left by a crashed Dev Proxy instance (PID: {orphan.Pid})." - : $"Removed stale system-proxy registration left by a crashed Dev Proxy instance (PID: {orphan.Pid}) while keeping the current system proxy owner unchanged."; - if (isJsonOutput) - { - await Console.Out.WriteLineAsync(FormatJsonLogEntry("info", message)); - } - else - { - await Console.Out.WriteLineAsync(message); - } - } - - // Check if an instance is already running as system proxy - var systemProxyInstance = await StateManager.FindSystemProxyInstanceAsync(); - if (systemProxyInstance is not null) - { - if (isJsonOutput) - { - await Console.Error.WriteLineAsync( - FormatJsonLogEntry("error", $"Dev Proxy is already running as system proxy (PID: {systemProxyInstance.Pid}). Use 'devproxy stop' to stop it first.")); - } - else - { - await Console.Error.WriteLineAsync($"Dev Proxy is already running as system proxy (PID: {systemProxyInstance.Pid})."); - await Console.Error.WriteLineAsync("Use 'devproxy stop' to stop it first."); - } - return 1; - } - - // Clean up old log files - StateManager.CleanupOldLogs(); - - // Build the arguments for the daemon process - // Replace --detach/-d with --_internal-daemon. Prepend it so that a trailing - // option missing its value (like a bare --report-dir) doesn't consume it. - var daemonArgs = args - .Where(a => a is not "--detach" and not "-d") - .Prepend(DevProxyCommand.InternalDaemonOptionName) - .ToArray(); - - var executablePath = Environment.ProcessPath; - if (string.IsNullOrEmpty(executablePath)) - { - if (isJsonOutput) - { - await Console.Error.WriteLineAsync( - FormatJsonLogEntry("error", "Could not determine executable path.")); - } - else - { - await Console.Error.WriteLineAsync("Could not determine executable path."); - } - return 1; - } - - var startInfo = new ProcessStartInfo - { - FileName = executablePath, - UseShellExecute = false, - CreateNoWindow = true, - // Redirect all std streams so the daemon doesn't hold on to the caller's - // stdin/stdout/stderr after this process exits. - RedirectStandardInput = true, - RedirectStandardOutput = true, - RedirectStandardError = true, - WorkingDirectory = Directory.GetCurrentDirectory() - }; - - // On Windows, we need to detach from the console - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - startInfo.WindowStyle = ProcessWindowStyle.Hidden; - } - - // ArgumentList quotes each argument, so empty or quoted values reach the daemon intact - foreach (var arg in daemonArgs) - { - startInfo.ArgumentList.Add(arg); - } - - // Without this, on Windows the daemon inherits the caller's stdout/stderr - // handles and callers that read our output to EOF (`| Out-String`, - // `$(devproxy --detach)`, subprocess pipes) hang until the daemon exits. - StandardHandleInheritance.DisableForCurrentProcess(); - - try - { - var process = Process.Start(startInfo); - if (process == null) - { - if (isJsonOutput) - { - await Console.Error.WriteLineAsync( - FormatJsonLogEntry("error", "Failed to start Dev Proxy process.")); - } - else - { - await Console.Error.WriteLineAsync("Failed to start Dev Proxy process."); - } - return 1; - } - - // The daemon never reads stdin; close it so it sees EOF immediately. - process.StandardInput.Close(); - - // Wait for the proxy to start and write its state file. Poll briefly, - // but wake up immediately if the daemon exits so failures surface fast. - var timeout = TimeSpan.FromSeconds(10); - var pollInterval = TimeSpan.FromMilliseconds(20); - var processExited = process.WaitForExitAsync(); - var stopwatch = Stopwatch.StartNew(); - - while (stopwatch.Elapsed < timeout) - { - _ = await Task.WhenAny(Task.Delay(pollInterval), processExited); - - var state = await StateManager.LoadStateByPidAsync(process.Id); - if (state is { Port: > 0 } && !string.IsNullOrEmpty(state.ApiUrl) && !state.ApiUrl.EndsWith(":0", StringComparison.Ordinal)) - { - var proxyUrl = state.ProxyUrl; - var token = ApiSecurity.ShouldDisplayTokenFor(state) ? - (await File.ReadAllTextAsync(ApiSecurity.GetTokenFilePath(state.Pid))).Trim() : null; - - if (isJsonOutput) - { - await Console.Out.WriteLineAsync(FormatJsonResultEntry(new - { - state.Pid, - ProxyUrl = proxyUrl, - state.ApiUrl, - Token = token, - state.LogFile - })); - } - else - { - var showToken = token is not null; - await Console.Out.WriteLineAsync("Dev Proxy started in background."); - await Console.Out.WriteLineAsync(); - await Console.Out.WriteLineAsync($" PID: {state.Pid}"); - await Console.Out.WriteLineAsync($" Proxy URL: {proxyUrl}"); - await Console.Out.WriteLineAsync($" API URL: {state.ApiUrl}"); - if (showToken) - { - await Console.Out.WriteLineAsync($" API token: {token}"); - } - await Console.Out.WriteLineAsync($" Log file: {state.LogFile}"); - await Console.Out.WriteLineAsync(); - if (!showToken) - { - await Console.Out.WriteLineAsync($"Use 'devproxy api token --pid {state.Pid}' to get the API token."); - } - await Console.Out.WriteLineAsync("Use 'devproxy status' to check status."); - await Console.Out.WriteLineAsync("Use 'devproxy logs' to view logs."); - await Console.Out.WriteLineAsync("Use 'devproxy stop' to stop."); - } - return 0; - } - - // Check if process exited prematurely - if (process.HasExited) - { - var errorOutput = await process.StandardError.ReadToEndAsync(); - var standardOutput = await process.StandardOutput.ReadToEndAsync(); - // The daemon redirects its console to its log file, so that's where - // the reason for the failure (like a port conflict) ends up. - var logOutput = await ReadDaemonLogAsync(process.Id); - - if (isJsonOutput) - { - if (!string.IsNullOrEmpty(logOutput)) - { - foreach (var entry in ToJsonLogEntries(logOutput)) - { - await Console.Error.WriteLineAsync(entry); - } - } - var message = "Dev Proxy failed to start."; - if (!string.IsNullOrEmpty(errorOutput)) - { - message += $" {errorOutput.Trim()}"; - } - if (!string.IsNullOrEmpty(standardOutput)) - { - message += $" {standardOutput.Trim()}"; - } - await Console.Error.WriteLineAsync(FormatJsonLogEntry("error", message)); - } - else - { - await Console.Error.WriteLineAsync("Dev Proxy failed to start."); - if (!string.IsNullOrEmpty(logOutput)) - { - await Console.Error.WriteLineAsync(logOutput.TrimEnd()); - } - if (!string.IsNullOrEmpty(errorOutput)) - { - await Console.Error.WriteLineAsync(errorOutput); - } - if (!string.IsNullOrEmpty(standardOutput)) - { - await Console.Error.WriteLineAsync(standardOutput); - } - } - return process.ExitCode; - } - } - - if (isJsonOutput) - { - await Console.Error.WriteLineAsync( - FormatJsonLogEntry("error", $"Timeout waiting for Dev Proxy to start. Check the log folder: {StateManager.GetLogsFolder()}")); - } - else - { - await Console.Error.WriteLineAsync("Timeout waiting for Dev Proxy to start."); - await Console.Error.WriteLineAsync($"Check the log folder: {StateManager.GetLogsFolder()}"); - } - return 1; - } - catch (Exception ex) - { - if (isJsonOutput) - { - await Console.Error.WriteLineAsync( - FormatJsonLogEntry("error", $"Failed to start Dev Proxy: {ex.Message}")); - } - else - { - await Console.Error.WriteLineAsync($"Failed to start Dev Proxy: {ex.Message}"); - } - return 1; - } -} - -/// -/// Formats a result entry matching the JSONL envelope produced by JsonConsoleFormatter: -/// {"type":"result","data":{...},"timestamp":"..."} -/// -static string FormatJsonResultEntry(object data) -{ -#pragma warning disable CA1869 // Called at most once per process lifetime - var jsonlOptions = new JsonSerializerOptions - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }; -#pragma warning restore CA1869 - var entry = new - { - type = "result", - data = JsonSerializer.SerializeToElement(data, jsonlOptions), - timestamp = DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture) - }; - return JsonSerializer.Serialize(entry, jsonlOptions); -} - -// The daemon logs JSONL, but output it doesn't control (like unhandled -// exception stack traces) can end up in its log too. Keep JSON entries as-is -// and wrap other runs of lines so the output stays valid JSONL. -static IEnumerable ToJsonLogEntries(string log) -{ - var pending = new List(); - foreach (var line in log.TrimEnd().Split('\n')) - { - var trimmed = line.TrimEnd('\r'); - if (IsJsonObject(trimmed)) - { - if (pending.Count > 0) - { - yield return FormatJsonLogEntry("error", string.Join(Environment.NewLine, pending)); - pending.Clear(); - } - yield return trimmed; - } - else if (pending.Count > 0 || !string.IsNullOrWhiteSpace(trimmed)) - { - pending.Add(trimmed); - } - } - if (pending.Count > 0) - { - yield return FormatJsonLogEntry("error", string.Join(Environment.NewLine, pending).TrimEnd()); - } -} - -static bool IsJsonObject(string line) -{ - if (!line.StartsWith('{')) - { - return false; - } - try - { - using var document = JsonDocument.Parse(line); - return document.RootElement.ValueKind == JsonValueKind.Object; - } - catch (JsonException) - { - return false; - } -} - -static async Task ReadDaemonLogAsync(int pid) -{ - try - { - var logsFolder = StateManager.GetLogsFolder(); - if (!Directory.Exists(logsFolder)) - { - return null; - } - var logFile = Directory.GetFiles(logsFolder, $"devproxy-{pid}-*.log") - .OrderByDescending(File.GetLastWriteTimeUtc) - .FirstOrDefault(); - return logFile is null ? null : await File.ReadAllTextAsync(logFile); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - return null; - } -} - -static async Task RunProxyAsync(string[] args, DevProxyConfigOptions options, HttpProxyEnvironment proxyEnvironment) -{ - // Keep overrides through host shutdown, but restore inherited values before a hot reload. - using var environment = new ProcessEnvironment(); - var app = BuildApplication(options, environment, proxyEnvironment); - try - { - var devProxyCommand = app.Services.GetRequiredService(); - return await devProxyCommand.InvokeAsync(args, app); - } - finally - { - await app.DisposeAsync(); - } -} - -// Handle 'config validate' early to allow validation of broken configs -// without requiring the full DI container to be built -if (DevProxyCommand.IsConfigValidateCommand) -{ - _ = Announcement.ShowOnceAsync(); - var validateExitCode = await ConfigCommand.RunValidateStandaloneAsync(args); - Environment.Exit(validateExitCode); - return; -} - -// Handle 'plugin' commands early so that plugins can be listed without -// a valid config file and without loading any configured plugins -if (DevProxyCommand.IsPluginCommand) -{ - var pluginExitCode = await PluginCommand.RunStandaloneAsync(args); - Environment.Exit(pluginExitCode); - return; -} - -var options = new DevProxyConfigOptions(); -options.ParseOptions(args); - -int exitCode; -bool shouldRestart; -var proxyEnvironment = new HttpProxyEnvironment(); -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); - - shouldRestart = ConfigFileWatcher.IsRestarting; - } - catch (Exception ex) - { - await Console.Error.WriteLineAsync("Unhandled exception during proxy run. Stopping restart loop."); - await Console.Error.WriteLineAsync(ex.ToString()); - exitCode = 1; - shouldRestart = false; - } -} while (shouldRestart); - -if (DevProxyCommand.IsRootCommand) -{ - await StateManager.DeleteStateAsync(); -} - -if (_detachedLogWriter is not null) -{ - await _detachedLogWriter.DisposeAsync(); -} - +// 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.Utils; +using DevProxy.Commands; +using DevProxy.Proxy; +using DevProxy.State; +using System.Diagnostics; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using static DevProxy.ProxyHost; + +// Keep management files discoverable even when env overrides change user data paths. +_ = StateManager.GetConfigFolder(); + +// Handle detached mode - spawn a child process and exit +// Only applies to root command (starting the proxy), not subcommands +if (DevProxyCommand.IsRootCommand && + DevProxyCommand.IsDetachedMode && + !DevProxyCommand.IsInternalDaemon) +{ + var detachedExitCode = await StartDetachedProcessAsync(args); + Environment.Exit(detachedExitCode); + return; +} + +// For daemon mode, redirect Console.Out/Error to the log file +// so that the normal console formatters (ProxyConsoleFormatter, +// MachineConsoleFormatter) write to the file instead of stdout. +// Console.IsOutputRedirected becomes true, which automatically +// strips ANSI color codes from human-readable output. +StreamWriter? _detachedLogWriter = null; +if (DevProxyCommand.IsInternalDaemon) +{ + var logFilePath = DevProxyCommand.DetachedLogFilePath; + var logDir = Path.GetDirectoryName(logFilePath); + if (!string.IsNullOrEmpty(logDir)) + { + PrivateFiles.EnsureDirectory(StateManager.GetConfigFolder()); + PrivateFiles.EnsureDirectory(logDir); + } + +#pragma warning disable CA2000 // Lifetime managed manually; disposed before Environment.Exit + _detachedLogWriter = new StreamWriter(logFilePath, append: false, Encoding.UTF8) { AutoFlush = true }; +#pragma warning restore CA2000 + Console.SetOut(_detachedLogWriter); + Console.SetError(_detachedLogWriter); +} + +static async Task StartDetachedProcessAsync(string[] args) +{ + var isJsonOutput = IsJsonOutputRequested(args); + + // Recover from a system-proxy registration left behind by a previous + // instance that crashed before restoring the OS proxy. This must run before + // any state-loading call below, which prunes (deletes) the stale state files + // it depends on without restoring the proxy. + var reconciliation = await SystemProxyManager.ReconcileOrphanedSystemProxiesAsync(); + foreach (var orphan in reconciliation.Orphans) + { + var message = reconciliation.SystemProxyDisabled + ? $"Recovered system proxy left by a crashed Dev Proxy instance (PID: {orphan.Pid})." + : $"Removed stale system-proxy registration left by a crashed Dev Proxy instance (PID: {orphan.Pid}) while keeping the current system proxy owner unchanged."; + if (isJsonOutput) + { + await Console.Out.WriteLineAsync(FormatJsonLogEntry("info", message)); + } + else + { + await Console.Out.WriteLineAsync(message); + } + } + + // Check if an instance is already running as system proxy + var systemProxyInstance = await StateManager.FindSystemProxyInstanceAsync(); + if (systemProxyInstance is not null) + { + if (isJsonOutput) + { + await Console.Error.WriteLineAsync( + FormatJsonLogEntry("error", $"Dev Proxy is already running as system proxy (PID: {systemProxyInstance.Pid}). Use 'devproxy stop' to stop it first.")); + } + else + { + await Console.Error.WriteLineAsync($"Dev Proxy is already running as system proxy (PID: {systemProxyInstance.Pid})."); + await Console.Error.WriteLineAsync("Use 'devproxy stop' to stop it first."); + } + return 1; + } + + // Clean up old log files + StateManager.CleanupOldLogs(); + + // Build the arguments for the daemon process + // Replace --detach/-d with --_internal-daemon. Prepend it so that a trailing + // option missing its value (like a bare --report-dir) doesn't consume it. + var daemonArgs = args + .Where(a => a is not "--detach" and not "-d") + .Prepend(DevProxyCommand.InternalDaemonOptionName) + .ToArray(); + + var executablePath = Environment.ProcessPath; + if (string.IsNullOrEmpty(executablePath)) + { + if (isJsonOutput) + { + await Console.Error.WriteLineAsync( + FormatJsonLogEntry("error", "Could not determine executable path.")); + } + else + { + await Console.Error.WriteLineAsync("Could not determine executable path."); + } + return 1; + } + + var startInfo = new ProcessStartInfo + { + FileName = executablePath, + UseShellExecute = false, + CreateNoWindow = true, + // Redirect all std streams so the daemon doesn't hold on to the caller's + // stdin/stdout/stderr after this process exits. + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + WorkingDirectory = Directory.GetCurrentDirectory() + }; + + // On Windows, we need to detach from the console + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + startInfo.WindowStyle = ProcessWindowStyle.Hidden; + } + + // ArgumentList quotes each argument, so empty or quoted values reach the daemon intact + foreach (var arg in daemonArgs) + { + startInfo.ArgumentList.Add(arg); + } + + // Without this, on Windows the daemon inherits the caller's stdout/stderr + // handles and callers that read our output to EOF (`| Out-String`, + // `$(devproxy --detach)`, subprocess pipes) hang until the daemon exits. + StandardHandleInheritance.DisableForCurrentProcess(); + + try + { + var process = Process.Start(startInfo); + if (process == null) + { + if (isJsonOutput) + { + await Console.Error.WriteLineAsync( + FormatJsonLogEntry("error", "Failed to start Dev Proxy process.")); + } + else + { + await Console.Error.WriteLineAsync("Failed to start Dev Proxy process."); + } + return 1; + } + + // The daemon never reads stdin; close it so it sees EOF immediately. + process.StandardInput.Close(); + + // Wait for the proxy to start and write its state file. Poll briefly, + // but wake up immediately if the daemon exits so failures surface fast. + var timeout = TimeSpan.FromSeconds(10); + var pollInterval = TimeSpan.FromMilliseconds(20); + var processExited = process.WaitForExitAsync(); + var stopwatch = Stopwatch.StartNew(); + + while (stopwatch.Elapsed < timeout) + { + _ = await Task.WhenAny(Task.Delay(pollInterval), processExited); + + var state = await StateManager.LoadStateByPidAsync(process.Id); + if (state is { Port: > 0 } && !string.IsNullOrEmpty(state.ApiUrl) && !state.ApiUrl.EndsWith(":0", StringComparison.Ordinal)) + { + var proxyUrl = state.ProxyUrl; + var token = ApiSecurity.ShouldDisplayTokenFor(state) ? + (await File.ReadAllTextAsync(ApiSecurity.GetTokenFilePath(state.Pid))).Trim() : null; + + if (isJsonOutput) + { + await Console.Out.WriteLineAsync(FormatJsonResultEntry(new + { + state.Pid, + ProxyUrl = proxyUrl, + state.ApiUrl, + Token = token, + state.LogFile + })); + } + else + { + var showToken = token is not null; + await Console.Out.WriteLineAsync("Dev Proxy started in background."); + await Console.Out.WriteLineAsync(); + await Console.Out.WriteLineAsync($" PID: {state.Pid}"); + await Console.Out.WriteLineAsync($" Proxy URL: {proxyUrl}"); + await Console.Out.WriteLineAsync($" API URL: {state.ApiUrl}"); + if (showToken) + { + await Console.Out.WriteLineAsync($" API token: {token}"); + } + await Console.Out.WriteLineAsync($" Log file: {state.LogFile}"); + await Console.Out.WriteLineAsync(); + if (!showToken) + { + await Console.Out.WriteLineAsync($"Use 'devproxy api token --pid {state.Pid}' to get the API token."); + } + await Console.Out.WriteLineAsync("Use 'devproxy status' to check status."); + await Console.Out.WriteLineAsync("Use 'devproxy logs' to view logs."); + await Console.Out.WriteLineAsync("Use 'devproxy stop' to stop."); + } + return 0; + } + + // Check if process exited prematurely + if (process.HasExited) + { + var errorOutput = await process.StandardError.ReadToEndAsync(); + var standardOutput = await process.StandardOutput.ReadToEndAsync(); + // The daemon redirects its console to its log file, so that's where + // the reason for the failure (like a port conflict) ends up. + var logOutput = await ReadDaemonLogAsync(process.Id); + + if (isJsonOutput) + { + if (!string.IsNullOrEmpty(logOutput)) + { + foreach (var entry in ToJsonLogEntries(logOutput)) + { + await Console.Error.WriteLineAsync(entry); + } + } + var message = "Dev Proxy failed to start."; + if (!string.IsNullOrEmpty(errorOutput)) + { + message += $" {errorOutput.Trim()}"; + } + if (!string.IsNullOrEmpty(standardOutput)) + { + message += $" {standardOutput.Trim()}"; + } + await Console.Error.WriteLineAsync(FormatJsonLogEntry("error", message)); + } + else + { + await Console.Error.WriteLineAsync("Dev Proxy failed to start."); + if (!string.IsNullOrEmpty(logOutput)) + { + await Console.Error.WriteLineAsync(logOutput.TrimEnd()); + } + if (!string.IsNullOrEmpty(errorOutput)) + { + await Console.Error.WriteLineAsync(errorOutput); + } + if (!string.IsNullOrEmpty(standardOutput)) + { + await Console.Error.WriteLineAsync(standardOutput); + } + } + return process.ExitCode; + } + } + + if (isJsonOutput) + { + await Console.Error.WriteLineAsync( + FormatJsonLogEntry("error", $"Timeout waiting for Dev Proxy to start. Check the log folder: {StateManager.GetLogsFolder()}")); + } + else + { + await Console.Error.WriteLineAsync("Timeout waiting for Dev Proxy to start."); + await Console.Error.WriteLineAsync($"Check the log folder: {StateManager.GetLogsFolder()}"); + } + return 1; + } + catch (Exception ex) + { + if (isJsonOutput) + { + await Console.Error.WriteLineAsync( + FormatJsonLogEntry("error", $"Failed to start Dev Proxy: {ex.Message}")); + } + else + { + await Console.Error.WriteLineAsync($"Failed to start Dev Proxy: {ex.Message}"); + } + return 1; + } +} + +/// +/// Formats a result entry matching the JSONL envelope produced by JsonConsoleFormatter: +/// {"type":"result","data":{...},"timestamp":"..."} +/// +static string FormatJsonResultEntry(object data) +{ +#pragma warning disable CA1869 // Called at most once per process lifetime + var jsonlOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; +#pragma warning restore CA1869 + var entry = new + { + type = "result", + data = JsonSerializer.SerializeToElement(data, jsonlOptions), + timestamp = DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture) + }; + return JsonSerializer.Serialize(entry, jsonlOptions); +} + +// The daemon logs JSONL, but output it doesn't control (like unhandled +// exception stack traces) can end up in its log too. Keep JSON entries as-is +// and wrap other runs of lines so the output stays valid JSONL. +static IEnumerable ToJsonLogEntries(string log) +{ + var pending = new List(); + foreach (var line in log.TrimEnd().Split('\n')) + { + var trimmed = line.TrimEnd('\r'); + if (IsJsonObject(trimmed)) + { + if (pending.Count > 0) + { + yield return FormatJsonLogEntry("error", string.Join(Environment.NewLine, pending)); + pending.Clear(); + } + yield return trimmed; + } + else if (pending.Count > 0 || !string.IsNullOrWhiteSpace(trimmed)) + { + pending.Add(trimmed); + } + } + if (pending.Count > 0) + { + yield return FormatJsonLogEntry("error", string.Join(Environment.NewLine, pending).TrimEnd()); + } +} + +static bool IsJsonObject(string line) +{ + if (!line.StartsWith('{')) + { + return false; + } + try + { + using var document = JsonDocument.Parse(line); + return document.RootElement.ValueKind == JsonValueKind.Object; + } + catch (JsonException) + { + return false; + } +} + +static async Task ReadDaemonLogAsync(int pid) +{ + try + { + var logsFolder = StateManager.GetLogsFolder(); + if (!Directory.Exists(logsFolder)) + { + return null; + } + var logFile = Directory.GetFiles(logsFolder, $"devproxy-{pid}-*.log") + .OrderByDescending(File.GetLastWriteTimeUtc) + .FirstOrDefault(); + return logFile is null ? null : await File.ReadAllTextAsync(logFile); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } +} + +static async Task RunProxyAsync(string[] args, DevProxyConfigOptions options, HttpProxyEnvironment proxyEnvironment) +{ + // Keep overrides through host shutdown, but restore inherited values before a hot reload. + using var environment = new ProcessEnvironment(); + var app = BuildApplication(options, environment, proxyEnvironment); + try + { + var devProxyCommand = app.Services.GetRequiredService(); + return await devProxyCommand.InvokeAsync(args, app); + } + finally + { + await app.DisposeAsync(); + } +} + +// Handle 'config validate' early to allow validation of broken configs +// without requiring the full DI container to be built +if (DevProxyCommand.IsConfigValidateCommand) +{ + _ = Announcement.ShowOnceAsync(); + var validateExitCode = await ConfigCommand.RunValidateStandaloneAsync(args); + Environment.Exit(validateExitCode); + return; +} + +// Handle 'plugin' commands early so that plugins can be listed without +// a valid config file and without loading any configured plugins +if (DevProxyCommand.IsPluginCommand) +{ + var pluginExitCode = await PluginCommand.RunStandaloneAsync(args); + Environment.Exit(pluginExitCode); + return; +} + +var options = new DevProxyConfigOptions(); +options.ParseOptions(args); + +int exitCode; +bool shouldRestart; +var proxyEnvironment = new HttpProxyEnvironment(); +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); + + shouldRestart = ConfigFileWatcher.IsRestarting; + } + catch (Exception ex) + { + await Console.Error.WriteLineAsync("Unhandled exception during proxy run. Stopping restart loop."); + await Console.Error.WriteLineAsync(ex.ToString()); + exitCode = 1; + shouldRestart = false; + } +} while (shouldRestart); + +if (DevProxyCommand.IsRootCommand) +{ + await StateManager.DeleteStateAsync(); +} + +if (_detachedLogWriter is not null) +{ + await _detachedLogWriter.DisposeAsync(); +} + Environment.Exit(exitCode); \ No newline at end of file From aa363f6bee5efa599bd81d9ba86714c97bec8a29 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Wed, 2 Dec 2026 13:19:28 +0100 Subject: [PATCH 5/6] Fix memory retention tests after merging main Replace Task.WhenAny with Task.Delay (CA2027, enabled by AnalysisLevel 11.0) and resolve the plugins path for the current target framework instead of hardcoding net10.0. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- DevProxy.Integration.Tests/MemoryRetentionTests.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/DevProxy.Integration.Tests/MemoryRetentionTests.cs b/DevProxy.Integration.Tests/MemoryRetentionTests.cs index 3a9b635d..62259b8f 100644 --- a/DevProxy.Integration.Tests/MemoryRetentionTests.cs +++ b/DevProxy.Integration.Tests/MemoryRetentionTests.cs @@ -239,7 +239,13 @@ private static async Task RunGenerationAsync( { Assert.True(attempt < 10, $"Generation {generation} didn't restart after the config file changed."); await File.WriteAllTextAsync(configPath, ConfigFile(originHost, generation * 100 + attempt)); - _ = await Task.WhenAny(stopping.Task, Task.Delay(TimeSpan.FromSeconds(3))); + try + { + await stopping.Task.WaitAsync(TimeSpan.FromSeconds(3)); + } + catch (TimeoutException) + { + } } Assert.True(ConfigFileWatcher.IsRestarting); @@ -333,9 +339,11 @@ private static string LocatePluginsDll() #else "Release"; #endif + // The test assembly targets the same framework as the host, so reuse its output folder name. + var targetFramework = Path.GetFileName(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory)); for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) { - var candidate = Path.Combine(dir.FullName, "DevProxy", "bin", config, "net10.0", "plugins", "DevProxy.Plugins.dll"); + var candidate = Path.Combine(dir.FullName, "DevProxy", "bin", config, targetFramework, "plugins", "DevProxy.Plugins.dll"); if (File.Exists(candidate)) { return candidate; From 20def0f503431584bf284706d20774e2e97ac0b4 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Wed, 2 Dec 2026 15:41:54 +0100 Subject: [PATCH 6/6] Isolate the hot-reload test's certificate authority Let tests configure services when building the host, and register a certificate authority with root and leaf paths under the test's temp folder so the test never touches the user's certificates. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../MemoryRetentionTests.cs | 22 +++++++++++++++++-- DevProxy/ProxyHost.cs | 14 +++++++++--- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/DevProxy.Integration.Tests/MemoryRetentionTests.cs b/DevProxy.Integration.Tests/MemoryRetentionTests.cs index 62259b8f..79ae73a3 100644 --- a/DevProxy.Integration.Tests/MemoryRetentionTests.cs +++ b/DevProxy.Integration.Tests/MemoryRetentionTests.cs @@ -14,8 +14,10 @@ using DevProxy.Plugins.Mocking; using DevProxy.Proxy; using DevProxy.Proxy.Kestrel; +using DevProxy.Proxy.Kestrel.Internal; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -137,6 +139,10 @@ private async Task MeasureHotReloadAsync(int generations, bool var options = new DevProxyConfigOptions(); options.ParseOptions(args); var proxyEnvironment = new HttpProxyEnvironment(); + // Starting the host creates the root and leaf certificates, so keep them in the + // temp folder instead of the user's Dev Proxy folder. + var rootCertPath = Path.Combine(configDir.FullName, "rootCert.pfx"); + var leafCertDirectory = Path.Combine(configDir.FullName, "certificates"); var generationRefs = new List(); try @@ -144,7 +150,8 @@ private async Task MeasureHotReloadAsync(int generations, bool for (var generation = 1; generation <= generations; generation++) { generationRefs.Add(await RunGenerationAsync( - args, options, proxyEnvironment, configPath, origin.Host, generation, leakGenerations)); + args, options, proxyEnvironment, configPath, rootCertPath, leafCertDirectory, + origin.Host, generation, leakGenerations)); } await CollectUntilAsync(() => generationRefs.All(g => !g.IsAlive)); @@ -199,13 +206,24 @@ private static async Task RunGenerationAsync( DevProxyConfigOptions options, HttpProxyEnvironment proxyEnvironment, string configPath, + string rootCertPath, + string leafCertDirectory, string originHost, int generation, bool leakGeneration) { ConfigFileWatcher.Reset(); using var environment = new ProcessEnvironment(); - var app = ProxyHost.BuildApplication(options, environment, proxyEnvironment); + var app = ProxyHost.BuildApplication( + options, + environment, + proxyEnvironment, + services => services + .RemoveAll() + .AddSingleton(sp => new CertificateAuthority( + rootCertPath, + leafCertDirectory, + sp.GetRequiredService().CreateLogger()))); try { // Mirror the start-up steps of DevProxyCommand.InvokeAsync that set up plugins, diff --git a/DevProxy/ProxyHost.cs b/DevProxy/ProxyHost.cs index 1a51772e..eb50d34e 100644 --- a/DevProxy/ProxyHost.cs +++ b/DevProxy/ProxyHost.cs @@ -64,7 +64,10 @@ internal static void WriteUnresolvedEnvironmentVariables(IConfiguration configur } internal static WebApplication BuildApplication( - DevProxyConfigOptions options, ProcessEnvironment environment, HttpProxyEnvironment proxyEnvironment) + DevProxyConfigOptions options, + ProcessEnvironment environment, + HttpProxyEnvironment proxyEnvironment, + Action? configureServices = null) { // 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 @@ -74,7 +77,7 @@ internal static WebApplication BuildApplication( _ = builder.Configuration.ConfigureDevProxyConfig(options); try { - return BuildApplicationCore(builder, options, environment, proxyEnvironment); + return BuildApplicationCore(builder, options, environment, proxyEnvironment, configureServices); } catch { @@ -86,7 +89,11 @@ internal static WebApplication BuildApplication( } internal static WebApplication BuildApplicationCore( - WebApplicationBuilder builder, DevProxyConfigOptions options, ProcessEnvironment environment, HttpProxyEnvironment proxyEnvironment) + WebApplicationBuilder builder, + DevProxyConfigOptions options, + ProcessEnvironment environment, + HttpProxyEnvironment proxyEnvironment, + Action? configureServices = null) { environment.Apply(builder.Configuration, options.Env); var changedProxyVariables = proxyEnvironment.GetChangedVariables(); @@ -94,6 +101,7 @@ internal static WebApplication BuildApplicationCore( _ = builder.Logging.ConfigureDevProxyLogging(builder.Configuration, options); var allowedOrigins = ApiSecurity.GetAllowedOrigins(builder.Configuration); _ = builder.Services.ConfigureDevProxyServices(builder.Configuration, options, allowedOrigins); + configureServices?.Invoke(builder.Services); var defaultApiPort = 8897; var apiPort = options.ApiPort ??