Add Flypaper solution skeleton with HTTP tarpit, SQLite event log and tests

This commit is contained in:
Tom committed 2026-11-14 13:15:57 +01:00
1 parent 20314268c6
commit f9161f48e7
55 files changed
+1331

No files matched your search

@@ -0,0 +1,76 @@
using System.Net;
using Flypaper.Core;
using Microsoft.Extensions.Options;
using Shouldly;
namespace Flypaper.Tests;
public sealed class ConnectionGovernorTests
{
private static readonly IPAddress IpA = IPAddress.Parse("203.0.113.1");
private static readonly IPAddress IpB = IPAddress.Parse("203.0.113.2");
[Fact]
public void Rejects_when_per_ip_limit_reached()
{
var governor = CreateGovernor(maxConnections: 10, maxPerIp: 2);
governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
governor.TryAcquire(Session(IpA), out var lease).ShouldBeFalse();
lease.ShouldBeNull();
governor.TryAcquire(Session(IpB), out _).ShouldBeTrue();
}
[Fact]
public void Rejects_when_total_limit_reached()
{
var governor = CreateGovernor(maxConnections: 2, maxPerIp: 10);
governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
governor.TryAcquire(Session(IpB), out _).ShouldBeTrue();
governor.TryAcquire(Session(IPAddress.Parse("203.0.113.3")), out _).ShouldBeFalse();
}
[Fact]
public void Disposing_lease_frees_slot()
{
var governor = CreateGovernor(maxConnections: 1, maxPerIp: 1);
governor.TryAcquire(Session(IpA), out var lease).ShouldBeTrue();
governor.TryAcquire(Session(IpA), out _).ShouldBeFalse();
lease.Dispose();
governor.ActiveConnections.ShouldBe(0);
governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
}
[Fact]
public void Disposing_lease_twice_releases_once()
{
var governor = CreateGovernor(maxConnections: 10, maxPerIp: 10);
governor.TryAcquire(Session(IpA), out var first).ShouldBeTrue();
governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
first.Dispose();
first.Dispose();
governor.ActiveConnections.ShouldBe(1);
}
[Fact]
public void Treats_ipv4_mapped_ipv6_as_same_ip()
{
var governor = CreateGovernor(maxConnections: 10, maxPerIp: 1);
governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
governor.TryAcquire(Session(IpA.MapToIPv6()), out _).ShouldBeFalse();
}
private static ConnectionGovernor CreateGovernor(int maxConnections, int maxPerIp) =>
new(Options.Create(new FlypaperOptions { MaxConnections = maxConnections, MaxConnectionsPerIp = maxPerIp }));
private static TrapSession Session(IPAddress ip) => new(Guid.NewGuid(), TrapProtocol.Http, ip, DateTimeOffset.UtcNow);
}
+43
View File
@@ -0,0 +1,43 @@
using Flypaper.Core;
using Flypaper.Core.Strategies;
using Microsoft.Extensions.Options;
using Shouldly;
namespace Flypaper.Tests;
public sealed class DripStrategyTests
{
[Fact]
public async Task Drips_single_bytes_until_cancelled()
{
var strategy = CreateStrategy(TimeSpan.FromMilliseconds(20));
var channel = new FakeTrapChannel();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
channel.Writes.Count.ShouldBeInRange(3, 20);
channel.Writes.ShouldAllBe(write => write.Length == 1);
}
[Fact]
public async Task Writes_first_byte_immediately()
{
var strategy = CreateStrategy(TimeSpan.FromMinutes(1));
var channel = new FakeTrapChannel();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
channel.Writes.Count.ShouldBe(1);
}
[Theory]
[InlineData(TrapProtocol.Http, true)]
[InlineData(TrapProtocol.Ssh, false)]
public void Supports_only_http(TrapProtocol protocol, bool expected) =>
CreateStrategy(TimeSpan.FromSeconds(1)).Supports(protocol).ShouldBe(expected);
private static DripStrategy CreateStrategy(TimeSpan interval) =>
new(Options.Create(new DripOptions { Interval = interval }), TimeProvider.System);
}
+19
View File
@@ -0,0 +1,19 @@
using System.Collections.Concurrent;
using System.Net;
using Flypaper.Core;
namespace Flypaper.Tests;
internal sealed class FakeTrapChannel : ITrapChannel
{
public TrapSession Session { get; } = new(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Loopback, DateTimeOffset.UtcNow);
public ConcurrentQueue<byte[]> Writes { get; } = new();
public ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
Writes.Enqueue(data.ToArray());
return ValueTask.CompletedTask;
}
}
+25
View File
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="Shouldly" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Flypaper.Http\Flypaper.Http.csproj" />
<ProjectReference Include="..\..\src\Flypaper.Storage\Flypaper.Storage.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
</Project>
+41
View File
@@ -0,0 +1,41 @@
using Flypaper.Http;
using Microsoft.Extensions.Options;
using Shouldly;
namespace Flypaper.Tests;
public sealed class TrapMatcherTests
{
private readonly TrapMatcher _matcher = new(Options.Create(new HttpTrapOptions
{
KnownHosts = ["example.com", "*.example.org"],
TrapPaths = ["/.env", "/.git/*", "/wp-login.php"]
}));
[Theory]
[InlineData("example.com", "/")]
[InlineData("EXAMPLE.com", "/index.html")]
[InlineData("app.example.org", "/api/items")]
[InlineData("example.com", "/.envelope")]
[InlineData("example.com", "/.git")]
public void Lets_normal_requests_pass(string host, string path) =>
_matcher.Match(host, path).ShouldBe(TrapMatch.None);
[Theory]
[InlineData("example.com", "/.env")]
[InlineData("example.com", "/.ENV")]
[InlineData("example.com", "/.env/")]
[InlineData("example.com", "/.git/config")]
[InlineData("app.example.org", "/wp-login.php")]
public void Traps_configured_paths(string host, string path) =>
_matcher.Match(host, path).ShouldBe(TrapMatch.TrapPath);
[Theory]
[InlineData("unknown.net", "/")]
[InlineData("203.0.113.7", "/")]
[InlineData("example.org", "/")]
[InlineData("", "/")]
[InlineData(null, "/")]
public void Traps_unknown_hosts(string? host, string path) =>
_matcher.Match(host, path).ShouldBe(TrapMatch.UnknownHost);
}
+88
View File
@@ -0,0 +1,88 @@
using System.Net;
using Flypaper.Core;
using Flypaper.Core.Strategies;
using Microsoft.Extensions.Options;
using NSubstitute;
using Shouldly;
namespace Flypaper.Tests;
public sealed class TrapRunnerTests
{
private readonly IConnectionGovernor _governor = Substitute.For<IConnectionGovernor>();
private readonly ITrapEventSink _sink = Substitute.For<ITrapEventSink>();
private readonly FakeTrapChannel _channel = new();
[Fact]
public async Task Rejects_without_opening_channel_when_governor_is_full()
{
_governor.TryAcquire(Arg.Any<TrapSession>(), out Arg.Any<IDisposable?>()).Returns(false);
var opened = false;
var outcome = await CreateRunner(TimeSpan.FromSeconds(1)).RunAsync(
Context(),
_ =>
{
opened = true;
return ValueTask.FromResult<ITrapChannel>(_channel);
},
CancellationToken.None);
outcome.ShouldBe(TrapOutcome.Rejected);
opened.ShouldBeFalse();
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.Rejected && e.BytesSent == 0));
}
[Fact]
public async Task Times_out_after_max_hold_duration_and_releases_lease()
{
var lease = AllowAcquire();
var outcome = await CreateRunner(TimeSpan.FromMilliseconds(200)).RunAsync(Context(), Open, CancellationToken.None);
outcome.ShouldBe(TrapOutcome.Timeout);
lease.Received(1).Dispose();
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e =>
e.Outcome == TrapOutcome.Timeout && e.BytesSent == _channel.Writes.Count && e.BytesSent > 0));
}
[Fact]
public async Task Reports_client_abort_when_caller_cancels()
{
AllowAcquire();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(), Open, cts.Token);
outcome.ShouldBe(TrapOutcome.ClientAborted);
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "drip"));
}
private IDisposable AllowAcquire()
{
var lease = Substitute.For<IDisposable>();
_governor.TryAcquire(Arg.Any<TrapSession>(), out Arg.Any<IDisposable?>())
.Returns(call =>
{
call[1] = lease;
return true;
});
return lease;
}
private ValueTask<ITrapChannel> Open(CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_channel);
private TrapRunner CreateRunner(TimeSpan maxHoldDuration)
{
var drip = new DripStrategy(Options.Create(new DripOptions { Interval = TimeSpan.FromMilliseconds(20) }), TimeProvider.System);
return new TrapRunner(
_governor,
[drip],
_sink,
Options.Create(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }),
TimeProvider.System);
}
private static TrapContext Context() =>
new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), "GET /.env");
}