Skip to content

Add 'devproxy system-proxy reset' and restore previous system proxy settings - #2100

Merged
waldekmastykarz merged 37 commits into
dotnet:mainfrom
waldekmastykarz:issue-2060-add-a-command-to-restore-system-proxy-se-ffa2f5
Dec 2, 2026
Merged

waldekmastykarz merged 37 commits into
dotnet:mainfrom
waldekmastykarz:issue-2060-add-a-command-to-restore-system-proxy-se-ffa2f5

Conversation

@waldekmastykarz

Copy link
Copy Markdown
Collaborator

Resolves #2060

Problem

A graceful shutdown turns the system proxy off, but a killed or crashed Dev Proxy leaves the OS pointing at a dead port. Even a graceful shutdown only flipped ProxyEnable/proxy state off and left Dev Proxy's ProxyServer value behind, and it turned off any proxy the user had configured before (e.g. a corporate proxy). Crash recovery only existed for detached instances (via state files); a killed foreground instance left nothing to recover from.

Changes

  • Snapshot before taking over. SystemProxyManager.Enable records the current OS proxy settings plus the owning PID in system-proxy-backup.json in the Dev Proxy config folder:
    • Windows: previous ProxyEnable / ProxyServer registry values (including "value didn't exist").
    • macOS: per network service web/secure web proxy server, port, and enabled state (networksetup -get[secure]webproxy).
    • An existing snapshot is kept, so a re-enable after a crash doesn't overwrite the original settings with Dev Proxy's.
  • Restore instead of just disabling. Disable puts the snapshot back (Windows: set/delete registry values + WinINET refresh; macOS: toggle-proxy.sh off, then networksetup to restore previous servers/states). Without a snapshot it behaves as before. If restoring fails, the snapshot is kept so it can be retried.
  • New command: devproxy system-proxy reset [--force]. Restores the settings Dev Proxy changed and removes stale instance records. Refuses (exit 1) when a live Dev Proxy owns the system proxy unless --force is passed. On Linux, where Dev Proxy doesn't change the system proxy, it's a no-op.
  • Automatic recovery on startup. Startup reconciliation now also runs for foreground starts (previously only --detach) and treats a snapshot whose PID is dead as a stale registration, so killed foreground instances are recovered too. It never touches settings owned by a live instance.

Notes / decisions

  • Command name: the issue suggested devproxy proxy reset (name TBD). I went with devproxy system-proxy reset since devproxy proxy is ambiguous with Dev Proxy itself. Happy to rename.
  • Startup cleanup is automatic in all sessions rather than prompting in interactive ones, consistent with the existing detached-mode reconciliation and to avoid blocking startup on input.
  • Linux: Dev Proxy doesn't configure gsettings today (it only logs a hint), so there's nothing to snapshot/restore there.
  • Docs: the troubleshooting page (No internet connection after using the proxy) lives in the docs repo and should mention devproxy system-proxy reset once this ships.

Testing

  • Unit tests for networksetup output parsing, restore command generation, and snapshot store round-trip/corrupt-file handling.
  • dotnet build + full DevProxy.Tests pass. Verified devproxy system-proxy reset --help and detached start/stop with --as-system-proxy false. I didn't run the restore against this machine's real system proxy settings.

…ettings

Dev Proxy now records the OS proxy settings it is about to replace (Windows
ProxyEnable/ProxyServer, macOS networksetup web/secure web proxies) together
with the owning PID, and restores them when it stops instead of just turning
the system proxy off.

Because the snapshot outlives the process, a killed or crashed instance
(foreground or detached) can be recovered:
- 'devproxy system-proxy reset' restores the settings on demand
- Dev Proxy restores a stale registration automatically on startup

Closes dotnet#2060

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@waldekmastykarz
waldekmastykarz requested a review from a team as a code owner November 5, 2026 10:47
Copilot AI balanced review requested due to automatic review settings November 5, 2026 10:47

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Proxy recovery can silently fail and delete its backup, while forced resets can disable a restored corporate proxy and configuration errors can block recovery entirely.

5 open issues
What changed in this PR

Adds system-proxy recovery to Dev Proxy, preserving previous OS settings so they can be restored after shutdown or a crash.

Changes:

  • Saves Windows and macOS proxy settings before Dev Proxy takes over.
  • Adds devproxy system-proxy reset [--force] and extends automatic recovery to foreground starts.
  • Adds tests for snapshot persistence and macOS parsing and restore commands.
File Description
DevProxy/​State/​StateManager.cs Exposes process-liveness checks for recovery.
DevProxy/​Proxy/​SystemProxySnapshot.cs Adds snapshot storage and macOS settings helpers.
DevProxy/​Proxy/​SystemProxyManager.cs Captures and restores settings; tracks live and orphaned owners.
DevProxy/​Program.cs Runs recovery before foreground startup.
DevProxy/​Commands/​SystemProxyCommand.cs Implements the reset command and force option.
DevProxy/​Commands/​StopCommand.cs Adapts stop reporting to the revised recovery results.
DevProxy/​Commands/​DevProxyCommand.cs Registers the system-proxy command.
DevProxy.Tests/​SystemProxyManagerTests.cs Tests snapshot persistence and macOS helpers.
DevProxy.Abstractions/​Proxy/​ISystemProxyManager.cs Documents restoration behavior for cleanup.

Review effort: Balanced

Comment thread DevProxy/Commands/DevProxyCommand.cs Resolved
Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
- Run 'system-proxy reset' before loading config/plugins
- Don't let an instance's shutdown undo a forced reset or another owner
- Treat networksetup timeouts/nonzero exits and toggle-proxy.sh failures as
  restore failures so the snapshot is kept
- Skip disabled macOS services in toggle-proxy.sh and propagate failures
- Report the Linux no-op before checking proxy ownership

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
Comment thread DevProxy/toggle-proxy.sh Resolved
Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
- Clear system-proxy ownership on live instances after a forced reset
- Report failed orphan restores distinctly and keep records for retry
- Continue restoring remaining macOS services after a failure
- Fail toggle-proxy.sh when listing network services fails
- Parse standalone reset args with System.CommandLine

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A partial proxy-disable failure can skip snapshot restoration, leaving affected network services without their previous corporate proxy settings even after retries.

No open issues 🎉

4 previously missed issues

In code that hasn't changed since last review

High severity Restore proxy snapshots even when disabling a service fails

DevProxy/​Proxy/​SystemProxyManager.cs:154

If toggle-proxy.sh off fails for one network service, it can still successfully disable the proxies on the other services. This condition then skips RestoreMacOS entirely, leaving those working services without their previous corporate proxy; retrying repeats the same problem while the failing service remains. Please attempt snapshot restoration even when the disable pass fails, and combine both results so the backup is still retained on either failure.

Medium severity Recognize recovery commands with global options in any position

DevProxy/​Commands/​DevProxyCommand.cs:148

The standalone recovery path is still bypassed when a recursive global option appears between the commands. For example, devproxy system-proxy --no-color reset is valid for the registered command tree, but this positional check returns false. It then builds the application host, where an empty plugins configuration throws before recovery runs. Please recognize the parsed command path independently of global-option placement so these valid invocations also work with broken configurations.

Medium severity Enforce enum validation for standalone options

DevProxy/​Commands/​SystemProxyCommand.cs:56

The registered command validates --output and --log-level as enums, but the standalone path accepts arbitrary strings here. For example, devproxy system-proxy reset --force --log-level typo changes the OS proxy settings instead of rejecting the invalid option before any side effects. Please retain the enum option types in this parser as well.

Medium severity Validate process start time to prevent stale PID ownership

DevProxy/​Proxy/​SystemProxySnapshot.cs:20

After a crash or reboot, the OS can reuse the saved PID for an unrelated process, causing startup recovery to skip restoration and an unforced reset to refuse it. Persist the owner's process start time alongside its PID, refresh both on takeover, and validate both in the ownership and orphan checks. The snapshot's existing CreatedAt cannot identify the current owner because it is preserved across takeovers.

6 resolved since last review

Review effort: Balanced

…ne reset parsing

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@waldekmastykarz

Copy link
Copy Markdown
Collaborator Author

Addressing the previously missed issues from the latest review, fixed in d14a489:

  • Restore snapshots even when disabling fails: fixed. RestoreMacOS now always runs when a snapshot exists, and either failure keeps the snapshot.
  • Global options in any position: fixed. IsSystemProxyResetCommand skips --output/--log-level (and their values) and --no-color before matching the command path.
  • Enum validation in the standalone parser: fixed. It now uses Option<OutputFormat?> and Option<LogLevel?>, so --log-level typo is rejected before any OS change.
  • PID start-time validation: not changing this here. The existing instance state (StateManager.IsProcessRunning, GetOrphanedSystemProxyStatesAsync, stop, status) identifies instances by PID only. The snapshot follows the same model on purpose, so ownership checks stay consistent across the code. If a PID is reused, the worst case is that automatic cleanup is skipped and reset asks for --force, which the error message explains. Validating start time for every PID-based check is a broader change that belongs in a separate issue.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Attached option values cause valid system-proxy reset commands to bypass the standalone recovery path, allowing broken configuration to block the reset.

1 open issue

Review effort: Balanced

Comment thread DevProxy/Commands/DevProxyCommand.cs Resolved
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A help flag in a response file is ignored, causing system-proxy reset --force --help to reset the system proxy instead of displaying help.

1 open issue
1 resolved since last review

Review effort: Balanced

Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human review is needed to assess interacting recovery, ownership, and command-routing risks that could lose recovery records or unexpectedly alter system proxy settings.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Resolve conflict in SystemProxyManager.ReconcileOrphanedSystemProxiesAsync:
keep the PR's snapshot-aware restore, and delete orphaned state records via
main's state-matching DeleteStateAsync(ProxyInstanceState) for PID-reuse safety.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 13:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because critical recovery and instance-ownership edge cases can disable active proxy settings, discard recovery data, or suppress authentication-restoration warnings.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 13:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unreadable state files can let restoration delete its snapshot while stale registrations later disable the restored corporate proxy, and detached Warning-level logging suppresses essential macOS authentication instructions.

2 open issues

Review effort: Balanced

Comment thread DevProxy/Proxy/SystemProxyManager.cs Resolved
Retiring system-proxy registrations after a restore now propagates read
failures (e.g. a locked state file) instead of skipping the record, so the
snapshot is kept for a retry rather than leaving a registration that could
undo the restored settings later.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 15:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Detached starts with --log-level Warning discard the macOS authentication warning because recovery detection relies on filtered Information-level markers, hiding instructions required to make the restored proxy usable.

2 open issues

Review effort: Balanced

Mark every message logged while restoring a crashed instance's system proxy,
so 'devproxy --detach --log-level Warning' still shows warnings like the
macOS proxy-authentication instructions.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 16:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because an unreadable backup can cause reset to report success without restoring the recorded proxy configuration or preserving recovery registrations.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings December 2, 2026 12:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

An unreadable proxy backup can trigger a destructive reset that reports success without restoring saved settings and discards recovery records needed for retry.

2 open issues

Review effort: Balanced

Comment thread DevProxy/Proxy/SystemProxySnapshot.cs Resolved
Comment thread DevProxy/Commands/SystemProxyCommand.cs Resolved
…errors visible

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 2, 2026 12:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because subtle instance-ownership and unreadable-backup paths can disable a live proxy or overwrite original system proxy settings.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

…ents-023

# Conflicts:
#	DevProxy/Commands/DevProxyCommand.cs
Copilot AI balanced review requested due to automatic review settings December 2, 2026 13:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Native Windows/macOS proxy takeover and restoration remain unvalidated, requiring human testing in disposable OS environments to verify prior-setting preservation, crash recovery, forced reset, and cleanup because failures can disrupt host connectivity.

No open issues 🎉

Review effort: Balanced

@garrytrinder garrytrinder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional test results

  • PR: #2100
  • Tested commit: 40d3daf830459057f5777cf5966af8b29359b289
  • Environment: macOS arm64; .NET SDK 11.0.100; source build; private state, logs, and certificate paths.

The full test run passed all 60 checks. The earlier detached mock-generation failure no longer occurs.
The existing thread contains the updated evidence.

Scenario or test command Expected Actual Result
Locked restore and source build Both commands succeed without source changes Stable SDK 11.0.100 succeeded; build produced zero warnings and zero errors; lock files stayed unchanged PASS
CI checks for the tested commit All current checks succeed Eight checks succeeded, including tests on Windows, Ubuntu, and macOS; automated tests were not repeated locally PASS
mocks from-http-responses response.txt --mocks-file generated.json with and without --detach and --no-mocks Four commands generate the expected body without recovery All returned 0; generated body was {"ok":true}; snapshot bytes stayed unchanged; no adapter calls occurred PASS
Read-only status after plugin options, global options, and a response file Commands do not run recovery All commands kept snapshot bytes unchanged and made no adapter calls PASS
Reset help and invalid arguments Help returns 0; invalid arguments return 2; no recovery occurs Expected exit codes; snapshot stayed unchanged; parse error remained visible at --log-level None PASS
JSON reset at --log-level Warning and None, with a broken configuration Successful reset still returns a JSON result Both returned 0, emitted a result, and removed the snapshot PASS
Reset with a live snapshot owner Reset refuses without --force Exit 1; snapshot stayed present; no adapter calls occurred PASS
Stop a dead registration while another live process owns the snapshot Stop removes only the dead registration Snapshot bytes stayed unchanged; the live process remained; no adapter calls occurred PASS
Reset with an unreadable backup or registration Reset fails and keeps recovery data for a retry Exit 1; snapshot and registration remained; no adapter calls occurred; retry succeeded after permission repair PASS
Unreadable backup with a live registration Failed reset keeps the process and ownership flag Exit 1; the process remained; asSystemProxy stayed true; no adapter calls occurred PASS
Reset with an immutable snapshot or registration Failed deletion keeps the snapshot; retry succeeds Exit 1; snapshot bytes stayed unchanged; retry removed recovery files after flag removal PASS
stop --pid <owned-pid> --force with adapter failure Stop does not terminate the process or remove recovery data Exit 1; process, snapshot, and registration remained PASS
Force reset of a live registration Reset clears the ownership flag without terminating the process Exit 0; process remained; asSystemProxy became false; later stop succeeded PASS
Two dead process identities with the same PID Reset removes both registrations Reset removed the legacy record, per-PID record, and snapshot PASS
Dead legacy record and newer live record with the same PID Stop recovers the dead identity and then stops the live process Both results appeared; the process exited; both listeners closed PASS
Reset without a backup through the private adapter command Reset preserves service names and skips disabled services Exact expected calls for Wi-Fi and USB Ethernet With Spaces; no call for the disabled service PASS
Detached recovery in text and JSON, including --output:json and an absolute response file Caller receives recovery output; snapshot is removed All four starts recovered; each JSON line parsed; each API and proxied request returned the expected result PASS
Detached recovery failure at Information and Warning levels Caller receives the error; recovery data remain JSON output contained recovery errors at both levels; snapshot and registration remained until a successful retry PASS
Eight runtime starts in the full run Each process serves its API and forwards an explicit proxy request Authenticated GET /proxy returned 200; proxied requests returned 200, header X-Test: pr2100, and body {"ok":true,"source":"local"} PASS
Native capture, takeover, restoration, and authenticated-proxy warnings Native settings return to their exact prior values A disposable native environment was unavailable; governing shared-host instructions prohibit these changes BLOCKED

The detached mock commands still print Dev Proxy failed to start. The earlier base comparison produced this message too.
These commands nevertheless return 0 and create the expected file. This report does not classify the existing message as a new failure.

The initial SDK candidate could not complete locked restore. Stable SDK 11.0.100 resolved the dependency mismatch without repository changes.
Two initial test runs stopped because of test-script errors.
I corrected immutable-file cleanup order and the response-file path, verified process cleanup, and repeated the full test.

Startup exceptions and cleanup

Every runtime start kept --detach --as-system-proxy false --port 0 --api-port 0 --install-cert false --no-first-run.
Management commands did not start a foreground proxy.

Scenario Changed default Why the default prevents reproduction Execution environment Safety controls Cleanup verification
Runtime checks None beyond the stated safe launch Not applicable Private HOME, CFFIXED_USER_HOME, root certificate, and leaf certificate directory Finite command deadlines; PID and start-time records; authenticated API checks; random ports All owned processes exited; assigned listeners closed; local server stopped
Recovery paths without native changes Seeded private registrations and empty macOS snapshots Real native capture would change this shared host Owned state directory Empty recorded service list prevents native adapter calls All recovery files, state, logs, and certificates removed
Adapter failure and missing backup Private executable replaced the PATH-based networksetup command A real adapter call could change native settings Owned PATH and command log Verified the private executable before execution; never supplied a nonempty native snapshot Recorded calls matched expectations; private executable removed
Read and deletion failures Read permission removed or immutable flag set on an owned file Normal files do not reproduce the required failure Owned state files only Permission and flag repair in cleanup; retry checks All flags cleared; all owned files removed
SDK setup Private stable SDK System SDK 10.0.103 cannot build the current net11.0 target Owned SDK directory System installation unchanged Private SDK removed; no private SDK processes remained
Native restoration No exception taken Governing instructions prohibit native changes on this shared host No disposable environment System proxy and certificate trust stayed disabled No native mutation was performed

Cleanup also covered the interrupted runs.
All 13 recorded runtime PIDs across the runs exited.
All recorded listener ports closed.
All 11 process IDs from remaining daemon logs had exited.
The original branch, garrytrinder-retest-pr-2100, was restored.
The worktree is clean. No source fixes, commits, pushes, or merges were made.

The ASD-STE100 Issue 9 dictionary is unavailable without an external copy request.
I checked sentence lengths and clarity, but the STE check is incomplete.

Requested changes

None.

Outcome

Comment only. The available functional checks pass, including the previous failure.
Essential native restoration checks remain blocked, so this report does not approve the PR.
Cleanup is verified.

@garrytrinder garrytrinder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved at the user’s direction after discussion of the native-test limitation.

All 60 checks passed on this commit. The previous detached mock-generation failure no longer occurs. Cleanup is verified.

Actual macOS system-proxy changes and restoration were not tested. Those checks require a disposable native environment. This approval accepts that remaining test limitation; it does not establish native restoration correctness.

Full results: #2100 (review)

The STE dictionary is unavailable, so the language check is incomplete.

@waldekmastykarz
waldekmastykarz merged commit ca74616 into dotnet:main Dec 2, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-enhancement Product features, behavior fixes, and usability or compatibility improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add a command to restore system proxy settings after Dev Proxy was killed or crashed

3 participants