Repository navigation
Create the root certificate only when it's needed - #2174
waldekmastykarz wants to merge 10 commits into
Conversation
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<X509Certificate2> 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 dotnet#2173 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues are reported for the change that defers root certificate creation until needed.
No open issues 🎉
What changed in this PR
Addresses #2173 by deferring Dev Proxy root certificate creation until it is needed, preventing unrelated CLI commands from writing rootCert.pfx.
Changes:
- Loads or creates the certificate authority’s root lazily, while preserving stale leaf-cache cleanup before leaf loading.
- Defers certificate resolution in
CertCommanduntil a certificate action runs. - Adds regression coverage for non-proxy commands and updates unit tests for lazy initialization.
| File | Description |
|---|---|
| DevProxy/Commands/CertCommand.cs | Resolves the lazy root certificate during ensure/remove actions. |
| DevProxy.Tests/CertCommandTests.cs | Adapts command tests to the lazy certificate dependency. |
| DevProxy.Proxy.Kestrel/IServiceCollectionExtensions.cs | Registers a lazy root certificate dependency for eager consumers. |
| DevProxy.Proxy.Kestrel/Internal/CertificateAuthority.cs | Defers root initialization and avoids creating it during disposal. |
| DevProxy.Proxy.Kestrel.Tests/CertificateAuthorityTests.cs | Tests deferred creation and adjusts certificate setup ordering. |
| DevProxy.Integration.Tests/CommandExitCodeTests.cs | Checks that version and help commands do not create a root certificate. |
Review effort: Balanced
garrytrinder
left a comment
There was a problem hiding this comment.
Functional test results
- PR: #2174
- Tested commit:
e5a0f46e6d1b372349de76eda28a21c91582fbae - Environment: macOS arm64, .NET SDK 10.0.103, source-built Debug application. Private
.devproxyfixtures, random proxy/API ports, system proxy and certificate trust installation disabled.
| Scenario or test command | Expected | Actual | Result |
|---|---|---|---|
dotnet restore DevProxy.sln --locked-mode and dotnet build DevProxy.sln --no-restore |
Successful build without changing dependencies | Both succeeded; build reported 0 warnings and 0 errors | PASS |
| Automated validation on tested SHA | CI build, smoke, and platform tests succeed | Build, client smoke, and Ubuntu/Windows/macOS tests all green on the tested commit (run); automated suites were not rerun locally | PASS |
--version, --help, jwt --help, cert --help, config --help, with DEV_PROXY_CERT_PATH pointing to an absent fixture file |
Correct version/help; no root created | All exited 0 with expected output; certificate remained absent | PASS |
jwt create --name PR2174 --output json |
Valid JWT without certificate creation | Exit 0; three-part JWT decoded to the requested identity; certificate remained absent | PASS |
config new <fixture>/created-config.json |
Valid config without certificate creation | Exit 0; JSON containing plugins written; certificate remained absent |
PASS |
--not-a-real-option |
Usage error without certificate creation | Exit 2 with unrecognized-option diagnostic; certificate remained absent | PASS |
cert remove with redirected stdin and CI=1, without --force |
Refuse unconfirmed removal without resolving root | Exit 1 with confirmation-required diagnostic; certificate remained absent | PASS |
Fresh detached startup: dotnet run --no-build --no-launch-profile --project DevProxy -- --detach --as-system-proxy false --port 0 --api-port 0 --install-cert false --no-first-run --output json -c <fixture>/devproxyrc.json |
Create root only when proxy starts; owned API and real proxy traffic work | PID 45360, proxy port 49186; root persisted; authenticated /proxy and /proxy/rootCertificate?format=crt returned 200. Explicit HTTP and HTTPS requests through assigned port returned 200 and exact body pr2174 certificate lazy smoke |
PASS |
HTTPS trust without OS-store modification: export root from authenticated API, then curl --noproxy "" --proxy http://127.0.0.1:<port> --cacert <exported-root.pem> https://pr2174.invalid/hello |
Real CONNECT/TLS interception verified against exported CA, not -k |
Certificate verification succeeded; subject and issuer were CN=Dev Proxy CA; exact mock body and HTTP 200 |
PASS |
| Stop and restart using persisted root | Root reused unchanged; API and TLS remain functional | PID 46086, proxy port 49519; persisted PFX SHA-256 unchanged; root fingerprint unchanged; authenticated API, HTTP, and verified HTTPS all succeeded | PASS |
| Stop, replace private root PFX with invalid bytes, seed stale private leaf, then restart | New root generated; stale leaf removed before use; HTTPS works with new root | PID 46775, proxy port 49784; root fingerprint changed; stale leaf removed; authenticated API, HTTP, and verified HTTPS succeeded | PASS |
| Direct source-assembly CA harness with explicit private root/leaf paths | Construction/disposal remain lazy; concurrent first use creates one root; persisted leaf chains remain valid; invalid root recovery purges cache | All four checks passed, including 20 concurrent root resolutions and custom-root certificate chain validation | PASS |
Live cert ensure and forced cert remove trust-store integration |
Create/resolve root and install/remove trust correctly | Not executed: these actions invoke the machine's native security/trust tools. Avoided changing the shared host trust store; HTTPS was verified using a per-request CA file instead | BLOCKED |
| Cleanup | Only owned processes stopped; fixtures removed | PIDs 36872, 40767, 41586, 45360, 46086, and 46775 stopped with PID-scoped source-build commands; exits verified. Owned fixture tree and exact owned logs removed; worktree clean; sanitized evidence retained locally | PASS |
Requested changes
None. No reproducible PR-attributable functional defect was found.
Outcome
Comment only. The reported eager-creation reproduction and tested proxy/certificate lifecycle scenarios pass on the current head. I am not submitting an approval because live certificate-command trust-store integration was not validated. This is functional testing, not a separate code review.
All launches used detached mode, random ports, and --as-system-proxy false; trust installation remained disabled. An initial fixture-isolation attempt using only HOME and XDG_CONFIG_HOME did not redirect macOS ApplicationData, so early runs used the shared leaf-cache location (and first-run creation could invalidate its cached leaves). Concurrent testers were notified. The final complete lifecycle run used both HOME and CFFIXED_USER_HOME, with ApplicationData and detached state/log paths confirmed inside the private fixture. Root regeneration was then tested entirely in that private location.
Setup-only failures were resolved before the reported scenarios: missing restore assets, missing plugin output from an application-only build, CLI fixture argument placement, and an initial harness assembly-reference mismatch. None is reported as a PR defect.
…r-2174 # Conflicts: # DevProxy.Integration.Tests/CommandExitCodeTests.cs
garrytrinder
left a comment
There was a problem hiding this comment.
Functional test results
- PR: #2174
- Tested commit:
2933b036baa35fcf45e5aa75668345e1524a964b - Environment: macOS arm64, .NET SDK 10.0.103, source-built Debug application. This is a fresh rerun after the upstream merges, superseding the earlier report for
e5a0f46e. - Isolation: unique
.devproxy/pr2174-rerunfixtures;HOMEandCFFIXED_USER_HOMEboth point into the private fixture, withLibrary/Application Supportpre-created. ApplicationData probe and every detached log path confirmed isolation before runtime checks. UniqueDEV_PROXY_CERT_PATH; no system proxy or OS trust-store changes.
| Scenario or test command | Expected | Actual | Result |
|---|---|---|---|
dotnet restore DevProxy.sln --locked-mode then dotnet build DevProxy.sln --no-restore |
Successful source build | Succeeded, 0 warnings and 0 errors; no tracked dependency changes | PASS |
| Automated validation on current head | CI build, smoke, and platform tests succeed | Build, client smoke, Ubuntu/Windows/macOS tests, and CodeQL all succeeded on 2933b036; CI run. Automated suites were not rerun locally |
PASS |
--version, --help, jwt --help, cert --help, config --help, each with absent root path |
Correct output; root remains absent | All exit 0 with expected version/help; no root PFX created | PASS |
jwt create --name PR2174 --output json |
Valid JWT; no root created | Exit 0; three-part JWT decodes to requested identity; root absent | PASS |
config new <fixture>/created-config.json |
Valid config; no root created | Exit 0; valid JSON with plugins written; root absent |
PASS |
Newly merged plugin list --output json |
Plugin listing; no eager CA creation | Exit 0; output contains MockResponsePlugin; root absent |
PASS |
| Invalid CLI option | Exit 2; no certificate side effect | Unrecognized-option diagnostic, exit 2; root absent | PASS |
cert remove in CI without --force |
Reject before resolving root | Confirmation-required diagnostic, exit 1; root absent | PASS |
Fresh detached launch with --as-system-proxy false --port 0 --api-port 0 --install-cert false --no-first-run |
Root created on demand; API and proxy ready | PID 10999, proxy port 50362; root persisted; authenticated /proxy returned 200; exact mocked HTTP and HTTPS bodies returned with 200 |
PASS |
Export root, then curl --noproxy "" --proxy http://127.0.0.1:<assigned-port> --cacert <root.pem> https://pr2174.invalid/hello |
Real CONNECT/TLS interception, verified without -k |
Certificate verification succeeded; exact body pr2174 certificate lazy smoke, HTTP 200 |
PASS |
| Newly merged certificate API formats | Missing format, pem, and crt return same CA; invalid format rejected |
All three successful downloads were byte-identical PEM with devProxy.crt filename; invalid format returned HTTP 400. Repeated on all three successful runtime launches |
PASS |
| Stop/restart with persisted root | Root reused unchanged; traffic works | PID 11213, proxy port 54894; PFX SHA-256 and exported CA fingerprint unchanged; authenticated API, HTTP, verified HTTPS succeeded | PASS |
| Corrupt private root and seed stale private leaf, then restart | Replace invalid root; purge stale leaves; traffic works with new root | PID 11493, proxy port 55116; fingerprint changed, stale leaf removed, API/HTTP/verified HTTPS succeeded | PASS |
| Private-path CA harness against current source assembly | Constructor/disposal stay lazy; one concurrent root; valid persisted leaf reuse; correct invalid-root recovery | All four checks passed, including 20 concurrent root resolutions and custom-root certificate chain validation | PASS |
Live cert ensure and forced cert remove native trust operations |
Native trust installation/removal succeeds | Not executed: these invoke shared-host native trust tooling. Per-request CA verification was used instead | BLOCKED |
| Cleanup | Stop only owned PIDs; remove private fixtures/logs | PIDs 9991 (initial harness attempt), 10999, 11213, and 11493 stopped using PID-scoped source-build commands; process exits verified; private fixtures/logs removed; worktree clean | PASS |
Requested changes
None. No reproducible PR-attributable functional defect found.
Outcome
Comment only. The eager-creation reproduction and the exercised CLI, certificate lifecycle, HTTP/TLS, and merged API regressions pass on the tested head. Native certificate-command trust-store integration remains unvalidated, so this report does not approve that behavior or replace code review.
One initial harness assertion expected a .pem download filename for the pem alias. Inspection confirmed the merged API intentionally returns devProxy.crt for all supported aliases; the assertion was corrected and the complete matrix passed. This was a test expectation error, not a PR defect.
garrytrinder
left a comment
There was a problem hiding this comment.
Functional test results
- PR: #2174
- Tested commit:
73b77e2fb23db90b6d3c5d1591037bf8ea6c0fe7 - Environment: macOS arm64, .NET SDK 10.0.103, source-built Debug application; fresh functional rerun on November 27.
- Isolation: unique
.devproxy/pr2174-nov27fixtures, privateHOME+CFFIXED_USER_HOME, pre-createdLibrary/Application Support, uniqueDEV_PROXY_CERT_PATH. ApplicationData probe and all detached log paths confirmed private locations. System proxy and native certificate trust installation disabled.
| Scenario or test command | Expected | Actual | Result |
|---|---|---|---|
dotnet build DevProxy.sln --no-restore |
Current source builds successfully | Exit 0, 0 warnings and 0 errors | PASS |
| Automated checks on tested SHA | CI build, smoke and platform tests pass | Build, client smoke, Ubuntu/Windows/macOS tests and CodeQL green on tested head; CI run. Automated suites were not rerun locally | PASS |
--version, --help, jwt --help, cert --help, config --help with absent root path |
Correct output without eager root creation | All exit 0; expected version/help present; root remains absent | PASS |
jwt create --name PR2174 --output json |
Valid JWT without creating CA | Exit 0; three-part JWT decodes to requested identity; root absent | PASS |
config new <fixture>/created-config.json |
Valid config without creating CA | Exit 0; JSON containing plugins written; root absent |
PASS |
plugin list --output json |
Plugin listing without creating CA | Exit 0; output includes MockResponsePlugin; root absent |
PASS |
Invalid option and unconfirmed cert remove with CI=1 |
Usage/confirmation failures without resolving CA | Invalid option exits 2 with diagnostic; unconfirmed removal exits 1 with confirmation-required diagnostic; root absent in both cases | PASS |
| Private CA harness against current source | Lazy construction/disposal, single concurrent root, valid persisted leaf reuse, correct cache invalidation | Four checks pass, including 20 concurrent root resolutions and custom-root certificate chain validation | PASS |
Fresh launch using dotnet run --no-build --no-launch-profile --project DevProxy -- --detach --as-system-proxy false --port 0 --api-port 0 --install-cert false --no-first-run --output json -c <fixture>/devproxyrc.json |
Persist root on demand; owned API and proxy respond | PID 41478, proxy port 57839; root persisted; authenticated API HTTP 200; HTTP and verified HTTPS return exact mock body and HTTP 200 | PASS |
Export CA and use curl --noproxy "" --proxy http://127.0.0.1:<assigned-port> --cacert <root.pem> https://pr2174.invalid/hello |
Real CONNECT/TLS interception verified without disabling validation | TLS verification succeeds; exact body pr2174 certificate lazy smoke, HTTP 200 |
PASS |
Root API default format, pem, crt, and invalid format |
Supported aliases return same certificate; invalid input rejected | Default/pem/crt return byte-identical PEM and devProxy.crt filename; invalid format HTTP 400; repeated on all three runtime launches |
PASS |
| Stop/restart with persisted root | Reuse root unchanged; API and HTTPS continue working | PID 41675, proxy port 62172; PFX SHA-256 and exported CA fingerprint unchanged; API/HTTP/verified HTTPS pass | PASS |
| Corrupt private root, seed stale private leaf, restart | Generate new root and purge stale leaves before reuse | PID 41839, proxy port 52866; fingerprint changes, stale leaf removed; API/HTTP/verified HTTPS pass | PASS |
Live cert ensure / forced cert remove native trust integration |
Native trust installation/removal works | Not executed: these invoke native trust tooling and would mutate the shared host. Per-request CA verification is not claimed to validate native trust integration | BLOCKED |
| Cleanup | Stop only owned processes; remove owned fixtures/logs | All three owned PIDs stopped with PID-scoped source-build commands and exits verified; private fixtures/logs removed; sanitized evidence retained; worktree clean | PASS |
Requested changes
None. No reproducible PR-attributable functional defect found.
Outcome
Comment only. The complete exercised lazy-certificate matrix passes on the current head, including first creation, reuse, invalid-root recovery and verified HTTPS. Native certificate-command trust-store integration remains blocked for shared-host safety, so this feedback does not approve that untested behavior or replace code review. No PR code changes, pushes or merges were made.
Resolve conflicts with cert export (dotnet#2091): - Take upstream CertCommand, which already resolves the root lazily, and drop the now-unused Lazy<X509Certificate2> registration - Make IsRootPersisted initialize the lazy root before reporting - Initialize the root in CertCommandTests' CA helper Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
garrytrinder
left a comment
There was a problem hiding this comment.
Functional test results
- PR: #2174
- Tested commit:
214ff35735d3575a427789a14dd11e407c8eecf3 - Environment: macOS 27.2 arm64; private .NET SDK 11.0.100; source-built Debug application.
- Private paths:
.devproxy/pr2174-dec02. BothHOMEandCFFIXED_USER_HOMEused itshomedirectory. - Safety: The test created
Library/Application Supportbefore execution. The ApplicationData check and all detached log paths confirmed private locations.
| Scenario or test command | Expected | Actual | Result |
|---|---|---|---|
| Current source build | Successful build with the required SDK | System SDK 10.0.103 failed with NETSDK1045. Private SDK 11.0.100 then completed locked restore and solution build. Build: 0 warnings, 0 errors |
PASS |
| Automated checks for this commit | Build and tests succeed | Build, client smoke tests, Ubuntu/Windows/macOS tests, and CodeQL succeeded. CI run. Local execution did not repeat automated suites | PASS |
--version, --help, jwt --help, cert --help, config --help |
Correct output; no root file | Each command returned 0 and the expected output. The private root file remained absent | PASS |
jwt create --name PR2174 --output json |
Valid token; no root file | Exit 0. The JWT contained the requested identity. The root file remained absent | PASS |
config new <private-path>/created-config.json |
Valid configuration; no root file | Exit 0. The JSON file contained plugins. The root file remained absent |
PASS |
plugin list --output json |
Plugin names; no root file | Exit 0. Output contained MockResponsePlugin. The root file remained absent |
PASS |
Invalid option; cert remove without --force in CI |
Clear errors; no root file | Invalid option returned 2. Unconfirmed removal returned 1 and required confirmation. Neither command created the root | PASS |
| Private certificate authority (CA) checks | No file before first use; valid certificates after first use | Five checks passed: unused construction/disposal, IsRootPersisted first use, 20 concurrent root resolutions, saved leaf reuse, and invalid-root recovery |
PASS |
cert export --file <private-path>/exported.pem --output json with no existing root |
Create and save root; export public certificate | Exit 0. Standard output contained valid JSON with path and format. OpenSSL accepted the PEM file. No private key appeared |
PASS |
| Export DER; attempt export onto root PFX | Valid DER; no damage to saved root | OpenSSL accepted DER. Export onto the root returned 1. The root SHA-256 stayed unchanged | PASS |
| Export when root cannot be saved | Failure; no misleading public export | A private file blocked creation of the root directory. Export returned 1, reported the save failure, and created no export file | PASS |
| First detached startup | Save root; API and proxy become available | PID 88062, proxy port 60836. Root saved. Authenticated API returned 200. HTTP and verified HTTPS returned the exact mock body and 200 | PASS |
Root API: default, pem, crt, invalid format |
Same public certificate for supported formats; reject invalid format | Supported forms returned identical PEM and devProxy.crt. Invalid format returned 400. Checks passed on all three launches |
PASS |
| Restart with saved root | Reuse unchanged root; HTTPS works | PID 88177, proxy port 60982. PFX SHA-256 and public fingerprint stayed unchanged. API, HTTP, and verified HTTPS passed | PASS |
| Replace private root with invalid bytes; add stale leaf; restart | Replace root; remove stale leaf; HTTPS works | PID 88498, proxy port 61088. Root fingerprint changed. Stale leaf disappeared. API, HTTP, and verified HTTPS passed | PASS |
Native cert ensure and forced cert remove |
Verify native trust installation and removal | BLOCKED. The coordinator prohibits shared-host trust mutations. Private paths do not isolate native trust stores. Export and HTTPS do not prove native trust behavior | BLOCKED |
| ASD-STE100 check | Check prose against Issue 9 and its dictionary | Sentence structure was checked. The official dictionary was unavailable without a separate request. The STE check is incomplete; verified conformance is not claimed | BLOCKED |
HTTPS used an explicit proxy and --cacert <private-root.pem>. It did not use -k.
The exact response body was pr2174 certificate lazy smoke.
Startup exceptions and cleanup
No startup defaults changed. Every proxy launch used --detach --as-system-proxy false --port 0 --api-port 0 --install-cert false.
The tests also used --no-first-run to prevent first-run interaction.
| Scenario | Changed default | Why the default prevents reproduction | Execution environment | Safety controls | Cleanup verification |
|---|---|---|---|---|---|
| CLI, CA, export, and proxy checks | None | Not applicable | Private macOS state, root, leaf, log, configuration, and SDK paths | Finite command deadlines; private environment for launch/status/stop; random ports; PID and start-time checks | All three proxy processes ended. Both listeners closed after each stop. Private files and SDK removed. Worktree clean |
| Native trust checks | None; not executed | Native trust requires a separate disposable environment | Shared Mac; no native trust changes permitted | No native trust command executed | No native settings required restoration |
Requested changes
None. The tests found no reproducible defect attributable to this PR.
Outcome
Comment only. All executed functional checks passed on the tested commit.
Native trust checks remain blocked. This report does not approve untested native trust behavior or replace code review.
The test made no source changes, pushes, or merges.
Since v4.0.0 every
devproxycommand, including--version,--help,jwtandconfig, createsrootCert.pfx. Building the CLI eagerly createdCertCommand, which took the rootX509Certificate2, which was resolved fromCertificateAuthority, whose constructor created and saved the root.Changes
CertificateAuthorityloads or creates the root lazily on first use (RootCertificate/GetCertificateForHost), so constructing it no longer writes anything to disk. This keeps other eager dependencies from reintroducing the bug.CertCommandtakesLazy<X509Certificate2>(registered alongside the CA), so onlycert ensure/cert removeresolve the root.GetCertificateForHostinitializes the root before loading leaves, so a freshly created root still purges stale on-disk leaves first.The proxy engine, cert API endpoint and Entra mock plugin still resolve the root when they actually use it.
Tests
--version,--helpandjwt --helpwithDEV_PROXY_CERT_PATHpointing to an empty temp folder create norootCert.pfx(fails onmain, passes with this change).CertificateAuthoritytest: the constructor doesn't create the root; first access does.Closes #2173