Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
c855766
Add devproxy cert export to write the root certificate to a file
waldekmastykarz Nov 5, 2026
7ed4e9b
Address review: fail on unpersisted root, keep stdout clean for cert …
waldekmastykarz Nov 5, 2026
76de29c
Detect cert export regardless of option placement
waldekmastykarz Nov 5, 2026
2163522
Prevent cert export from overwriting the stored root certificate
waldekmastykarz Nov 5, 2026
e3a7918
Keep OpenSSL in CI docs pinned to v4.0.0; document cert export for la…
waldekmastykarz Nov 5, 2026
76d05b1
Merge main into cert-export-command
waldekmastykarz Nov 24, 2026
be30ce7
Merge branch 'main' into cert-export-command
waldekmastykarz Nov 24, 2026
fd53f89
Merge latest main into cert-export-command
waldekmastykarz Nov 25, 2026
678aaed
Merge branch 'main' into cert-export-command
waldekmastykarz Nov 26, 2026
29134d9
Address cert export review feedback
waldekmastykarz Nov 26, 2026
8a7041e
Detect cert export with the real root options
waldekmastykarz Nov 26, 2026
5af530e
Restore CRLF line endings in DevProxyCommand.cs
waldekmastykarz Nov 26, 2026
f53c33e
Allow plugin options before cert export in command detection
waldekmastykarz Nov 26, 2026
d3937f5
Let the file system decide whether paths differing in case are the sa…
waldekmastykarz Nov 26, 2026
1b6085a
Merge branch 'main' into cert-export-command
waldekmastykarz Nov 26, 2026
5a44662
Merge remote-tracking branch 'upstream/main' into resolve-conflicts-p…
waldekmastykarz Nov 26, 2026
6b8faa8
Merge upstream/main into cert-export-command
waldekmastykarz Nov 26, 2026
97fcb48
Merge branch 'main' into cert-export-command
waldekmastykarz Nov 26, 2026
72a0b9a
Merge upstream/main into cert-export-command
waldekmastykarz Nov 27, 2026
33c94aa
Merge branch 'main' into cert-export-command
waldekmastykarz Nov 27, 2026
75c836e
Don't detect cert export when another built-in command follows plugin…
waldekmastykarz Nov 27, 2026
c0152d9
Treat built-in command names directly after plugin options as option …
waldekmastykarz Nov 27, 2026
b8c8c90
Merge upstream main into cert-export-command
waldekmastykarz Nov 27, 2026
b9a0237
Don't treat cert as cert export when it's a plugin option value
waldekmastykarz Nov 27, 2026
1247803
Detect cert export when cert is also a plugin option value
waldekmastykarz Nov 27, 2026
31c12cb
Merge remote-tracking branch 'upstream/main' into fix-conflicts-pr-2091
waldekmastykarz Nov 27, 2026
4856a7f
Merge upstream main into cert-export-command
waldekmastykarz Nov 27, 2026
7f4be19
Restore trailing newline in DevProxyCommand.cs
waldekmastykarz Nov 27, 2026
9cb903e
Resolve cert export from the real parse instead of guessing
waldekmastykarz Nov 27, 2026
40324d0
Document plugin options with cert export
waldekmastykarz Nov 27, 2026
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
144 changes: 142 additions & 2 deletions DevProxy.Integration.Tests/ProcessSmokeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ private static JsonElement GetResultData(string output)
throw new InvalidOperationException("Command did not emit a JSON result.");
}

private static async Task<(int ExitCode, string Output)> RunCommandAsync(
private static async Task<(int ExitCode, string Output, string Error)> RunCommandAsync(
string host, string workDir, IEnumerable<string> args, IReadOnlyDictionary<string, string>? environment = null)
{
var startInfo = new ProcessStartInfo(host)
Expand Down Expand Up @@ -474,7 +474,7 @@ private static JsonElement GetResultData(string output)
{
await process.WaitForExitAsync(timeout.Token);
await Task.WhenAll(output, error);
return (process.ExitCode, await output);
return (process.ExitCode, await output, await error);
}
finally
{
Expand All @@ -486,6 +486,146 @@ private static JsonElement GetResultData(string output)
}
}

// Options before a command can't be fully resolved until plugins register theirs, so these
// run the real host to verify which command runs and where its output goes.
[Theory]
[InlineData(new[] { "cert", "export" }, "text")]
[InlineData(new[] { "--log-level", "debug", "cert", "export" }, "text")]
[InlineData(new[] { "cert", "export", "--output", "json" }, "json")]
public async Task CertExport_WritesOnlyResultToStdout(string[] args, string output)
{
var host = Path.Combine(Path.GetDirectoryName(LocateHostDll())!,
OperatingSystem.IsWindows() ? "devproxy.exe" : "devproxy");
var workDir = Directory.CreateTempSubdirectory("devproxy-cert-export-");
try
{
await WriteCommandConfigAsync(workDir.FullName);
var file = Path.Combine(workDir.FullName, "ca.pem");

var result = await RunCommandAsync(host, workDir.FullName, [.. args, "--file", file], GetCommandEnvironment(workDir.FullName));

Assert.Equal(0, result.ExitCode);
Assert.True(File.Exists(file), result.Error);
string? exportedPath;
if (output == "json")
{
using var json = JsonDocument.Parse(result.Output);
exportedPath = json.RootElement.GetProperty("path").GetString();
}
else
{
exportedPath = result.Output.Trim();
}
Assert.Equal(Path.GetFileName(file), Path.GetFileName(exportedPath));
// First run creates the root certificate, which is logged to stderr
Assert.Contains("root certificate", result.Error, StringComparison.Ordinal);
}
finally
{
workDir.Delete(recursive: true);
}
}

// cert is the value of a plugin option here, so the export runs but plugins that initialize
// before the command is resolved may still log to stdout
[Fact]
public async Task CertExport_AfterPluginOptionWithCertValue_ExportsCertificate()
{
var host = Path.Combine(Path.GetDirectoryName(LocateHostDll())!,
OperatingSystem.IsWindows() ? "devproxy.exe" : "devproxy");
var workDir = Directory.CreateTempSubdirectory("devproxy-cert-export-");
try
{
await WriteCommandConfigAsync(workDir.FullName);
var file = Path.Combine(workDir.FullName, "ca.pem");

var result = await RunCommandAsync(host, workDir.FullName,
["--mocks-file", "cert", "cert", "export", "--output", "json", "--file", file],
GetCommandEnvironment(workDir.FullName));

Assert.Equal(0, result.ExitCode);
Assert.True(File.Exists(file), result.Error);
Assert.Contains("\"path\"", result.Output, StringComparison.Ordinal);
}
finally
{
workDir.Delete(recursive: true);
}
}

// cert and export are values of plugin options or arguments of a plugin command here
[Theory]
[InlineData("--failure-rate", "10", "mocks", "from-http-responses", "cert", "export", "--mocks-file", "out.json")]
[InlineData("--no-mocks", "mocks", "from-http-responses", "cert", "export", "--mocks-file", "generated.json")]
public async Task PluginCommand_WithCertExportArguments_ReportsPluginErrors(params string[] args)
{
var host = Path.Combine(Path.GetDirectoryName(LocateHostDll())!,
OperatingSystem.IsWindows() ? "devproxy.exe" : "devproxy");
var workDir = Directory.CreateTempSubdirectory("devproxy-cert-export-");
try
{
await WriteCommandConfigAsync(workDir.FullName);

var result = await RunCommandAsync(host, workDir.FullName, args, GetCommandEnvironment(workDir.FullName));

Assert.Equal(1, result.ExitCode);
Assert.Contains("No matching HTTP response files found", result.Error, StringComparison.Ordinal);
Assert.False(File.Exists(Path.Combine(workDir.FullName, "dev-proxy-ca.pem")));
}
finally
{
workDir.Delete(recursive: true);
}
}

[Theory]
[InlineData("--mocks-file", "cert", "--watch-process-names", "export", "jwt", "create", "--output", "json")]
[InlineData("--mocks-file", "cert", "jwt", "create", "--scopes", "export", "--output", "json")]
public async Task JwtCreate_WithCertExportArguments_WritesResultToStdout(params string[] args)
{
var host = Path.Combine(Path.GetDirectoryName(LocateHostDll())!,
OperatingSystem.IsWindows() ? "devproxy.exe" : "devproxy");
var workDir = Directory.CreateTempSubdirectory("devproxy-cert-export-");
try
{
await WriteCommandConfigAsync(workDir.FullName);

var result = await RunCommandAsync(host, workDir.FullName, args, GetCommandEnvironment(workDir.FullName));

Assert.Equal(0, result.ExitCode);
Assert.False(string.IsNullOrEmpty(GetResultData(result.Output).GetProperty("token").GetString()));
Assert.False(File.Exists(Path.Combine(workDir.FullName, "dev-proxy-ca.pem")));
}
finally
{
workDir.Delete(recursive: true);
}
}

private static async Task WriteCommandConfigAsync(string workDir)
{
var config = JsonNode.Parse(ConfigFile)!.AsObject();
config["installCert"] = false;
config["noFirstRun"] = true;
config["validateSchemas"] = false;
// Registers --failure-rate
config["plugins"]!.AsArray().Insert(0, new JsonObject
{
["name"] = "GenericRandomErrorPlugin",
["enabled"] = true,
["pluginPath"] = "~appFolder/plugins/DevProxy.Plugins.dll",
["configSection"] = "errorsPlugin"
});
config["errorsPlugin"] = new JsonObject { ["errorsFile"] = "errors.json" };
await File.WriteAllTextAsync(Path.Combine(workDir, "errors.json"), """{ "errors": [] }""");
await File.WriteAllTextAsync(Path.Combine(workDir, "mocks.json"), MocksFile);
await File.WriteAllTextAsync(Path.Combine(workDir, "devproxyrc.json"), config.ToJsonString());
}

// Isolates the root certificate so that tests don't create or reuse the user's one
private static Dictionary<string, string> GetCommandEnvironment(string workDir) =>
new() { ["DEV_PROXY_CERT_PATH"] = Path.Combine(workDir, "rootCert.pfx") };

[Fact]
public async Task Host_LoadsMockPluginFromConfig_AndServesMock()
{
Expand Down
25 changes: 25 additions & 0 deletions DevProxy.Proxy.Kestrel.Tests/CertificateAuthorityTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,31 @@ public void RelativeEnvPath_PersistsRootInSubfolder()
Assert.True(File.Exists(Path.Combine(_dir, "rootCert", "rootCert.pfx")));
}

[Fact]
public void IsRootPersisted_TrueForNewSavedRootAndReloadedRoot()
{
using (var first = new CertificateAuthority(_rootPath, _leafDir))
{
Assert.True(first.IsRootPersisted);
}

using var second = new CertificateAuthority(_rootPath, _leafDir);
Assert.True(second.IsRootPersisted);
}

[Fact]
public void IsRootPersisted_FalseWhenRootCannotBeSaved()
{
// A file where the root's parent directory should be makes the save fail.
var blocker = Path.Combine(_dir, "blocker");
File.WriteAllText(blocker, string.Empty);

using var ca = new CertificateAuthority(Path.Combine(blocker, "rootCert.pfx"), _leafDir);

Assert.NotNull(ca.RootCertificate);
Assert.False(ca.IsRootPersisted);
}

[Fact]
public void FirstRun_CreatesValidRoot_AndPersistsToDisk()
{
Expand Down
9 changes: 4 additions & 5 deletions DevProxy.Proxy.Kestrel.Tests/WebSocketRelayTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,12 +132,11 @@ await clientWs.SendAsync(
await relayTask;

// Verify captured messages (origin→client "origin-frame", client→origin "client-frame", close).
// Each direction is relayed independently, and an origin frame is captured after it's
// forwarded, so the client's reply can be captured first.
var messages = capturedMessages.ToArray();
Assert.True(messages.Length >= 2, $"Expected at least 2 messages, got {messages.Length}");
Assert.Equal(WebSocketMessageDirection.Receive, messages[0].Direction);
Assert.Equal("origin-frame", messages[0].Text);
Assert.Equal(WebSocketMessageDirection.Send, messages[1].Direction);
Assert.Equal("client-frame", messages[1].Text);
Assert.Contains(messages, m => m.Direction == WebSocketMessageDirection.Receive && m.Text == "origin-frame");
Assert.Contains(messages, m => m.Direction == WebSocketMessageDirection.Send && m.Text == "client-frame");
}

[Fact]
Expand Down
11 changes: 11 additions & 0 deletions DevProxy.Proxy.Kestrel/Internal/CertificateAuthority.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,15 @@ internal static string ResolveRootPfxPath(string? envPath, string configDirector
/// <summary>The root CA certificate clients must trust to allow interception.</summary>
public X509Certificate2 RootCertificate => _ca;

/// <summary>Path of the PKCS#12 file that stores the root certificate and its private key.</summary>
public string RootCertificatePath => _rootPfxPath;

/// <summary>
/// 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; }

public X509Certificate2 GetCertificateForHost(string host) => _cache.GetOrAdd(host, LoadOrCreateLeaf);

// Mirrors Titanium's CertificateDiskCache.GetRootCertificateDirectory: on Windows the
Expand All @@ -137,6 +146,7 @@ private X509Certificate2 LoadOrCreateRoot()
if (existing is not null)
{
_logger.LogDebug("Loaded persisted root certificate from {Path}", _rootPfxPath);
IsRootPersisted = true;
return existing;
}

Expand Down Expand Up @@ -201,6 +211,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;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Expand Down
Loading
Loading