diff --git a/DevProxy.Integration.Tests/CommandExitCodeTests.cs b/DevProxy.Integration.Tests/CommandExitCodeTests.cs index ed161d75..1472d96b 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); + } + [Theory] [InlineData("warning")] [InlineData("none")] diff --git a/DevProxy.Proxy.Kestrel.Tests/CertificateAuthorityTests.cs b/DevProxy.Proxy.Kestrel.Tests/CertificateAuthorityTests.cs index 951d465c..dcd19113 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 IsRootPersisted_TrueForNewSavedRootAndReloadedRoot() { @@ -244,8 +257,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)); } @@ -293,9 +307,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"); @@ -308,9 +323,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..83a62dbb 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 { diff --git a/DevProxy.Proxy.Kestrel/Internal/CertificateAuthority.cs b/DevProxy.Proxy.Kestrel/Internal/CertificateAuthority.cs index 30cc71a0..2f9d8200 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,8 @@ 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 bool _isRootPersisted; private readonly ConcurrentDictionary _cache = new(StringComparer.OrdinalIgnoreCase); public CertificateAuthority(string rootPfxPath, string leafDirectory, ILogger? logger = null) @@ -72,7 +73,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,7 +114,8 @@ 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; /// Path of the PKCS#12 file that stores the root certificate and its private key. public string RootCertificatePath => _rootPfxPath; @@ -120,9 +124,23 @@ internal static string ResolveRootPfxPath(string? envPath, string configDirector /// Whether is stored on disk and will be reused by /// subsequent runs. false when a newly generated root couldn't be saved. /// - public bool IsRootPersisted { get; private set; } + /// Loads or creates (and persists) the root on first access. + public bool IsRootPersisted + { + get + { + _ = RootCertificate; + return _isRootPersisted; + } + } - 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. @@ -146,7 +164,7 @@ private X509Certificate2 LoadOrCreateRoot() if (existing is not null) { _logger.LogDebug("Loaded persisted root certificate from {Path}", _rootPfxPath); - IsRootPersisted = true; + _isRootPersisted = true; return existing; } @@ -211,7 +229,7 @@ private void SaveRoot(X509Certificate2 root) File.WriteAllBytes(_rootPfxPath, root.Export(X509ContentType.Pkcs12, string.Empty)); _logger.LogInformation("Saved new root certificate to {Path}", _rootPfxPath); - IsRootPersisted = true; + _isRootPersisted = true; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { @@ -266,7 +284,7 @@ private X509Certificate2 LoadOrCreateLeaf(string host) string.Empty, X509KeyStorageFlags.Exportable); - var ski = _ca.Extensions + var ski = RootCertificate.Extensions .OfType() .FirstOrDefault()?.SubjectKeyIdentifierBytes; @@ -378,7 +396,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); @@ -386,21 +404,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); @@ -417,7 +435,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 1beee77e..e025da1b 100644 --- a/DevProxy.Tests/CertCommandTests.cs +++ b/DevProxy.Tests/CertCommandTests.cs @@ -38,10 +38,19 @@ public void Dispose() } } - private CertificateAuthority GetCertificateAuthority() => - _certificateAuthority ??= new CertificateAuthority( - Path.Combine(_caDirectory, "rootCert.pfx"), - Path.Combine(_caDirectory, "certificates")); + private CertificateAuthority GetCertificateAuthority() + { + if (_certificateAuthority is null) + { + _certificateAuthority = new CertificateAuthority( + Path.Combine(_caDirectory, "rootCert.pfx"), + Path.Combine(_caDirectory, "certificates")); + // The root is created lazily; tests expect it on disk. + _ = _certificateAuthority.RootCertificate; + } + + return _certificateAuthority; + } [Theory] [InlineData("Pem", null, "Pem")]