Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Proxying with SSL and NetCoreApp3.1 #547

Merged
merged 7 commits into from
Dec 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions azure-pipelines-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ jobs:
script: |
$jdkPath = $env:JAVA_HOME_11_X64
Write-Host "##vso[task.setvariable variable=JAVA_HOME]$jdkPath"

- script: |
dotnet dev-certs https --trust || true
displayName: 'dotnet dev-certs https'

- task: SonarCloudPrepare@1
displayName: 'Prepare analysis on SonarCloud'
Expand Down
14 changes: 11 additions & 3 deletions examples/WireMock.Net.StandAlone.NETCoreApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using log4net;
using log4net.Config;
using log4net.Repository;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;

Expand All @@ -23,15 +25,21 @@ static void Main(string[] args)
{
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));

if (WireMockServerSettingsParser.TryParseArguments(args, out var settings, new WireMockLog4NetLogger()))
if (!WireMockServerSettingsParser.TryParseArguments(args, out var settings, new WireMockLog4NetLogger()))
{
return;
}
}
settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'")));

_server = WireMockServer.Start(settings);

//_server
// .Given(Request.Create()
// .UsingAnyMethod())
// .RespondWith(Response.Create()
// .WithProxy("https://www.google.com"));

Console.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down");

Console.CancelKeyPress += (s, e) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"profiles": {
"WireMock.Net.StandAlone.NETCoreApp": {
"commandName": "Project",
"commandLineArgs": "--Port 9091 --WireMockLogger WireMockConsoleLogger"
"commandLineArgs": "--Urls https://localhost:10080 --WireMockLogger WireMockConsoleLogger"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp2.1</TargetFrameworks>
<TargetFrameworks>netcoreapp3.1</TargetFrameworks>
<ApplicationIcon>../../WireMock.Net-Logo.ico</ApplicationIcon>
<StartupObject>WireMock.Net.StandAlone.NETCoreApp.Program</StartupObject>
</PropertyGroup>
Expand Down
1 change: 0 additions & 1 deletion examples/WireMock.Net.StandAlone.NETCoreApp/run10.cmd

This file was deleted.

1 change: 0 additions & 1 deletion examples/WireMock.Net.StandAlone.NETCoreApp/run20.cmd

This file was deleted.

1 change: 0 additions & 1 deletion examples/WireMock.Net.StandAlone.NETCoreApp/run21.cmd

This file was deleted.

13 changes: 6 additions & 7 deletions src/WireMock.Net/Http/HttpClientHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,12 @@ public static HttpClient CreateHttpClient(IProxyAndRecordSettings settings)
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
#else
var handler = new WebRequestHandler
{
ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
#endif

if (!string.IsNullOrEmpty(settings.ClientX509Certificate2ThumbprintOrSubjectName))
Expand All @@ -59,13 +57,14 @@ public static HttpClient CreateHttpClient(IProxyAndRecordSettings settings)
{
handler.Proxy.Credentials = new NetworkCredential(settings.WebProxySettings.UserName, settings.WebProxySettings.Password);
}
}

var client = new HttpClient(handler);
#if NET452 || NET46
}

#if !NETSTANDARD1_3
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = (message, cert, chain, errors) => true;
#endif
return client;

return new HttpClient(handler);
}

public static async Task<ResponseMessage> SendAsync([NotNull] HttpClient client, [NotNull] RequestMessage requestMessage, string url, bool deserializeJson, bool decompressGzipAndDeflate)
Expand Down
22 changes: 18 additions & 4 deletions src/WireMock.Net/Http/HttpRequestMessageHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,29 @@ internal static HttpRequestMessage Create([NotNull] RequestMessage requestMessag

foreach (var header in requestMessage.Headers.Where(h => !excludeHeaders.Contains(h.Key, StringComparer.OrdinalIgnoreCase)))
{
// Try to add to request headers. If failed - try to add to content headers
if (httpRequestMessage.Headers.Contains(header.Key))
// Skip if already added. We need to ToList() else calling httpRequestMessage.Headers.Contains() with a header starting with a ":" throws an exception.
if (httpRequestMessage.Headers.ToList().Any(h => string.Equals(h.Key, header.Key, StringComparison.OrdinalIgnoreCase)))
{
continue;
}

if (!httpRequestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value))
// Skip if already added. We need to ToList() else calling httpRequestMessage.Content.Headers.Contains(...) with a header starting with a ":" throws an exception.
if (httpRequestMessage.Content != null && httpRequestMessage.Content.Headers.ToList().Any(h => string.Equals(h.Key, header.Key, StringComparison.OrdinalIgnoreCase)))
{
httpRequestMessage.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);
continue;
}

// Try to add to request headers. If failed - try to add to content headers. If still fails, just ignore this header.
try
{
if (!httpRequestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value))
{
httpRequestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
catch
{
// Just continue
}
}

Expand Down
32 changes: 31 additions & 1 deletion test/WireMock.Net.Tests/WireMockServer.Proxy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using FluentAssertions;
using NFluent;
using WireMock.Admin.Mappings;
using WireMock.Logging;
using WireMock.Matchers.Request;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
Expand All @@ -20,6 +19,37 @@ namespace WireMock.Net.Tests
{
public class WireMockServerProxyTests
{
[Fact(Skip = "Fails in Linux CI")]
public async Task WireMockServer_ProxySSL_Should_log_proxied_requests()
{
// Assign
var settings = new WireMockServerSettings
{
UseSSL = true,
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = "https://www.google.com",
SaveMapping = true,
SaveMappingToFile = false
}

};
var server = WireMockServer.Start(settings);

// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(server.Urls[0])
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
await new HttpClient(httpClientHandler).SendAsync(requestMessage);

// Assert
Check.That(server.Mappings).HasSize(2);
Check.That(server.LogEntries).HasSize(1);
}

[Fact]
public async Task WireMockServer_Proxy_Should_log_proxied_requests()
{
Expand Down