Skip to content

Commit

Permalink
Adds IP Address option. Closes #380
Browse files Browse the repository at this point in the history
  • Loading branch information
waldekmastykarz committed Nov 21, 2023
1 parent f91dc3e commit 0594857
Show file tree
Hide file tree
Showing 6 changed files with 34 additions and 10 deletions.
1 change: 1 addition & 0 deletions dev-proxy-abstractions/IProxyConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public enum LabelMode {

public interface IProxyConfiguration {
int Port { get; }
string? IPAddress { get; }
LabelMode LabelMode { get; }
bool Record { get; }
LogLevel LogLevel { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -361,12 +361,12 @@ private async Task EvaluateMinimalScopes(IEnumerable<Tuple<string, string>> endp
using (var client = new HttpClient())
{
var stringPayload = JsonSerializer.Serialize(payload);
_logger?.LogDebug($"Calling {url} with payload{Environment.NewLine}{stringPayload}");
_logger?.LogDebug(string.Format("Calling {0} with payload{1}{2}", url, Environment.NewLine, stringPayload));

var response = await client.PostAsJsonAsync(url, payload);
var content = await response.Content.ReadAsStringAsync();

_logger?.LogDebug($"Response:{Environment.NewLine}{content}");
_logger?.LogDebug(string.Format("Response:{0}{1}", Environment.NewLine, content));

var resultsAndErrors = JsonSerializer.Deserialize<ResultsAndErrors>(content);
var minimalPermissions = resultsAndErrors?.Results?.Select(p => p.Value).ToArray() ?? Array.Empty<string>();
Expand Down Expand Up @@ -411,7 +411,7 @@ private async Task EvaluateMinimalScopes(IEnumerable<Tuple<string, string>> endp
}
catch (Exception ex)
{
_logger?.LogError($"An error has occurred while retrieving minimal permissions: {ex.Message}");
_logger?.LogError(string.Format("An error has occurred while retrieving minimal permissions: {0}", ex.Message));
}
}

Expand All @@ -420,14 +420,14 @@ private Tuple<string, string> GetMethodAndUrl(string message)
var info = message.Split(" ");
if (info.Length > 2)
{
info = new[] { info[0], String.Join(" ", info.Skip(1)) };
info = [info[0], string.Join(" ", info.Skip(1))];
}
return new Tuple<string, string>(info[0], info[1]);
}

private string GetTokenizedUrl(string absoluteUrl)
{
var sanitizedUrl = ProxyUtils.SanitizeUrl(absoluteUrl);
return "/" + String.Join("", new Uri(sanitizedUrl).Segments.Skip(2).Select(s => Uri.UnescapeDataString(s)));
return "/" + string.Join("", new Uri(sanitizedUrl).Segments.Skip(2).Select(Uri.UnescapeDataString));
}
}
7 changes: 7 additions & 0 deletions dev-proxy/ProxyCommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace Microsoft.DevProxy;

public class ProxyCommandHandler : ICommandHandler {
public Option<int?> Port { get; set; }
public Option<string?> IPAddress { get; set; }
public Option<LogLevel?> LogLevel { get; set; }
public Option<bool?> Record { get; set; }
public Option<IEnumerable<int>?> WatchPids { get; set; }
Expand All @@ -21,6 +22,7 @@ public class ProxyCommandHandler : ICommandHandler {
private readonly ILogger _logger;

public ProxyCommandHandler(Option<int?> port,
Option<string?> ipAddress,
Option<LogLevel?> logLevel,
Option<bool?> record,
Option<IEnumerable<int>?> watchPids,
Expand All @@ -30,6 +32,7 @@ public ProxyCommandHandler(Option<int?> port,
ISet<UrlToWatch> urlsToWatch,
ILogger logger) {
Port = port ?? throw new ArgumentNullException(nameof(port));
IPAddress = ipAddress ?? throw new ArgumentNullException(nameof(ipAddress));
LogLevel = logLevel ?? throw new ArgumentNullException(nameof(logLevel));
Record = record ?? throw new ArgumentNullException(nameof(record));
WatchPids = watchPids ?? throw new ArgumentNullException(nameof(watchPids));
Expand All @@ -49,6 +52,10 @@ public async Task<int> InvokeAsync(InvocationContext context) {
if (port is not null) {
Configuration.Port = port.Value;
}
var ipAddress = context.ParseResult.GetValueForOption(IPAddress);
if (ipAddress is not null) {
Configuration.IPAddress = ipAddress;
}
var logLevel = context.ParseResult.GetValueForOption(LogLevel);
if (logLevel is not null) {
_logger.LogLevel = logLevel.Value;
Expand Down
2 changes: 2 additions & 0 deletions dev-proxy/ProxyConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ namespace Microsoft.DevProxy;
public class ProxyConfiguration: IProxyConfiguration {
[JsonPropertyName("port")]
public int Port { get; set; } = 8000;
[JsonPropertyName("ipAddress")]
public string? IPAddress { get; set; }
[JsonPropertyName("labelMode")]
[JsonConverter(typeof(JsonStringEnumConverter))]
public LabelMode LabelMode { get; set; } = LabelMode.Text;
Expand Down
5 changes: 3 additions & 2 deletions dev-proxy/ProxyEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public async Task Run(CancellationToken? cancellationToken) {
var _logger2 = (ILogger)_logger.Clone();
_logger2.LogLevel = LogLevel.Warn;
// let's not await so that it doesn't block the proxy startup
MSGraphDbCommandHandler.GenerateMsGraphDb(_logger2, true);
_ = MSGraphDbCommandHandler.GenerateMsGraphDb(_logger2, true);

_proxyServer = new ProxyServer();

Expand All @@ -85,7 +85,8 @@ public async Task Run(CancellationToken? cancellationToken) {
_proxyServer.ClientCertificateSelectionCallback += OnCertificateSelection;
cancellationToken?.Register(OnCancellation);

_explicitEndPoint = new ExplicitProxyEndPoint(IPAddress.Any, _config.Port, true);
var ipAddress = string.IsNullOrEmpty(_config.IPAddress) ? IPAddress.Any : IPAddress.Parse(_config.IPAddress);
_explicitEndPoint = new ExplicitProxyEndPoint(ipAddress, _config.Port, true);
if (!RunTime.IsWindows) {
// we need to change this to a value lower than 397
// to avoid the ERR_CERT_VALIDITY_TOO_LONG error in Edge
Expand Down
19 changes: 16 additions & 3 deletions dev-proxy/ProxyHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@

using Microsoft.DevProxy.Abstractions;
using System.CommandLine;
using System.Net;

namespace Microsoft.DevProxy;

internal class ProxyHost {
private Option<int?> _portOption;
private Option<string?> _ipAddressOption;
private Option<LogLevel?> _logLevelOption;
private Option<bool?> _recordOption;
private Option<IEnumerable<int>?> _watchPidsOption;
Expand Down Expand Up @@ -61,10 +63,20 @@ public static string ConfigFile {
}

public ProxyHost() {
_portOption = new Option<int?>("--port", "The port for the proxy server to listen on");
_portOption = new Option<int?>("--port", "The port for the proxy to listen on");
_portOption.AddAlias("-p");
_portOption.ArgumentHelpName = "port";


_ipAddressOption = new Option<string?>("--ip-address", "The IP address for the proxy to bind to")
{
ArgumentHelpName = "ipAddress"
};
_ipAddressOption.AddValidator(input => {
if (!IPAddress.TryParse(input.Tokens.First().Value, out var ipAddress)) {
input.ErrorMessage = $"{input.Tokens.First().Value} is not a valid IP address";
}
});

_logLevelOption = new Option<LogLevel?>("--log-level", $"Level of messages to log. Allowed values: {string.Join(", ", Enum.GetNames(typeof(LogLevel)))}");
_logLevelOption.ArgumentHelpName = "logLevel";
_logLevelOption.AddValidator(input => {
Expand Down Expand Up @@ -99,6 +111,7 @@ public ProxyHost() {
public RootCommand GetRootCommand(ILogger logger) {
var command = new RootCommand {
_portOption,
_ipAddressOption,
_logLevelOption,
_recordOption,
_watchPidsOption,
Expand All @@ -119,6 +132,6 @@ public RootCommand GetRootCommand(ILogger logger) {
return command;
}

public ProxyCommandHandler GetCommandHandler(PluginEvents pluginEvents, ISet<UrlToWatch> urlsToWatch, ILogger logger) => new ProxyCommandHandler(_portOption, _logLevelOption, _recordOption, _watchPidsOption, _watchProcessNamesOption, _rateOption, pluginEvents, urlsToWatch, logger);
public ProxyCommandHandler GetCommandHandler(PluginEvents pluginEvents, ISet<UrlToWatch> urlsToWatch, ILogger logger) => new ProxyCommandHandler(_portOption, _ipAddressOption, _logLevelOption, _recordOption, _watchPidsOption, _watchProcessNamesOption, _rateOption, pluginEvents, urlsToWatch, logger);
}

0 comments on commit 0594857

Please sign in to comment.