From ea809b58465fb9b0851736ce474542f683a54fc6 Mon Sep 17 00:00:00 2001 From: Waldek Mastykarz Date: Tue, 24 Nov 2026 10:40:25 +0100 Subject: [PATCH] Create the root certificate only when it's needed Since v4.0.0 every devproxy command, including --version and --help, created rootCert.pfx because building the CLI eagerly resolved the root certificate for CertCommand, and CertificateAuthority created the root in its constructor. - CertificateAuthority now loads/creates the root lazily on first use - CertCommand takes a Lazy so only cert subcommands resolve the root - Leaf lookup initializes the root first so a fresh root still purges stale leaves before any leaf is loaded Closes #2173 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../CommandExitCodeTests.cs | 19 ++++++++++ .../CertificateAuthorityTests.cs | 22 ++++++++++-- .../IServiceCollectionExtensions.cs | 8 +++++ .../Internal/CertificateAuthority.cs | 36 ++++++++++++------- DevProxy.Tests/CertCommandTests.cs | 4 +-- DevProxy/Commands/CertCommand.cs | 8 ++--- 6 files changed, 76 insertions(+), 21 deletions(-) diff --git a/DevProxy.Integration.Tests/CommandExitCodeTests.cs b/DevProxy.Integration.Tests/CommandExitCodeTests.cs index fde02816..b5cb1a70 100644 --- a/DevProxy.Integration.Tests/CommandExitCodeTests.cs +++ b/DevProxy.Integration.Tests/CommandExitCodeTests.cs @@ -28,6 +28,25 @@ public async Task ConfigNew_Succeeds_ReturnsZero() Assert.True(File.Exists(Path.Combine(workDir.Path, "myconfig.json")), output); } + [Theory] + [InlineData("--version")] + [InlineData("--help")] + [InlineData("jwt --help")] + public async Task NonProxyCommands_DoNotCreateRootCertificate(string args) + { + using var workDir = new TempDir(); + var rootCertPath = Path.Combine(workDir.Path, "rootCert.pfx"); + var env = new Dictionary + { + ["DEV_PROXY_CERT_PATH"] = rootCertPath, + }; + + var (exitCode, output) = await RunHostAsync(workDir.Path, env, args.Split(' ')); + + Assert.True(exitCode == 0, output); + Assert.False(File.Exists(rootCertPath), output); + } + [Fact] public async Task ConfigNew_Fails_ReturnsNonZero() { diff --git a/DevProxy.Proxy.Kestrel.Tests/CertificateAuthorityTests.cs b/DevProxy.Proxy.Kestrel.Tests/CertificateAuthorityTests.cs index 7d8aa699..dd39b893 100644 --- a/DevProxy.Proxy.Kestrel.Tests/CertificateAuthorityTests.cs +++ b/DevProxy.Proxy.Kestrel.Tests/CertificateAuthorityTests.cs @@ -77,10 +77,23 @@ public void RelativeEnvPath_PersistsRootInSubfolder() var rootPath = CertificateAuthority.ResolveRootPfxPath("rootCert/rootCert.pfx", _dir); using var ca = new CertificateAuthority(rootPath, _leafDir); + _ = ca.RootCertificate; Assert.True(File.Exists(Path.Combine(_dir, "rootCert", "rootCert.pfx"))); } + [Fact] + public void Constructor_DoesNotCreateRootUntilFirstUse() + { + using var ca = new CertificateAuthority(_rootPath, _leafDir); + + Assert.False(File.Exists(_rootPath)); + + _ = ca.RootCertificate; + + Assert.True(File.Exists(_rootPath)); + } + [Fact] public void FirstRun_CreatesValidRoot_AndPersistsToDisk() { @@ -219,8 +232,9 @@ public void FreshRoot_PurgesStaleLeafCache() var stale = Path.Combine(_leafDir, "stale.pfx"); File.WriteAllBytes(stale, [0x00]); - // No root file exists -> a fresh root is created -> the old leaf cache is dropped. + // No root file exists -> a fresh root is created on first use -> the old leaf cache is dropped. using var ca = new CertificateAuthority(_rootPath, _leafDir); + _ = ca.RootCertificate; Assert.False(File.Exists(stale)); } @@ -268,9 +282,10 @@ public void GetCertificateForHost_LeafDoesNotOutliveRoot() public void GetCertificateForHost_LeafWithoutAki_Regenerates() { using var ca = new CertificateAuthority(_rootPath, _leafDir); + var root = ca.RootCertificate; _ = Directory.CreateDirectory(_leafDir); - File.WriteAllBytes(Path.Combine(_leafDir, "example.com.pfx"), CreateLeafPfx(ca.RootCertificate, null)); + File.WriteAllBytes(Path.Combine(_leafDir, "example.com.pfx"), CreateLeafPfx(root, null)); var leaf = ca.GetCertificateForHost("example.com"); @@ -283,9 +298,10 @@ public void GetCertificateForHost_LeafWithMismatchedAki_Regenerates() var rootNotAfter = DateTimeOffset.UtcNow.AddDays(10); using var otherCa = CreateRootCertificate(rootNotAfter); using var ca = new CertificateAuthority(_rootPath, _leafDir); + var root = ca.RootCertificate; _ = Directory.CreateDirectory(_leafDir); - File.WriteAllBytes(Path.Combine(_leafDir, "example.com.pfx"), CreateLeafPfx(ca.RootCertificate, otherCa)); + File.WriteAllBytes(Path.Combine(_leafDir, "example.com.pfx"), CreateLeafPfx(root, otherCa)); var leaf = ca.GetCertificateForHost("example.com"); diff --git a/DevProxy.Proxy.Kestrel/IServiceCollectionExtensions.cs b/DevProxy.Proxy.Kestrel/IServiceCollectionExtensions.cs index 65ebc503..20941c66 100644 --- a/DevProxy.Proxy.Kestrel/IServiceCollectionExtensions.cs +++ b/DevProxy.Proxy.Kestrel/IServiceCollectionExtensions.cs @@ -20,6 +20,11 @@ namespace Microsoft.Extensions.DependencyInjection; /// plugin (signing-key chain) all resolve the same certificate rather than each /// loading its own copy. /// +/// +/// +/// The root is loaded or created on first use, not when the CA is constructed, so +/// commands that never need it (such as --version) don't write it to disk. +/// /// public static class KestrelProxyServiceCollectionExtensions { @@ -31,6 +36,9 @@ public static IServiceCollection AddKestrelCertificateAuthority(this IServiceCol CertificateAuthority.CreateDefault( sp.GetRequiredService().CreateLogger())); _ = services.AddSingleton(sp => sp.GetRequiredService().RootCertificate); + // Lets consumers built eagerly (e.g. CLI commands) defer loading/creating the root + // until they actually need it. + _ = services.AddSingleton(sp => new Lazy(sp.GetRequiredService)); return services; } diff --git a/DevProxy.Proxy.Kestrel/Internal/CertificateAuthority.cs b/DevProxy.Proxy.Kestrel/Internal/CertificateAuthority.cs index 977f2e83..880ebc81 100644 --- a/DevProxy.Proxy.Kestrel/Internal/CertificateAuthority.cs +++ b/DevProxy.Proxy.Kestrel/Internal/CertificateAuthority.cs @@ -11,8 +11,8 @@ namespace DevProxy.Proxy.Kestrel.Internal; /// -/// A persistent certificate authority. It loads a self-signed root CA from disk -/// (creating + saving one on first run), then mints and caches a leaf certificate +/// A persistent certificate authority. On first use it loads a self-signed root CA +/// from disk (creating + saving one if needed), then mints and caches a leaf certificate /// per host on demand so the proxy can terminate TLS and inspect decrypted traffic. /// /// @@ -61,7 +61,7 @@ public sealed class CertificateAuthority : IDisposable private readonly string _rootPfxPath; private readonly string _leafDirectory; private readonly ILogger _logger; - private readonly X509Certificate2 _ca; + private readonly Lazy _root; private readonly ConcurrentDictionary _cache = new(StringComparer.OrdinalIgnoreCase); public CertificateAuthority(string rootPfxPath, string leafDirectory, ILogger? logger = null) @@ -72,7 +72,9 @@ public CertificateAuthority(string rootPfxPath, string leafDirectory, ILogger? l _rootPfxPath = rootPfxPath; _leafDirectory = leafDirectory; _logger = logger ?? NullLogger.Instance; - _ca = LoadOrCreateRoot(); + // Defer loading/creating the root until it's actually needed so that merely + // constructing the CA (e.g. while building the CLI) doesn't write a root to disk. + _root = new(LoadOrCreateRoot, LazyThreadSafetyMode.ExecutionAndPublication); } /// @@ -111,9 +113,16 @@ internal static string ResolveRootPfxPath(string? envPath, string configDirector } /// The root CA certificate clients must trust to allow interception. - public X509Certificate2 RootCertificate => _ca; + /// Loads or creates (and persists) the root on first access. + public X509Certificate2 RootCertificate => _root.Value; - public X509Certificate2 GetCertificateForHost(string host) => _cache.GetOrAdd(host, LoadOrCreateLeaf); + public X509Certificate2 GetCertificateForHost(string host) + { + // Initialize the root first: creating a fresh root purges stale on-disk leaves, + // which must happen before any leaf is loaded from disk. + _ = RootCertificate; + return _cache.GetOrAdd(host, LoadOrCreateLeaf); + } // Mirrors Titanium's CertificateDiskCache.GetRootCertificateDirectory: on Windows the // root lives next to the executable; on mac/Linux under ApplicationData/dev-proxy. @@ -255,7 +264,7 @@ private X509Certificate2 LoadOrCreateLeaf(string host) string.Empty, X509KeyStorageFlags.Exportable); - var ski = _ca.Extensions + var ski = RootCertificate.Extensions .OfType() .FirstOrDefault()?.SubjectKeyIdentifierBytes; @@ -367,7 +376,7 @@ private X509Certificate2 CreateLeafCertificate(string host) request.CertificateExtensions.Add( X509AuthorityKeyIdentifierExtension.CreateFromCertificate( - _ca, includeKeyIdentifier: true, includeIssuerAndSerial: false)); + RootCertificate, includeKeyIdentifier: true, includeIssuerAndSerial: false)); var serialNumber = new byte[8]; RandomNumberGenerator.Fill(serialNumber); @@ -375,21 +384,21 @@ private X509Certificate2 CreateLeafCertificate(string host) // A leaf may not outlive its issuer. When reusing an existing (possibly // near-expiry) root, clamp the leaf's validity window to the root's. var notBefore = DateTimeOffset.UtcNow.AddDays(-1); - var rootNotBefore = new DateTimeOffset(_ca.NotBefore.ToUniversalTime()); + var rootNotBefore = new DateTimeOffset(RootCertificate.NotBefore.ToUniversalTime()); if (notBefore < rootNotBefore) { notBefore = rootNotBefore; } var notAfter = DateTimeOffset.UtcNow.AddDays(LeafValidityDays); - var rootNotAfter = new DateTimeOffset(_ca.NotAfter.ToUniversalTime()); + var rootNotAfter = new DateTimeOffset(RootCertificate.NotAfter.ToUniversalTime()); if (notAfter > rootNotAfter) { notAfter = rootNotAfter; } using var leaf = request.Create( - _ca, + RootCertificate, notBefore, notAfter, serialNumber); @@ -406,7 +415,10 @@ private X509Certificate2 CreateLeafCertificate(string host) public void Dispose() { - _ca.Dispose(); + if (_root.IsValueCreated) + { + _root.Value.Dispose(); + } foreach (var leaf in _cache.Values) { leaf.Dispose(); diff --git a/DevProxy.Tests/CertCommandTests.cs b/DevProxy.Tests/CertCommandTests.cs index 06cea4a9..afebc36a 100644 --- a/DevProxy.Tests/CertCommandTests.cs +++ b/DevProxy.Tests/CertCommandTests.cs @@ -22,7 +22,7 @@ public void Ensure_ReportsTrustResult(bool fail, int expectedExitCode) { using var certificate = CreateCertificate(); var trust = new TestCertificateTrust(fail); - var command = new CertCommand(NullLogger.Instance, certificate, trust); + var command = new CertCommand(NullLogger.Instance, new Lazy(() => certificate), trust); Assert.Equal(expectedExitCode, command.Parse("ensure").Invoke()); Assert.True(trust.TrustCalled); @@ -39,7 +39,7 @@ public void Ensure_ExportFailure_ReturnsNonZeroOnSupportedPlatforms() using var certificate = CreateCertificate(); certificate.Dispose(); var trust = new RootCertificateTrust(new FakeProxyConfiguration(), NullLogger.Instance); - var command = new CertCommand(NullLogger.Instance, certificate, trust); + var command = new CertCommand(NullLogger.Instance, new Lazy(() => certificate), trust); Assert.Equal(1, command.Parse("ensure").Invoke()); } diff --git a/DevProxy/Commands/CertCommand.cs b/DevProxy/Commands/CertCommand.cs index a4b0f333..0524bca2 100644 --- a/DevProxy/Commands/CertCommand.cs +++ b/DevProxy/Commands/CertCommand.cs @@ -13,7 +13,7 @@ namespace DevProxy.Commands; sealed class CertCommand : Command { private readonly ILogger _logger; - private readonly X509Certificate2 _rootCertificate; + private readonly Lazy _rootCertificate; private readonly IRootCertificateTrust _rootCertificateTrust; private readonly Option _forceOption = new("--force", "-f") { @@ -22,7 +22,7 @@ sealed class CertCommand : Command public CertCommand( ILogger logger, - X509Certificate2 rootCertificate, + Lazy rootCertificate, IRootCertificateTrust rootCertificateTrust) : base("cert", "Manage the Dev Proxy certificate") { @@ -62,7 +62,7 @@ private int EnsureCert() { // Resolving the shared root certificate creates + persists it on first run. _logger.LogInformation("Ensuring certificate exists and is trusted..."); - _rootCertificateTrust.Trust(_rootCertificate); + _rootCertificateTrust.Trust(_rootCertificate.Value); _logger.LogInformation("DONE"); return 0; } @@ -102,7 +102,7 @@ public int RemoveCert(ParseResult parseResult) _logger.LogInformation("Uninstalling the root certificate..."); - _rootCertificateTrust.Untrust(_rootCertificate); + _rootCertificateTrust.Untrust(_rootCertificate.Value); _logger.LogInformation("DONE"); return 0;