81 lines
2.4 KiB
C#
81 lines
2.4 KiB
C#
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 HealthProbeTests
|
|
{
|
|
[Theory]
|
|
[InlineData("172.19.0.7")]
|
|
[InlineData("127.0.0.1")]
|
|
[InlineData("192.168.1.20")]
|
|
[InlineData("::1")]
|
|
public async Task Lets_health_probe_from_private_network_pass_with_unknown_host(string remoteIp)
|
|
{
|
|
var (reachedApp, status) = await SendAsync(IPAddress.Parse(remoteIp), "/health");
|
|
|
|
reachedApp.ShouldBeTrue();
|
|
status.ShouldBe(StatusCodes.Status200OK);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Traps_health_path_from_public_ip()
|
|
{
|
|
var (reachedApp, status) = await SendAsync(IPAddress.Parse("203.0.113.9"), "/health");
|
|
|
|
reachedApp.ShouldBeFalse();
|
|
status.ShouldBe(StatusCodes.Status404NotFound);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Traps_other_paths_from_private_network_with_unknown_host()
|
|
{
|
|
var (reachedApp, _) = await SendAsync(IPAddress.Parse("172.19.0.7"), "/status");
|
|
|
|
reachedApp.ShouldBeFalse();
|
|
}
|
|
|
|
private static async Task<(bool ReachedApp, int Status)> SendAsync(IPAddress remoteIp, string path)
|
|
{
|
|
var configuration = new ConfigurationBuilder()
|
|
.AddInMemoryCollection(new Dictionary<string, string?>
|
|
{
|
|
["Flypaper:MaxConnections"] = "0"
|
|
})
|
|
.Build();
|
|
|
|
var services = new ServiceCollection()
|
|
.AddLogging()
|
|
.AddSingleton(Substitute.For<ITrapEventSink>())
|
|
.AddFlypaperCore(configuration)
|
|
.AddFlypaperHttp(configuration)
|
|
.BuildServiceProvider();
|
|
|
|
var reachedApp = false;
|
|
var app = new ApplicationBuilder(services);
|
|
app.UseFlypaper();
|
|
app.Run(_ =>
|
|
{
|
|
reachedApp = true;
|
|
return Task.CompletedTask;
|
|
});
|
|
|
|
var httpContext = new DefaultHttpContext { RequestServices = services };
|
|
httpContext.Connection.RemoteIpAddress = remoteIp;
|
|
httpContext.Connection.LocalPort = 8080;
|
|
httpContext.Request.Host = new HostString("flypaper:8080");
|
|
httpContext.Request.Path = path;
|
|
|
|
await app.Build()(httpContext);
|
|
return (reachedApp, httpContext.Response.StatusCode);
|
|
}
|
|
}
|