Skip to content

Commit

Permalink
WebHeaderCollection.IsRestricted (#148)
Browse files Browse the repository at this point in the history
  • Loading branch information
StefH committed Jul 18, 2018
1 parent 7191c08 commit f1896ef
Show file tree
Hide file tree
Showing 8 changed files with 173 additions and 1 deletion.
7 changes: 7 additions & 0 deletions WireMock.Net Solution.sln
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.StandAlone.Net
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.Service", "examples\Wiremock.Net.Service\WireMock.Net.Service.csproj", "{7F0B2446-0363-4720-AF46-F47F83B557DC}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.Console.HeadersTest", "examples\WireMock.Net.Console.HeadersTest\WireMock.Net.Console.HeadersTest.csproj", "{B70278E7-A2C6-4A3B-BBA9-1C873CA6F03C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -114,6 +116,10 @@ Global
{7F0B2446-0363-4720-AF46-F47F83B557DC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F0B2446-0363-4720-AF46-F47F83B557DC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F0B2446-0363-4720-AF46-F47F83B557DC}.Release|Any CPU.Build.0 = Release|Any CPU
{B70278E7-A2C6-4A3B-BBA9-1C873CA6F03C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B70278E7-A2C6-4A3B-BBA9-1C873CA6F03C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B70278E7-A2C6-4A3B-BBA9-1C873CA6F03C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B70278E7-A2C6-4A3B-BBA9-1C873CA6F03C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -133,6 +139,7 @@ Global
{23A9AA3C-40FC-42AA-8A5E-05899795A1C6} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A}
{3C279524-DB73-4DE3-BEF1-F2B2958C9F65} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A}
{7F0B2446-0363-4720-AF46-F47F83B557DC} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A}
{B70278E7-A2C6-4A3B-BBA9-1C873CA6F03C} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BF428BCC-C837-433B-87D2-15C7014B73E9}
Expand Down
60 changes: 60 additions & 0 deletions examples/WireMock.Net.Console.HeadersTest/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
using log4net.Repository;
using Newtonsoft.Json;
using WireMock.Logging;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;

namespace WireMock.Net.Console.NETCoreApp
{
static class Program
{
private static readonly ILoggerRepository LogRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

static void Main(params string[] args)
{
XmlConfigurator.Configure(LogRepository, new FileInfo("log4net.config"));

string url = "http://localhost:9999/";

var server = FluentMockServer.Start(new FluentMockServerSettings
{
Urls = new[] { url },
StartAdminInterface = true,
Logger = new WireMockConsoleLogger()
});
System.Console.WriteLine("FluentMockServer listening at {0}", string.Join(",", server.Urls));

server.SetBasicAuthentication("a", "b");

server.AllowPartialMapping();

server
.Given(Request.Create()
.UsingGet()
.WithHeader("Keep-Alive-Test", "stef")
)
.RespondWith(Response.Create()
.WithHeader("Keep-Alive", "timeout=1, max=1")
.WithBody("Keep-Alive OK")
);

System.Console.WriteLine("Press any key to stop the server");
System.Console.ReadKey();
server.Stop();

System.Console.WriteLine("Displaying all requests");
var allRequests = server.LogEntries;
System.Console.WriteLine(JsonConvert.SerializeObject(allRequests, Formatting.Indented));

System.Console.WriteLine("Press any key to quit");
System.Console.ReadKey();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
<ApplicationIcon>../../WireMock.Net-Logo.ico</ApplicationIcon>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\WireMock.Net\WireMock.Net.csproj" />
<PackageReference Include="log4net" Version="2.0.8" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
</ItemGroup>

<ItemGroup>
<None Update="log4net.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="nlog.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
20 changes: 20 additions & 0 deletions examples/WireMock.Net.Console.HeadersTest/log4net.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger{1} - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
</configuration>
18 changes: 18 additions & 0 deletions examples/WireMock.Net.Console.HeadersTest/nlog.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="info"
internalLogFile="c:\temp\wiremock-internal-nlog.log">

<targets>
<!-- write logs to file -->
<target xsi:type="File" name="all" fileName="c:\temp\wiremock-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger}|${message} ${exception}" />
</targets>

<!-- rules to map from logger name to target -->
<rules>
<logger name="*" minlevel="Debug" writeTo="all" />
</rules>
</nlog>
19 changes: 19 additions & 0 deletions examples/WireMock.Net.ConsoleApplication/MainApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,25 @@ public static void Run()

server.AllowPartialMapping();

server
.Given(Request.Create()
.UsingGet()
.WithPath("/proxy-test-keep-alive")
)
.RespondWith(Response.Create()
.WithHeader("Keep-Alive", "timeout=1, max=1")
);

server
.Given(Request.Create()
.UsingGet()
.WithPath("/proxy-execute-keep-alive")
)
.RespondWith(Response.Create()
.WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999", BlackListedHeaders = new [] { "Keep-Alive" } })
.WithHeader("Keep-Alive-Test", "stef")
);

server
.Given(Request.Create()
.WithPath("/xpath").UsingPost()
Expand Down
8 changes: 7 additions & 1 deletion src/WireMock.Net/Owin/OwinResponseMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
Expand Down Expand Up @@ -49,8 +50,13 @@ public class OwinResponseMapper
else
{
#if !NETSTANDARD
response.Headers.AppendValues(pair.Key, pair.Value.ToArray());
// For non-NETSTANDARD, check if this response header can be added (#148)
if (!WebHeaderCollection.IsRestricted(pair.Key, true))
{
response.Headers.AppendValues(pair.Key, pair.Value.ToArray());
}

This comment has been minimized.

Copy link
@josdeweger-zz

josdeweger-zz Jul 19, 2018

I'm not sure this will be a long term fix. Unless I'm missing something, the restricted headers are now omitted on the response. What if that header is important for your virtualization scenario?

Also, from what I understand from https://stackoverflow.com/a/4752359 there should be an option to set the header via a specific property, which the exception suggests. I could only find examples for setting these headers via properties on the request (casting it to HttpWebRequest) though, not on the response.

This comment has been minimized.

Copy link
@StefH

StefH Jul 19, 2018

Author Collaborator

That code is for request headers, cannot be used for response.

I found some more details:
https://referencesource.microsoft.com/#system/net/system/Net/WebHeaderCollection.cs
and
https://github.com/jbevain/mono.net.httplistener/blob/master/Mono.Net/WebHeaderCollection.cs#L77

According to that mono c# file, only a few headers are restricted on response.

So for now I'll keep my code as is.
And please open a new issue when you still experience issues.
Or try to use dotnet core instead of net45 / 46

#else
// NETSTANDARD can add any header (or so it seems)
response.Headers.Append(pair.Key, pair.Value.ToArray());
#endif
}
Expand Down
18 changes: 18 additions & 0 deletions test/WireMock.Net.Tests/FluentMockServerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,24 @@ public async Task FluentMockServer_Should_respond_to_request_callback()
Check.That(response).IsEqualTo("/fooBar");
}


[Fact]
public async Task FluentMockServer_Should_exclude_restrictedResponseHeader_for_IOwinResponse()
{
_server = FluentMockServer.Start();

_server
.Given(Request.Create().WithPath("/foo").UsingGet())
.RespondWith(Response.Create().WithHeader("Keep-Alive", "").WithHeader("test", ""));

// Act
var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");

// Assert
Check.That(response.Headers.Contains("test")).IsTrue();
Check.That(response.Headers.Contains("Keep-Alive")).IsFalse();
}

public void Dispose()
{
_server?.Stop();
Expand Down

0 comments on commit f1896ef

Please sign in to comment.