Skip to content

Commit 7e82379

Browse files
Make DevToolsPlugin usable from containers and secure its WebSocket. Closes #2005 (#2008)
* Make DevToolsPlugin usable from containers and secure its WebSocket. Closes #2005 - Add `port` setting to listen on a fixed port (0, default, picks a random port) - Add `launchBrowser` setting; when false, log a devtools:// URL to open manually - Bind the DevTools WebSocket to the proxy's IP address (0.0.0.0 -> all interfaces) and start it after command-line options are applied so --ip-address is honored - Require a random per-run token in the WebSocket path and only accept connections from DevTools frontend origins - Update the v4.0.0 schema and skill docs; add tests Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Escape control characters in logged DevTools Origin header Addresses CodeQL log-injection alert: the Origin header is client-controlled and the listener may be network-reachable. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Fall back to loopback when DevTools can't listen on all interfaces On Windows, HttpListener needs admin rights or a URL ACL for the * prefix, so with --ip-address 0.0.0.0 the DevTools plugin would otherwise fail where it previously worked on 127.0.0.1. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 0a46e08 commit 7e82379

6 files changed

Lines changed: 325 additions & 23 deletions

File tree

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
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 System.Net.WebSockets;
6+
using DevProxy.Plugins.Inspection;
7+
using Microsoft.Extensions.Logging.Abstractions;
8+
using Xunit;
9+
10+
namespace DevProxy.Integration.Tests;
11+
12+
/// <summary>
13+
/// Covers the DevToolsPlugin WebSocket server's access checks (path token
14+
/// and Origin) and how it maps the proxy IP address to the listener host.
15+
/// </summary>
16+
public sealed class DevToolsWebSocketServerTests
17+
{
18+
private const string Token = "4f2b8f0e-7c1d-4b8e-9d3a-2a6f5e1c0b9d";
19+
20+
[Theory]
21+
[InlineData("devtools://devtools")]
22+
[InlineData("http://localhost:9222")]
23+
[InlineData("http://127.0.0.1:9222")]
24+
public async Task AcceptsConnection_WithTokenAndDevToolsOrigin(string origin)
25+
{
26+
using var server = StartServer(out var port);
27+
28+
using var client = await ConnectAsync(port, Token, origin);
29+
30+
Assert.Equal(WebSocketState.Open, client.State);
31+
}
32+
33+
[Theory]
34+
[InlineData("")]
35+
[InlineData("wrong")]
36+
[InlineData(Token + "/extra")]
37+
public async Task RejectsConnection_WithInvalidToken(string path)
38+
{
39+
using var server = StartServer(out var port);
40+
41+
_ = await Assert.ThrowsAsync<WebSocketException>(() => ConnectAsync(port, path, "devtools://devtools"));
42+
}
43+
44+
[Theory]
45+
[InlineData("https://example.com")]
46+
[InlineData("http://localhost:3000")]
47+
[InlineData("null")]
48+
[InlineData(null)]
49+
public async Task RejectsConnection_FromOtherOrigins(string? origin)
50+
{
51+
using var server = StartServer(out var port);
52+
53+
_ = await Assert.ThrowsAsync<WebSocketException>(() => ConnectAsync(port, Token, origin));
54+
}
55+
56+
[Theory]
57+
[InlineData(null, "127.0.0.1", "127.0.0.1")]
58+
[InlineData("", "127.0.0.1", "127.0.0.1")]
59+
[InlineData("127.0.0.1", "127.0.0.1", "127.0.0.1")]
60+
[InlineData("0.0.0.0", "*", "127.0.0.1")]
61+
[InlineData("::", "*", "127.0.0.1")]
62+
[InlineData("192.168.1.10", "192.168.1.10", "192.168.1.10")]
63+
[InlineData("::1", "[::1]", "[::1]")]
64+
public void GetWebSocketHosts_MapsProxyIPAddress(string? ipAddress, string expectedListenerHost, string expectedConnectHost)
65+
{
66+
var (listenerHost, connectHost) = DevToolsPlugin.GetWebSocketHosts(ipAddress);
67+
68+
Assert.Equal(expectedListenerHost, listenerHost);
69+
Assert.Equal(expectedConnectHost, connectHost);
70+
}
71+
72+
[Theory]
73+
[InlineData(null, "(none)")]
74+
[InlineData("https://example.com", "https://example.com")]
75+
[InlineData("https://evil\r\n[WS] forged", "https://evil\\u000d\\u000a[WS] forged")]
76+
public void SanitizeForLog_EscapesControlCharacters(string? value, string expected)
77+
{
78+
Assert.Equal(expected, WebSocketServer.SanitizeForLog(value));
79+
}
80+
81+
private static WebSocketServer StartServer(out int port)
82+
{
83+
port = NetUtil.GetFreePort();
84+
var server = new WebSocketServer("127.0.0.1", port, Token, NullLogger.Instance);
85+
server.Start();
86+
return server;
87+
}
88+
89+
private static async Task<ClientWebSocket> ConnectAsync(int port, string path, string? origin)
90+
{
91+
var client = new ClientWebSocket();
92+
if (origin is not null)
93+
{
94+
client.Options.SetRequestHeader("Origin", origin);
95+
}
96+
97+
try
98+
{
99+
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
100+
await client.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/{path}"), cts.Token);
101+
return client;
102+
}
103+
catch
104+
{
105+
client.Dispose();
106+
throw;
107+
}
108+
}
109+
}

‎DevProxy.Plugins/Inspection/DevToolsPlugin.cs‎

Lines changed: 124 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,21 @@ public sealed class DevToolsPluginConfiguration
4040
/// <remarks>Use this value when you install the browser in a non-standard
4141
/// path.</remarks>
4242
public string PreferredBrowserPath { get; set; } = string.Empty;
43+
44+
/// <summary>
45+
/// Port on which the plugin listens for DevTools connections. 0 (default)
46+
/// picks a random available port.
47+
/// </summary>
48+
/// <remarks>Use a fixed port when you need to publish it, eg. when running
49+
/// Dev Proxy in a container.</remarks>
50+
public int Port { get; set; }
51+
52+
/// <summary>
53+
/// Whether to launch the browser with DevTools. When false, the plugin
54+
/// only logs the DevTools URL, which you can open in Microsoft Edge or
55+
/// Google Chrome yourself.
56+
/// </summary>
57+
public bool LaunchBrowser { get; set; } = true;
4358
}
4459

4560
public sealed class DevToolsPlugin(
@@ -74,6 +89,7 @@ public sealed class DevToolsPlugin(
7489
private readonly Lock _replayLock = new();
7590

7691
private CancellationToken? _cancellationToken;
92+
private bool _isProxyCommand;
7793
private WebSocketServer? _webSocket;
7894

7995
public override string Name => nameof(DevToolsPlugin);
@@ -91,7 +107,19 @@ public override async Task InitializeAsync(InitArgs e, CancellationToken cancell
91107
return;
92108
}
93109

94-
InitInspector();
110+
_isProxyCommand = true;
111+
}
112+
113+
public override void OptionsLoaded(OptionsLoadedArgs e)
114+
{
115+
base.OptionsLoaded(e);
116+
117+
// start the inspector after command-line options have been applied
118+
// so that it binds to the IP address specified using --ip-address
119+
if (_isProxyCommand)
120+
{
121+
InitInspector();
122+
}
95123
}
96124

97125
public override async Task BeforeRequestAsync(ProxyRequestArgs e, CancellationToken cancellationToken)
@@ -886,30 +914,63 @@ private void InitInspector()
886914
{
887915
var browserPath = string.Empty;
888916

889-
try
917+
if (Configuration.LaunchBrowser)
890918
{
891-
browserPath = GetBrowserPath();
919+
try
920+
{
921+
browserPath = GetBrowserPath();
922+
}
923+
catch (NotSupportedException ex)
924+
{
925+
Logger.LogError(ex, "Error starting {Plugin}. Error finding the browser.", Name);
926+
return;
927+
}
928+
929+
// check if the browser is installed
930+
if (!File.Exists(browserPath))
931+
{
932+
Logger.LogError("Error starting {Plugin}. Browser executable not found at {BrowserPath}", Name, browserPath);
933+
return;
934+
}
892935
}
893-
catch (NotSupportedException ex)
936+
937+
if (Configuration.Port is < 0 or > IPEndPoint.MaxPort)
894938
{
895-
Logger.LogError(ex, "Error starting {Plugin}. Error finding the browser.", Name);
939+
Logger.LogError("Error starting {Plugin}. {Port} must be between 0 and {MaxPort} but was {Value}", Name, nameof(Configuration.Port), IPEndPoint.MaxPort, Configuration.Port);
896940
return;
897941
}
898942

899-
// check if the browser is installed
900-
if (!File.Exists(browserPath))
943+
var port = Configuration.Port == 0 ? GetFreePort() : Configuration.Port;
944+
// random token required in the WebSocket path so that only clients
945+
// that got the URL from Dev Proxy can connect
946+
var token = Guid.NewGuid().ToString();
947+
var (listenerHost, connectHost) = GetWebSocketHosts(ProxyConfiguration.IPAddress);
948+
949+
_webSocket = TryStartWebSocketServer(listenerHost, port, token, out var startException);
950+
if (_webSocket is null && listenerHost == "*")
951+
{
952+
// on Windows, listening on all interfaces requires admin rights
953+
// or a URL ACL; fall back to loopback so the plugin keeps working
954+
Logger.LogWarning(startException, "{Plugin} couldn't listen for DevTools connections on all interfaces. Listening on 127.0.0.1 instead, so DevTools can only connect from this machine", Name);
955+
listenerHost = "127.0.0.1";
956+
_webSocket = TryStartWebSocketServer(listenerHost, port, token, out startException);
957+
}
958+
959+
if (_webSocket is null)
901960
{
902-
Logger.LogError("Error starting {Plugin}. Browser executable not found at {BrowserPath}", Name, browserPath);
961+
Logger.LogError(startException, "Error starting {Plugin}. Couldn't listen for DevTools connections on {Host}:{Port}", Name, listenerHost, port);
903962
return;
904963
}
905964

906-
var port = GetFreePort();
907-
_webSocket = new(port, Logger);
908-
_webSocket.MessageReceived += SocketMessageReceived;
909-
_webSocket.ClientConnected += OnWebSocketClientConnected;
910-
_ = _webSocket.StartAsync();
965+
var webSocketAddress = $"{connectHost}:{port}/{token}";
911966

912-
var inspectionUrl = $"http://localhost:9222/devtools/inspector.html?ws=127.0.0.1:{port}";
967+
if (!Configuration.LaunchBrowser)
968+
{
969+
Logger.LogInformation("{Name} available at devtools://devtools/bundled/inspector.html?ws={WebSocketAddress}. Open this URL in Microsoft Edge or Google Chrome to inspect requests.", Name, webSocketAddress);
970+
return;
971+
}
972+
973+
var inspectionUrl = $"http://localhost:9222/devtools/inspector.html?ws={webSocketAddress}";
913974
var profilePath = Path.Combine(Path.GetTempPath(), "devtools-devproxy");
914975
var args = $"{inspectionUrl} --remote-debugging-port=9222 --user-data-dir=\"{profilePath}\"";
915976

@@ -1047,6 +1108,55 @@ private static int GetFreePort()
10471108
return port;
10481109
}
10491110

1111+
/// <summary>
1112+
/// Gets the host to listen on for DevTools connections, matching the
1113+
/// proxy's IP address, and the host DevTools should connect to.
1114+
/// </summary>
1115+
private WebSocketServer? TryStartWebSocketServer(string host, int port, string token, out Exception? exception)
1116+
{
1117+
var server = new WebSocketServer(host, port, token, Logger);
1118+
try
1119+
{
1120+
server.Start();
1121+
}
1122+
catch (Exception ex) when (ex is HttpListenerException or SocketException)
1123+
{
1124+
server.Dispose();
1125+
exception = ex;
1126+
return null;
1127+
}
1128+
1129+
server.MessageReceived += SocketMessageReceived;
1130+
server.ClientConnected += OnWebSocketClientConnected;
1131+
exception = null;
1132+
return server;
1133+
}
1134+
1135+
internal static (string ListenerHost, string ConnectHost) GetWebSocketHosts(string? ipAddress)
1136+
{
1137+
if (string.IsNullOrWhiteSpace(ipAddress))
1138+
{
1139+
return ("127.0.0.1", "127.0.0.1");
1140+
}
1141+
1142+
if (!IPAddress.TryParse(ipAddress, out var address))
1143+
{
1144+
return (ipAddress, ipAddress);
1145+
}
1146+
1147+
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
1148+
{
1149+
// listen on all interfaces; connect through loopback, which is
1150+
// where published container ports and forwarded ports end up
1151+
return ("*", "127.0.0.1");
1152+
}
1153+
1154+
var host = address.AddressFamily == AddressFamily.InterNetworkV6
1155+
? $"[{address}]"
1156+
: address.ToString();
1157+
return (host, host);
1158+
}
1159+
10501160
private static string GetRequestId(IProxySession? session)
10511161
{
10521162
if (session is null)

0 commit comments

Comments
 (0)