using System.Net; using Flypaper.Core; using Flypaper.Core.Abstractions; 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.Http; 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); } [Theory] [InlineData("172.19.0.3")] [InlineData("10.1.2.3")] [InlineData("192.168.1.2")] [InlineData("127.0.0.1")] [InlineData("fd00::2")] public async Task Trusts_private_networks_by_default(string proxy) { var ip = await SendAsync(IPAddress.Parse(proxy), trustedProxy: null, ("X-Real-IP", Client)); ip.ShouldBe(IPAddress.Parse(Client)); } [Fact] public async Task Configured_proxies_replace_the_default_networks() { var sender = IPAddress.Parse("192.168.1.2"); var ip = await SendAsync(sender, ("X-Real-IP", Client)); ip.ShouldBe(sender); } private static Task SendAsync(IPAddress remoteIp, params (string Name, string Value)[] headers) => SendAsync(remoteIp, "172.18.0.0/16", headers); private static async Task SendAsync(IPAddress remoteIp, string? trustedProxy, params (string Name, string Value)[] headers) { var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary { ["Flypaper:Http:TrustedProxies:0"] = trustedProxy }) .Build(); var services = new ServiceCollection() .AddLogging() .AddSingleton(Substitute.For()) .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.Connection.LocalPort = 8081; 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; } }