Fix Proxying with SSL and NetCoreApp3.1 (#547)

* Fix Proxying with SSL and NetCoreApp3.1

* add test

* ServicePointManager.ServerCertificateValidationCallback = (message, cert, chain, errors) => true;

* dotnet dev-certs https

* x

* .
This commit is contained in:
Stef Heyenrath
2020-12-03 09:36:42 +01:00
committed by GitHub
parent 933bd7d046
commit 3dfee689b5
10 changed files with 72 additions and 20 deletions

View File

@@ -22,6 +22,10 @@ jobs:
$jdkPath = $env:JAVA_HOME_11_X64 $jdkPath = $env:JAVA_HOME_11_X64
Write-Host "##vso[task.setvariable variable=JAVA_HOME]$jdkPath" Write-Host "##vso[task.setvariable variable=JAVA_HOME]$jdkPath"
- script: |
dotnet dev-certs https --trust || true
displayName: 'dotnet dev-certs https'
- task: SonarCloudPrepare@1 - task: SonarCloudPrepare@1
displayName: 'Prepare analysis on SonarCloud' displayName: 'Prepare analysis on SonarCloud'
inputs: inputs:

View File

@@ -6,6 +6,8 @@ using System.Threading;
using log4net; using log4net;
using log4net.Config; using log4net.Config;
using log4net.Repository; using log4net.Repository;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server; using WireMock.Server;
using WireMock.Settings; using WireMock.Settings;
@@ -23,7 +25,7 @@ namespace WireMock.Net.StandAlone.NETCoreApp
{ {
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config")); 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; return;
} }
@@ -32,6 +34,12 @@ namespace WireMock.Net.StandAlone.NETCoreApp
_server = WireMockServer.Start(settings); _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.WriteLine($"{DateTime.UtcNow} Press Ctrl+C to shut down");
Console.CancelKeyPress += (s, e) => Console.CancelKeyPress += (s, e) =>

View File

@@ -2,7 +2,7 @@
"profiles": { "profiles": {
"WireMock.Net.StandAlone.NETCoreApp": { "WireMock.Net.StandAlone.NETCoreApp": {
"commandName": "Project", "commandName": "Project",
"commandLineArgs": "--Port 9091 --WireMockLogger WireMockConsoleLogger" "commandLineArgs": "--Urls https://localhost:10080 --WireMockLogger WireMockConsoleLogger"
} }
} }
} }

View File

@@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp2.1</TargetFrameworks> <TargetFrameworks>netcoreapp3.1</TargetFrameworks>
<ApplicationIcon>../../WireMock.Net-Logo.ico</ApplicationIcon> <ApplicationIcon>../../WireMock.Net-Logo.ico</ApplicationIcon>
<StartupObject>WireMock.Net.StandAlone.NETCoreApp.Program</StartupObject> <StartupObject>WireMock.Net.StandAlone.NETCoreApp.Program</StartupObject>
</PropertyGroup> </PropertyGroup>

View File

@@ -1 +0,0 @@
dotnet run --framework netcoreapp1.1

View File

@@ -1 +0,0 @@
dotnet run --framework netcoreapp2.0

View File

@@ -1 +0,0 @@
dotnet run --framework netcoreapp2.1

View File

@@ -27,14 +27,12 @@ namespace WireMock.Http
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true, ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
}; };
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
#else #else
var handler = new WebRequestHandler var handler = new WebRequestHandler
{ {
ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true, ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
}; };
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
#endif #endif
if (!string.IsNullOrEmpty(settings.ClientX509Certificate2ThumbprintOrSubjectName)) if (!string.IsNullOrEmpty(settings.ClientX509Certificate2ThumbprintOrSubjectName))
@@ -61,11 +59,12 @@ namespace WireMock.Http
} }
} }
var client = new HttpClient(handler); #if !NETSTANDARD1_3
#if NET452 || NET46
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = (message, cert, chain, errors) => true;
#endif #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) public static async Task<ResponseMessage> SendAsync([NotNull] HttpClient client, [NotNull] RequestMessage requestMessage, string url, bool deserializeJson, bool decompressGzipAndDeflate)

View File

@@ -59,15 +59,29 @@ namespace WireMock.Http
foreach (var header in requestMessage.Headers.Where(h => !excludeHeaders.Contains(h.Key, StringComparer.OrdinalIgnoreCase))) 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 // 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.Contains(header.Key)) if (httpRequestMessage.Headers.ToList().Any(h => string.Equals(h.Key, header.Key, StringComparison.OrdinalIgnoreCase)))
{ {
continue; 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
} }
} }

View File

@@ -8,7 +8,6 @@ using System.Threading.Tasks;
using FluentAssertions; using FluentAssertions;
using NFluent; using NFluent;
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;
using WireMock.Logging;
using WireMock.Matchers.Request; using WireMock.Matchers.Request;
using WireMock.RequestBuilders; using WireMock.RequestBuilders;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
@@ -20,6 +19,37 @@ namespace WireMock.Net.Tests
{ {
public class WireMockServerProxyTests 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] [Fact]
public async Task WireMockServer_Proxy_Should_log_proxied_requests() public async Task WireMockServer_Proxy_Should_log_proxied_requests()
{ {