91 lines
2.7 KiB
C#
91 lines
2.7 KiB
C#
using System.Net;
|
|
using Flypaper.Core;
|
|
using Flypaper.Http;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using NSubstitute;
|
|
using Shouldly;
|
|
|
|
namespace Flypaper.Tests;
|
|
|
|
public sealed class ForwardedHeadersTests
|
|
{
|
|
private static readonly IPAddress Npm = IPAddress.Parse("172.18.0.5");
|
|
private const string Client = "198.51.100.7";
|
|
|
|
[Fact]
|
|
public async Task Uses_x_forwarded_for_from_proxy_in_trusted_network()
|
|
{
|
|
var ip = await SendAsync(Npm, ("X-Forwarded-For", $"10.9.9.9, {Client}"));
|
|
|
|
ip.ShouldBe(IPAddress.Parse(Client));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Accepts_ipv4_mapped_proxy_address()
|
|
{
|
|
var ip = await SendAsync(Npm.MapToIPv6(), ("X-Forwarded-For", Client));
|
|
|
|
ip.ShouldBe(IPAddress.Parse(Client));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Falls_back_to_x_real_ip()
|
|
{
|
|
var ip = await SendAsync(Npm.MapToIPv6(), ("X-Real-IP", Client));
|
|
|
|
ip.ShouldBe(IPAddress.Parse(Client));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Ignores_headers_from_untrusted_sender()
|
|
{
|
|
var sender = IPAddress.Parse("203.0.113.50");
|
|
|
|
var ip = await SendAsync(sender, ("X-Forwarded-For", Client), ("X-Real-IP", Client));
|
|
|
|
ip.ShouldBe(sender);
|
|
}
|
|
|
|
private static async Task<IPAddress?> SendAsync(IPAddress remoteIp, params (string Name, string Value)[] headers)
|
|
{
|
|
var configuration = new ConfigurationBuilder()
|
|
.AddInMemoryCollection(new Dictionary<string, string?>
|
|
{
|
|
["Flypaper:Http:KnownHosts:0"] = "dashboard.lan",
|
|
["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16"
|
|
})
|
|
.Build();
|
|
|
|
var services = new ServiceCollection()
|
|
.AddLogging()
|
|
.AddSingleton(Substitute.For<ITrapEventSink>())
|
|
.AddFlypaperCore(configuration)
|
|
.AddFlypaperHttp(configuration)
|
|
.BuildServiceProvider();
|
|
|
|
IPAddress? seen = null;
|
|
var app = new ApplicationBuilder(services);
|
|
app.UseFlypaper();
|
|
app.Run(context =>
|
|
{
|
|
seen = context.Connection.RemoteIpAddress;
|
|
return Task.CompletedTask;
|
|
});
|
|
|
|
var httpContext = new DefaultHttpContext { RequestServices = services };
|
|
httpContext.Connection.RemoteIpAddress = remoteIp;
|
|
httpContext.Request.Host = new HostString("dashboard.lan");
|
|
httpContext.Request.Path = "/";
|
|
foreach (var (name, value) in headers)
|
|
{
|
|
httpContext.Request.Headers[name] = value;
|
|
}
|
|
|
|
await app.Build()(httpContext);
|
|
return seen;
|
|
}
|
|
}
|