Skip to content

Commit ece57ef

Browse files
Don't register as system proxy or install root cert by default in CI (#2093)
* Don't register as system proxy or install root cert by default in CI When the CI environment variable is set, asSystemProxy and installCert default to false unless set explicitly in the config file or on the command line. Dev Proxy logs the effective values and how to override them at startup. Closes #2059 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Add parser-level tests for --install-cert validation with CI defaults Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent ac6aee9 commit ece57ef

5 files changed

Lines changed: 230 additions & 26 deletions

File tree

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using DevProxy.Commands;
6+
using DevProxy.Proxy;
7+
using Microsoft.Extensions.Configuration;
8+
using System.CommandLine;
9+
using Xunit;
10+
11+
namespace DevProxy.Tests;
12+
13+
public class ProxyConfigurationCiDefaultsTests
14+
{
15+
private static ProxyConfiguration Create(bool isCi, Dictionary<string, string?>? settings = null)
16+
{
17+
var configurationRoot = new ConfigurationBuilder()
18+
.AddInMemoryCollection(settings ?? [])
19+
.Build();
20+
return new ProxyConfiguration(configurationRoot, isCi);
21+
}
22+
23+
[Fact]
24+
public void NotCi_KeepsDefaults()
25+
{
26+
var config = Create(isCi: false);
27+
28+
Assert.True(config.AsSystemProxy);
29+
Assert.True(config.InstallCert);
30+
Assert.False(config.AsSystemProxyDefaultedForCi);
31+
Assert.False(config.InstallCertDefaultedForCi);
32+
}
33+
34+
[Fact]
35+
public void Ci_NotSetInConfig_DisablesSystemProxyAndCertInstall()
36+
{
37+
var config = Create(isCi: true);
38+
39+
Assert.False(config.AsSystemProxy);
40+
Assert.False(config.InstallCert);
41+
Assert.True(config.AsSystemProxyDefaultedForCi);
42+
Assert.True(config.InstallCertDefaultedForCi);
43+
}
44+
45+
[Theory]
46+
[InlineData("true", true)]
47+
[InlineData("false", false)]
48+
public void Ci_SetInConfig_KeepsConfiguredValues(string value, bool expected)
49+
{
50+
var config = Create(isCi: true, new()
51+
{
52+
["asSystemProxy"] = value,
53+
["installCert"] = value,
54+
});
55+
56+
Assert.Equal(expected, config.AsSystemProxy);
57+
Assert.Equal(expected, config.InstallCert);
58+
Assert.False(config.AsSystemProxyDefaultedForCi);
59+
Assert.False(config.InstallCertDefaultedForCi);
60+
}
61+
62+
[Fact]
63+
public void Ci_OnlyAsSystemProxyInConfig_DefaultsInstallCertOnly()
64+
{
65+
var config = Create(isCi: true, new() { ["asSystemProxy"] = "true" });
66+
67+
Assert.True(config.AsSystemProxy);
68+
Assert.False(config.InstallCert);
69+
Assert.False(config.AsSystemProxyDefaultedForCi);
70+
Assert.True(config.InstallCertDefaultedForCi);
71+
}
72+
73+
[Fact]
74+
public void ShouldLogCiDefaults_NotCi_ReturnsFalse()
75+
{
76+
Assert.False(DevProxyCommand.ShouldLogCiDefaults(Create(isCi: false), null, null));
77+
}
78+
79+
[Fact]
80+
public void ShouldLogCiDefaults_CiDefaultsApplied_ReturnsTrue()
81+
{
82+
Assert.True(DevProxyCommand.ShouldLogCiDefaults(Create(isCi: true), null, null));
83+
}
84+
85+
[Fact]
86+
public void ShouldLogCiDefaults_OneOverriddenOnCommandLine_ReturnsTrue()
87+
{
88+
Assert.True(DevProxyCommand.ShouldLogCiDefaults(Create(isCi: true), true, null));
89+
}
90+
91+
[Fact]
92+
public void ShouldLogCiDefaults_BothOverriddenOnCommandLine_ReturnsFalse()
93+
{
94+
Assert.False(DevProxyCommand.ShouldLogCiDefaults(Create(isCi: true), true, true));
95+
}
96+
97+
private static ParseResult ParseInstallCert(ProxyConfiguration config, params string[] args)
98+
{
99+
var asSystemProxyOption = new Option<bool?>(DevProxyCommand.AsSystemProxyOptionName);
100+
var command = new RootCommand
101+
{
102+
asSystemProxyOption,
103+
DevProxyCommand.CreateInstallCertOption(asSystemProxyOption, config),
104+
};
105+
return command.Parse(args);
106+
}
107+
108+
[Fact]
109+
public void InstallCertFalse_Ci_WithoutAsSystemProxy_IsAccepted()
110+
{
111+
var result = ParseInstallCert(Create(isCi: true), "--install-cert", "false");
112+
113+
Assert.Empty(result.Errors);
114+
}
115+
116+
[Fact]
117+
public void InstallCertFalse_AsSystemProxyFalseInConfig_WithoutAsSystemProxy_IsAccepted()
118+
{
119+
var config = Create(isCi: false, new() { ["asSystemProxy"] = "false" });
120+
121+
var result = ParseInstallCert(config, "--install-cert", "false");
122+
123+
Assert.Empty(result.Errors);
124+
}
125+
126+
[Fact]
127+
public void InstallCertFalse_AsSystemProxyTrueInConfig_IsRejected()
128+
{
129+
var config = Create(isCi: true, new() { ["asSystemProxy"] = "true" });
130+
131+
var result = ParseInstallCert(config, "--install-cert", "false");
132+
133+
Assert.Contains(result.Errors, e => e.Message.Contains(DevProxyCommand.AsSystemProxyOptionName, StringComparison.Ordinal));
134+
}
135+
136+
[Fact]
137+
public void InstallCertFalse_AsSystemProxyTrueOnCommandLine_IsRejected()
138+
{
139+
var result = ParseInstallCert(Create(isCi: true), "--install-cert", "false", "--as-system-proxy", "true");
140+
141+
Assert.NotEmpty(result.Errors);
142+
}
143+
}

‎DevProxy/Commands/DevProxyCommand.cs‎

Lines changed: 50 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,32 @@ public async Task<int> InvokeAsync(string[] args, WebApplication app)
436436
return exitCode;
437437
}
438438

439+
internal static Option<bool?> CreateInstallCertOption(Option<bool?> asSystemProxyOption, IProxyConfiguration proxyConfiguration)
440+
{
441+
var installCertOption = new Option<bool?>(InstallCertOptionName)
442+
{
443+
Description = "Install and trust the root certificate (default: true, false when CI is set). On Linux, trust it manually",
444+
HelpName = "true|false"
445+
};
446+
installCertOption.Validators.Add(input =>
447+
{
448+
try
449+
{
450+
var asSystemProxy = input.GetValue(asSystemProxyOption) ?? proxyConfiguration.AsSystemProxy;
451+
var installCert = input.GetValue(installCertOption) ?? proxyConfiguration.InstallCert;
452+
if (asSystemProxy && !installCert)
453+
{
454+
input.AddError($"Requires option '{AsSystemProxyOptionName}' to be 'false'");
455+
}
456+
}
457+
catch (InvalidOperationException ex)
458+
{
459+
input.AddError(ex.Message);
460+
}
461+
});
462+
return installCertOption;
463+
}
464+
439465
// Reads the raw token rather than the parsed value, because the parsed
440466
// value isn't available when the parse result has errors
441467
internal static bool IsJsonOutputRequested(ParseResult parseResult) =>
@@ -730,31 +756,11 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions)
730756

731757
var asSystemProxyOption = new Option<bool?>(AsSystemProxyOptionName)
732758
{
733-
Description = "Register Dev Proxy as the system proxy (default: true). See https://go.devproxy.net?go=system-proxy",
759+
Description = "Register Dev Proxy as the system proxy (default: true, false when CI is set). See https://go.devproxy.net?go=system-proxy",
734760
HelpName = "true|false"
735761
};
736762

737-
var installCertOption = new Option<bool?>(InstallCertOptionName)
738-
{
739-
Description = "Install and trust the root certificate (default: true). On Linux, trust it manually",
740-
HelpName = "true|false"
741-
};
742-
installCertOption.Validators.Add(input =>
743-
{
744-
try
745-
{
746-
var asSystemProxy = input.GetValue(asSystemProxyOption) ?? true;
747-
var installCert = input.GetValue(installCertOption) ?? true;
748-
if (asSystemProxy && !installCert)
749-
{
750-
input.AddError($"Requires option '{AsSystemProxyOptionName}' to be 'false'");
751-
}
752-
}
753-
catch (InvalidOperationException ex)
754-
{
755-
input.AddError(ex.Message);
756-
}
757-
});
763+
var installCertOption = CreateInstallCertOption(asSystemProxyOption, _proxyConfiguration);
758764

759765
var timeoutOption = new Option<long?>(TimeoutOptionName, "-t")
760766
{
@@ -1008,6 +1014,7 @@ private void ConfigureFromOptions(ParseResult parseResult)
10081014
{
10091015
_proxyConfiguration.InstallCert = installCert.Value;
10101016
}
1017+
LogCiDefaults(asSystemProxy, installCert);
10111018
var timeout = parseResult.GetValueOrDefault<long?>(TimeoutOptionName);
10121019
if (timeout is not null)
10131020
{
@@ -1033,6 +1040,26 @@ private void ConfigureFromOptions(ParseResult parseResult)
10331040
}
10341041
}
10351042

1043+
private void LogCiDefaults(bool? asSystemProxyOption, bool? installCertOption)
1044+
{
1045+
if (_proxyConfiguration is not ProxyConfiguration proxyConfiguration ||
1046+
!ShouldLogCiDefaults(proxyConfiguration, asSystemProxyOption, installCertOption))
1047+
{
1048+
return;
1049+
}
1050+
1051+
_logger.LogInformation(
1052+
"CI environment detected. Using asSystemProxy: {AsSystemProxy}, installCert: {InstallCert}. To change, use {AsSystemProxyOption} and {InstallCertOption} or set asSystemProxy and installCert in the config file.",
1053+
proxyConfiguration.AsSystemProxy.ToString().ToLowerInvariant(),
1054+
proxyConfiguration.InstallCert.ToString().ToLowerInvariant(),
1055+
AsSystemProxyOptionName,
1056+
InstallCertOptionName);
1057+
}
1058+
1059+
internal static bool ShouldLogCiDefaults(ProxyConfiguration proxyConfiguration, bool? asSystemProxyOption, bool? installCertOption) =>
1060+
(proxyConfiguration.AsSystemProxyDefaultedForCi && asSystemProxyOption is null) ||
1061+
(proxyConfiguration.InstallCertDefaultedForCi && installCertOption is null);
1062+
10361063
internal static Task CheckForNewVersionInBackgroundAsync(UpdateNotification updateNotification, ReleaseType releaseType, ILogger logger, CancellationToken cancellationToken) =>
10371064
Task.Run(() => CheckForNewVersionAsync(updateNotification, releaseType, logger, cancellationToken), CancellationToken.None);
10381065

@@ -1085,4 +1112,4 @@ private async Task WriteInstanceStateAsync(string apiUrl)
10851112

10861113
await StateManager.SaveStateAsync(state);
10871114
}
1088-
}
1115+
}

‎DevProxy/Proxy/ProxyConfiguration.cs‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,42 @@ public string ConfigFile
5555
public IEnumerable<string> WatchProcessNames { get; set; } = [];
5656
public bool WatchProcessTree { get; set; }
5757

58-
public ProxyConfiguration(IConfigurationRoot configurationRoot)
58+
// True when the value wasn't set in the config file and was turned off
59+
// because Dev Proxy is running in CI.
60+
internal bool AsSystemProxyDefaultedForCi { get; private set; }
61+
internal bool InstallCertDefaultedForCi { get; private set; }
62+
63+
internal static bool IsCi => Environment.GetEnvironmentVariable("CI") is not null;
64+
65+
public ProxyConfiguration(IConfigurationRoot configurationRoot) : this(configurationRoot, IsCi)
66+
{
67+
}
68+
69+
internal ProxyConfiguration(IConfigurationRoot configurationRoot, bool isCi)
5970
{
6071
_configurationRoot = configurationRoot;
6172
_configurationRoot.Bind(this);
6273
ReportsFolder = ResolveReportsFolder(ReportsFolder, _configurationRoot);
74+
if (isCi)
75+
{
76+
ApplyCiDefaults(_configurationRoot);
77+
}
78+
}
79+
80+
// In CI, don't change machine-wide state (system proxy, trusted root
81+
// certificates) unless the config file explicitly asks for it.
82+
private void ApplyCiDefaults(IConfiguration configuration)
83+
{
84+
if (configuration[nameof(AsSystemProxy)] is null)
85+
{
86+
AsSystemProxy = false;
87+
AsSystemProxyDefaultedForCi = true;
88+
}
89+
if (configuration[nameof(InstallCert)] is null)
90+
{
91+
InstallCert = false;
92+
InstallCertDefaultedForCi = true;
93+
}
6394
}
6495

6596
// reportsFolder from the config file is relative to the config file
@@ -94,4 +125,4 @@ internal static string GetConfigFilePath(IConfigurationRoot configurationRoot)
94125
var fileInfo = provider.Source.FileProvider!.GetFileInfo(provider.Source.Path!);
95126
return fileInfo.PhysicalPath!;
96127
}
97-
}
128+
}

‎skills/dev-proxy/references/ci-cd-integration.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ Dev Proxy runs headlessly in CI/CD pipelines to automate API testing — catchin
44

55
With Dev Proxy 3.3.1 or later, every management API request requires a bearer token. Set `CI=true` in the proxy process to suppress automatic token output, and retrieve credentials explicitly with `devproxy api token`. Keep shell tracing disabled around credentials. For multiple instances, add `--pid <PID>` and use the actual API URL from `devproxy status`.
66

7+
When `CI` is set, Dev Proxy doesn't register itself as the system proxy or install its root certificate, unless you set `asSystemProxy` or `installCert` in the config file or pass `--as-system-proxy` or `--install-cert`. Point your app at Dev Proxy with `HTTPS_PROXY`/`HTTP_PROXY` and trust the root certificate as shown below.
8+
79
Use action versions that support the authenticated API. For integrations that have not yet added bearer authentication, use the CLI and authenticated HTTP examples below.
810

911
## GitHub Actions (Recommended)

‎skills/dev-proxy/references/configuration.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,8 @@ Plugin-specific override:
158158
| `watchPids` | — | `--watch-pids` | Only intercept from these PIDs |
159159
| `watchProcessNames` | — | `--watch-process-names` | Only intercept from these processes |
160160
| `watchProcessTree` | — | `--watch-process-tree` | Also intercept descendants of watched processes |
161-
| `asSystemProxy` | `true` | `--as-system-proxy` | Register as system proxy |
161+
| `asSystemProxy` | `true` (`false` when `CI` is set) | `--as-system-proxy` | Register as system proxy |
162+
| `installCert` | `true` (`false` when `CI` is set) | `--install-cert` | Install and trust the root certificate |
162163
| — | off | `--detach` | Run in detached (background) mode |
163164
| — | `text` | `--output` | Output format: `text` or `json` |
164165

0 commit comments

Comments
 (0)