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

Add blacklist for Request Cookies. #319

Merged
merged 3 commits into from Aug 19, 2019
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/WireMock.Net.StandAlone/StandAloneApp.cs
Expand Up @@ -81,7 +81,8 @@ public static FluentMockServer Start([NotNull] string[] args, [CanBeNull] IWireM
SaveMapping = parser.GetBoolValue("SaveMapping"),
SaveMappingToFile = parser.GetBoolValue("SaveMappingToFile"),
ClientX509Certificate2ThumbprintOrSubjectName = parser.GetStringValue("ClientX509Certificate2ThumbprintOrSubjectName"),
BlackListedHeaders = parser.GetValues("BlackListedHeaders")
BlackListedHeaders = parser.GetValues("BlackListedHeaders"),
BlackListedCookies = parser.GetValues("BlackListedCookies")
};
}

Expand Down
14 changes: 10 additions & 4 deletions src/WireMock.Net/Server/FluentMockServer.Admin.cs
Expand Up @@ -268,7 +268,7 @@ private async Task<ResponseMessage> ProxyAndRecordAsync(RequestMessage requestMe

if (settings.ProxyAndRecordSettings.SaveMapping || settings.ProxyAndRecordSettings.SaveMappingToFile)
{
var mapping = ToMapping(requestMessage, responseMessage, settings.ProxyAndRecordSettings.BlackListedHeaders ?? new string[] { });
var mapping = ToMapping(requestMessage, responseMessage, settings.ProxyAndRecordSettings.BlackListedHeaders ?? new string[] { }, settings.ProxyAndRecordSettings.BlackListedCookies ?? new string[] { });

if (settings.ProxyAndRecordSettings.SaveMapping)
{
Expand All @@ -284,19 +284,25 @@ private async Task<ResponseMessage> ProxyAndRecordAsync(RequestMessage requestMe
return responseMessage;
}

private IMapping ToMapping(RequestMessage requestMessage, ResponseMessage responseMessage, string[] blacklistedHeaders)
private IMapping ToMapping(RequestMessage requestMessage, ResponseMessage responseMessage, string[] blacklistedHeaders, string[] blacklistedCookies)
{
var request = Request.Create();
request.WithPath(requestMessage.Path);
request.UsingMethod(requestMessage.Method);

requestMessage.Query.Loop((key, value) => request.WithParam(key, false, value.ToArray()));
requestMessage.Cookies.Loop((key, value) => request.WithCookie(key, value));
requestMessage.Cookies.Loop((key, value) =>
{
if (!blacklistedCookies.Contains(key, StringComparer.OrdinalIgnoreCase))
{
request.WithCookie(key, value);
}
});

var allBlackListedHeaders = new List<string>(blacklistedHeaders) { "Cookie" };
requestMessage.Headers.Loop((key, value) =>
{
if (!allBlackListedHeaders.Any(b => string.Equals(key, b, StringComparison.OrdinalIgnoreCase)))
if (!allBlackListedHeaders.Contains(key, StringComparer.OrdinalIgnoreCase))
{
request.WithHeader(key, value.ToArray());
}
Expand Down
5 changes: 5 additions & 0 deletions src/WireMock.Net/Settings/IProxyAndRecordSettings.cs
Expand Up @@ -30,5 +30,10 @@ public interface IProxyAndRecordSettings
/// Defines a list from headers which will excluded from the saved mappings.
/// </summary>
string[] BlackListedHeaders { get; set; }

/// <summary>
/// Defines a list of cookies which will excluded from the saved mappings.
/// </summary>
string[] BlackListedCookies { get; set; }
vitaliydavydiak marked this conversation as resolved.
Show resolved Hide resolved
}
}
4 changes: 4 additions & 0 deletions src/WireMock.Net/Settings/ProxyAndRecordSettings.cs
Expand Up @@ -26,5 +26,9 @@ public class ProxyAndRecordSettings : IProxyAndRecordSettings
/// <inheritdoc cref="IProxyAndRecordSettings.BlackListedHeaders"/>
[PublicAPI]
public string[] BlackListedHeaders { get; set; }

/// <inheritdoc cref="IProxyAndRecordSettings.BlackListedCookies"/>
[PublicAPI]
public string[] BlackListedCookies { get; set; }
}
}
63 changes: 56 additions & 7 deletions test/WireMock.Net.Tests/FluentMockServerTests.Proxy.cs
Expand Up @@ -6,6 +6,7 @@
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WireMock.Matchers.Request;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
Expand Down Expand Up @@ -109,6 +110,7 @@ public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_content_head
}
};
var server = FluentMockServer.Start(settings);
var defaultMapping = server.Mappings.First();

// Act
var requestMessage = new HttpRequestMessage
Expand All @@ -117,18 +119,65 @@ public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_content_head
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("stringContent")
};
requestMessage.Headers.Add("blacklisted", "test");
requestMessage.Headers.Add("blacklisted", "exact_match");
requestMessage.Headers.Add("ok", "ok-value");
await new HttpClient().SendAsync(requestMessage);

// Assert
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.Headers).Not.ContainsKey("bbb");
Check.That(receivedRequest.Headers).ContainsKey("ok");
var mapping = server.Mappings.FirstOrDefault(m => m.Guid != defaultMapping.Guid);
Check.That(mapping).IsNotNull();
var matchers = ((Request)mapping.RequestMatcher).GetRequestMessageMatchers<RequestMessageHeaderMatcher>().Select(m => m.Name).ToList();
Check.That(matchers).Not.Contains("blacklisted");
Check.That(matchers).Contains("ok");
}

[Fact]
public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_cookies_in_mapping()
{
// Assign
string path = $"/prx_{Guid.NewGuid().ToString()}";
var serverForProxyForwarding = FluentMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create());

var settings = new FluentMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = serverForProxyForwarding.Urls[0],
SaveMapping = true,
SaveMappingToFile = false,
BlackListedCookies = new[] { "ASP.NET_SessionId" }
}
};
var server = FluentMockServer.Start(settings);
var defaultMapping = server.Mappings.First();

// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("stringContent")
};

var cookieContainer = new CookieContainer(3);
cookieContainer.Add(new Uri("http://localhost"), new Cookie("ASP.NET_SessionId", "exact_match"));
cookieContainer.Add(new Uri("http://localhost"), new Cookie("AsP.NeT_SessIonID", "case_mismatch"));
cookieContainer.Add(new Uri("http://localhost"), new Cookie("GoodCookie", "I_should_pass"));

var handler = new HttpClientHandler { CookieContainer = cookieContainer };
await new HttpClient(handler).SendAsync(requestMessage);

// Assert
var mapping = server.Mappings.FirstOrDefault(m => m.Guid != defaultMapping.Guid);
Check.That(mapping).IsNotNull();

//var mapping = _server.Mappings.Last();
//var matcher = ((Request)mapping.RequestMatcher).GetRequestMessageMatchers<RequestMessageHeaderMatcher>().FirstOrDefault(m => m.Name == "bbb");
//Check.That(matcher).IsNull();
var matchers = ((Request)mapping.RequestMatcher).GetRequestMessageMatchers<RequestMessageCookieMatcher>().Select(m => m.Name).ToList();
Check.That(matchers).Not.Contains("ASP.NET_SessionId");
Check.That(matchers).Not.Contains("AsP.NeT_SessIonID");
Check.That(matchers).Contains("GoodCookie");
}

[Fact]
Expand Down