Restructure solution into folders and fix persistence issues

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-14 14:10:24 +01:00
1 parent 37987a394a
commit 7c39cb5562
62 files changed
+219 -151

No files matched your search

@@ -0,0 +1,78 @@
using System.Net;
using Flypaper.Core;
using Flypaper.Core.Models;
using Flypaper.Core.Runtime;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
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(TestOptions.Monitor(new FlypaperOptions { MaxConnections = maxConnections, MaxConnectionsPerIp = maxPerIp }));
private static TrapSession Session(IPAddress ip) => new(Guid.NewGuid(), TrapProtocol.Http, ip, DateTimeOffset.UtcNow);
}
@@ -0,0 +1,43 @@
using Flypaper.Core.Models;
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
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(TestOptions.Monitor(new DripOptions { Interval = interval }), TimeProvider.System);
}
@@ -0,0 +1,114 @@
using Flypaper.Core.Settings;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed class RuntimeSettingsParserTests
{
private static readonly RuntimeSettingsInput Valid = new(
"/.env\n/wp-admin/*\r\n /xmlrpc.php \n/.env",
"00:00:05",
"200",
"5",
"00:30:00",
"example.com\n*.example.org");
[Fact]
public void Parses_valid_input_and_normalizes_lists()
{
var result = RuntimeSettingsParser.Parse(Valid);
result.Errors.ShouldBeEmpty();
var settings = result.Settings.ShouldNotBeNull();
settings.TrapPaths.ShouldBe(["/.env", "/wp-admin/*", "/xmlrpc.php"]);
settings.ExtraKnownHosts.ShouldBe(["example.com", "*.example.org"]);
settings.DripInterval.ShouldBe(TimeSpan.FromSeconds(5));
settings.MaxConnections.ShouldBe(200);
settings.MaxConnectionsPerIp.ShouldBe(5);
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(30));
}
[Fact]
public void Accepts_empty_lists()
{
var result = RuntimeSettingsParser.Parse(Valid with { TrapPaths = "", ExtraKnownHosts = null });
result.Settings.ShouldNotBeNull().TrapPaths.ShouldBeEmpty();
}
[Theory]
[InlineData("env")]
[InlineData("/with space")]
[InlineData("/a*b")]
public void Rejects_invalid_trap_paths(string path)
{
var result = RuntimeSettingsParser.Parse(Valid with { TrapPaths = $"/ok\n{path}" });
result.Settings.ShouldBeNull();
result.Errors.Keys.ShouldBe([nameof(RuntimeSettingsInput.TrapPaths)]);
}
[Theory]
[InlineData("https://example.com")]
[InlineData("example.com/path")]
[InlineData("example.com:8080")]
[InlineData("-bad.com")]
public void Rejects_invalid_hosts(string host)
{
var result = RuntimeSettingsParser.Parse(Valid with { ExtraKnownHosts = host });
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.ExtraKnownHosts));
}
[Theory]
[InlineData("10")]
[InlineData("abc")]
[InlineData("")]
[InlineData("00:00:00")]
[InlineData("02:00:00")]
public void Rejects_invalid_drip_intervals(string value)
{
var result = RuntimeSettingsParser.Parse(Valid with { DripInterval = value });
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.DripInterval));
}
[Theory]
[InlineData("0")]
[InlineData("-3")]
[InlineData("1.5")]
[InlineData("x")]
[InlineData("")]
public void Rejects_invalid_connection_counts(string value)
{
var result = RuntimeSettingsParser.Parse(Valid with { MaxConnections = value, MaxConnectionsPerIp = value });
result.Errors.Keys.ShouldBe(
[nameof(RuntimeSettingsInput.MaxConnections), nameof(RuntimeSettingsInput.MaxConnectionsPerIp)],
ignoreOrder: true);
}
[Fact]
public void Rejects_per_ip_limit_above_total()
{
var result = RuntimeSettingsParser.Parse(Valid with { MaxConnections = "3", MaxConnectionsPerIp = "4" });
result.Errors.Keys.ShouldBe([nameof(RuntimeSettingsInput.MaxConnectionsPerIp)]);
}
[Fact]
public void Rejects_hold_duration_out_of_range()
{
var result = RuntimeSettingsParser.Parse(Valid with { MaxHoldDuration = "00:00:00.5" });
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.MaxHoldDuration));
}
[Fact]
public void Exposes_only_whitelisted_configuration_keys()
{
var keys = RuntimeSettingsParser.Parse(Valid).Settings.ShouldNotBeNull().ToConfiguration().Keys;
keys.ShouldBe(SettingKeys.All, ignoreOrder: true);
}
}
@@ -0,0 +1,93 @@
using System.Net;
using Flypaper.Core;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Flypaper.Core.Runtime;
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Shouldly;
namespace Flypaper.Tests.Core;
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(TestOptions.Monitor(new DripOptions { Interval = TimeSpan.FromMilliseconds(20) }), TimeProvider.System);
return new TrapRunner(
_governor,
[drip],
_sink,
TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }),
TimeProvider.System,
NullLogger<TrapRunner>.Instance);
}
private static TrapContext Context() =>
new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), "GET /.env");
}