Files
Flypaper/test/Flypaper.Tests/Http/LureTests.cs
T
TomandClaude Sonnet 5.5 4b946453fb
Build and deploy / build (push) Successful in 1m33s
Build and deploy / deploy (push) Successful in 20s
Answer first visits to / and favicon with an instant WordPress lure
Unknown IPs get a small WordPress-looking page or icon and are not held;
later requests are trapped as before. Switch: Flypaper__Drip__Lure.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 12:57:29 +01:00

72 lines
2.7 KiB
C#

using System.Net;
using System.Text;
using Flypaper.Core;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
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 LureTests
{
[Fact]
public async Task Unknown_ip_gets_the_lure_page_with_matching_headers_and_is_not_held()
{
var (body, headers, sink) = await SendAsync(known: false, "/");
body.ShouldContain("WordPress");
headers["X-Powered-By"].ToString().ShouldStartWith("PHP/");
headers.Server.ToString().ShouldBe("nginx");
sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Strategy == "lure-page" && e.Outcome == TrapOutcome.Completed));
}
[Fact]
public async Task Known_ip_gets_no_lure()
{
var (_, headers, sink) = await SendAsync(known: true, "/", cancelAfter: TimeSpan.FromMilliseconds(100));
headers.ContainsKey("X-Powered-By").ShouldBeFalse();
sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Strategy != "lure-page"));
}
private static async Task<(string Body, IHeaderDictionary Headers, ITrapEventSink Sink)> SendAsync(bool known, string path, TimeSpan? cancelAfter = null)
{
var lookup = Substitute.For<IKnownIpLookup>();
lookup.HasSeenAsync(Arg.Any<IPAddress>(), Arg.Any<CancellationToken>()).Returns(known);
var sink = Substitute.For<ITrapEventSink>();
var configuration = new ConfigurationBuilder().Build();
var services = new ServiceCollection()
.AddLogging()
.AddSingleton(sink)
.AddSingleton(lookup)
.AddFlypaperCore(configuration)
.AddFlypaperHttp(configuration)
.BuildServiceProvider();
var app = new ApplicationBuilder(services);
app.UseFlypaper();
var body = new MemoryStream();
using var cts = new CancellationTokenSource();
var httpContext = new DefaultHttpContext { RequestServices = services, RequestAborted = cts.Token };
httpContext.Connection.RemoteIpAddress = IPAddress.Parse("203.0.113.9");
httpContext.Connection.LocalPort = 8080;
httpContext.Request.Method = "GET";
httpContext.Request.Host = new HostString("example.com");
httpContext.Request.Path = path;
httpContext.Response.Body = body;
if (cancelAfter is { } delay)
{
cts.CancelAfter(delay);
}
await app.Build()(httpContext);
return (Encoding.UTF8.GetString(body.ToArray()), httpContext.Response.Headers, sink);
}
}