Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions DevProxy.Integration.Tests/CommandExitCodeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>
{
["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")]
Expand Down
22 changes: 19 additions & 3 deletions DevProxy.Proxy.Kestrel.Tests/CertificateAuthorityTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down Expand Up @@ -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));
}
Expand Down Expand Up @@ -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");

Expand All @@ -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");

Expand Down
5 changes: 5 additions & 0 deletions DevProxy.Proxy.Kestrel/IServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ namespace Microsoft.Extensions.DependencyInjection;
/// plugin (signing-key chain) all resolve the <b>same</b> certificate rather than each
/// loading its own copy.
/// </para>
///
/// <para>
/// The root is loaded or created on first use, not when the CA is constructed, so
/// commands that never need it (such as <c>--version</c>) don't write it to disk.
/// </para>
/// </summary>
public static class KestrelProxyServiceCollectionExtensions
{
Expand Down
51 changes: 36 additions & 15 deletions DevProxy.Proxy.Kestrel/Internal/CertificateAuthority.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
namespace DevProxy.Proxy.Kestrel.Internal;

/// <summary>
/// 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.
///
/// <para>
Expand Down Expand Up @@ -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<X509Certificate2> _root;
private bool _isRootPersisted;
private readonly ConcurrentDictionary<string, X509Certificate2> _cache = new(StringComparer.OrdinalIgnoreCase);

public CertificateAuthority(string rootPfxPath, string leafDirectory, ILogger? logger = null)
Expand All @@ -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);
}

/// <summary>
Expand Down Expand Up @@ -111,7 +114,8 @@ internal static string ResolveRootPfxPath(string? envPath, string configDirector
}

/// <summary>The root CA certificate clients must trust to allow interception.</summary>
public X509Certificate2 RootCertificate => _ca;
/// <remarks>Loads or creates (and persists) the root on first access.</remarks>
public X509Certificate2 RootCertificate => _root.Value;

/// <summary>Path of the PKCS#12 file that stores the root certificate and its private key.</summary>
public string RootCertificatePath => _rootPfxPath;
Expand All @@ -120,9 +124,23 @@ internal static string ResolveRootPfxPath(string? envPath, string configDirector
/// Whether <see cref="RootCertificate"/> is stored on disk and will be reused by
/// subsequent runs. <c>false</c> when a newly generated root couldn't be saved.
/// </summary>
public bool IsRootPersisted { get; private set; }
/// <remarks>Loads or creates (and persists) the root on first access.</remarks>
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.
Expand All @@ -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;
}

Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -266,7 +284,7 @@ private X509Certificate2 LoadOrCreateLeaf(string host)
string.Empty,
X509KeyStorageFlags.Exportable);

var ski = _ca.Extensions
var ski = RootCertificate.Extensions
.OfType<X509SubjectKeyIdentifierExtension>()
.FirstOrDefault()?.SubjectKeyIdentifierBytes;

Expand Down Expand Up @@ -378,29 +396,29 @@ 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);

// 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);
Expand All @@ -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();
Expand Down
17 changes: 13 additions & 4 deletions DevProxy.Tests/CertCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down
Loading