Add data management, randomized HTML drip and public README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-14 16:08:45 +01:00
1 parent 3671019e60
commit f5d8ca7484
46 files changed
+1601 -172

No files matched your search

@@ -0,0 +1,55 @@
using System.Text;
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed class DripScheduleTests
{
private static readonly DripOptions Options = new()
{
MinDelay = TimeSpan.FromMilliseconds(50),
MaxDelay = TimeSpan.FromSeconds(1),
MinChunkSize = 1,
MaxChunkSize = 64
};
[Fact]
public void Uses_random_chunk_sizes_and_delays_within_bounds()
{
var random = new SeededRandomSource(11);
var steps = DripSchedule.Create(HtmlContent.Generate(random), random, Options).Take(2000).ToList();
steps.ShouldAllBe(step => step.Chunk.Length >= 1 && step.Chunk.Length <= 64);
steps.ShouldAllBe(step => step.Delay >= TimeSpan.FromMilliseconds(50) && step.Delay <= TimeSpan.FromSeconds(1));
steps.Select(step => step.Chunk.Length).Distinct().Count().ShouldBeGreaterThan(40);
steps.Select(step => step.Delay).Distinct().Count().ShouldBeGreaterThan(500);
}
[Fact]
public void Delivers_the_content_unchanged_and_in_order()
{
var content = new[] { "<!doctype html>", "<p>hällo ", "world</p>", "\n" };
var steps = DripSchedule.Create(content, new SeededRandomSource(12), Options).ToList();
Encoding.UTF8.GetString(steps.SelectMany(step => step.Chunk.ToArray()).ToArray()).ShouldBe(string.Concat(content));
}
[Fact]
public void Ends_when_content_ends()
{
DripSchedule.Create([], new SeededRandomSource(13), Options).ShouldBeEmpty();
}
[Fact]
public void Tolerates_inverted_bounds()
{
var options = new DripOptions { MinDelay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(1), MinChunkSize = 10, MaxChunkSize = 5 };
var step = DripSchedule.Create(["0123456789abcdef"], new SeededRandomSource(14), options).First();
step.Chunk.Length.ShouldBe(10);
step.Delay.ShouldBe(TimeSpan.FromSeconds(2));
}
}
@@ -1,43 +0,0 @@
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,58 @@
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed class HtmlContentTests
{
[Fact]
public void Starts_with_a_complete_html_head()
{
var head = HtmlContent.Generate(new SeededRandomSource(1)).First();
head.ShouldStartWith("<!doctype html>");
head.ShouldContain("<head>");
head.ShouldContain("<title>");
head.ShouldContain("<style>");
head.ShouldContain("</head>");
head.ShouldContain("<body>");
}
[Fact]
public void Keeps_generating_varied_body_content()
{
var body = string.Concat(HtmlContent.Generate(new SeededRandomSource(2)).Skip(1).Take(400));
body.ShouldContain("<main>");
body.ShouldContain("<h2>");
body.ShouldContain("<p>");
body.ShouldContain("<li><a href=\"/");
body.ShouldNotContain("</html>");
body.Length.ShouldBeGreaterThan(50_000);
}
[Fact]
public void Varies_sentence_and_paragraph_lengths()
{
var paragraphs = string.Concat(HtmlContent.Generate(new SeededRandomSource(3)).Take(300))
.Split("<p>", StringSplitOptions.RemoveEmptyEntries)
.Skip(1)
.Select(p => p[..p.IndexOf("</p>", StringComparison.Ordinal)])
.ToList();
paragraphs.Select(p => p.Length).Distinct().Count().ShouldBeGreaterThan(paragraphs.Count / 2);
paragraphs.Select(p => p.Count(c => c is '.' or '?')).Distinct().Count().ShouldBeGreaterThan(3);
}
[Fact]
public void Is_deterministic_for_the_same_random_source()
{
var first = string.Concat(HtmlContent.Generate(new SeededRandomSource(4)).Take(50));
var second = string.Concat(HtmlContent.Generate(new SeededRandomSource(4)).Take(50));
var other = string.Concat(HtmlContent.Generate(new SeededRandomSource(5)).Take(50));
second.ShouldBe(first);
other.ShouldNotBe(first);
}
}
@@ -0,0 +1,35 @@
using System.Text;
using Flypaper.Core.Models;
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed class HtmlDripStrategyTests
{
[Fact]
public async Task Drips_html_in_small_chunks_until_cancelled()
{
var strategy = CreateStrategy();
var channel = new FakeTrapChannel();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
channel.Writes.Count.ShouldBeGreaterThan(5);
channel.Writes.ShouldAllBe(write => write.Length >= 1 && write.Length <= 64);
Encoding.UTF8.GetString(channel.Writes.SelectMany(write => write).ToArray()).ShouldStartWith("<!doctype html>");
}
[Theory]
[InlineData(TrapProtocol.Http, true)]
[InlineData(TrapProtocol.Ssh, false)]
public void Supports_only_http(TrapProtocol protocol, bool expected) =>
CreateStrategy().Supports(protocol).ShouldBe(expected);
private static HtmlDripStrategy CreateStrategy() => new(
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(5) }),
new SeededRandomSource(21),
TimeProvider.System);
}
@@ -7,11 +7,12 @@ 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");
"example.com\n*.example.org",
"90",
true);
[Fact]
public void Parses_valid_input_and_normalizes_lists()
@@ -22,10 +23,35 @@ public sealed class RuntimeSettingsParserTests
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));
settings.RetentionDays.ShouldBe(90);
settings.IgnorePrivateNetworks.ShouldBeTrue();
}
[Theory]
[InlineData("0", 0)]
[InlineData("365", 365)]
[InlineData("3650", 3650)]
public void Accepts_retention_days_including_unlimited(string value, int expected) =>
RuntimeSettingsParser.Parse(Valid with { RetentionDays = value }).Settings.ShouldNotBeNull().RetentionDays.ShouldBe(expected);
[Theory]
[InlineData("-1")]
[InlineData("3651")]
[InlineData("x")]
[InlineData("")]
public void Rejects_invalid_retention_days(string value) =>
RuntimeSettingsParser.Parse(Valid with { RetentionDays = value }).Errors.Keys.ShouldBe([nameof(RuntimeSettingsInput.RetentionDays)]);
[Fact]
public void Keeps_private_network_choice()
{
var settings = RuntimeSettingsParser.Parse(Valid with { IgnorePrivateNetworks = false }).Settings.ShouldNotBeNull();
settings.IgnorePrivateNetworks.ShouldBeFalse();
settings.ToConfiguration()[SettingKeys.IgnorePrivateNetworks].ShouldBe("false");
}
[Fact]
@@ -65,12 +91,12 @@ public sealed class RuntimeSettingsParserTests
[InlineData("abc")]
[InlineData("")]
[InlineData("00:00:00")]
[InlineData("02:00:00")]
public void Rejects_invalid_drip_intervals(string value)
[InlineData("8.00:00:00")]
public void Rejects_invalid_hold_durations(string value)
{
var result = RuntimeSettingsParser.Parse(Valid with { DripInterval = value });
var result = RuntimeSettingsParser.Parse(Valid with { MaxHoldDuration = value });
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.DripInterval));
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.MaxHoldDuration));
}
[Theory]
+48 -8
View File
@@ -47,7 +47,7 @@ public sealed class TrapRunnerTests
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));
e.Outcome == TrapOutcome.Timeout && e.BytesSent == _channel.Writes.Sum(w => w.Length) && e.BytesSent > 0));
}
[Fact]
@@ -59,7 +59,44 @@ public sealed class TrapRunnerTests
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"));
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "html-drip"));
}
[Theory]
[InlineData("192.168.1.20")]
[InlineData("172.19.0.1")]
[InlineData("127.0.0.1")]
public async Task Traps_but_does_not_store_private_ips_by_default(string ip)
{
AllowAcquire();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(ip), Open, cts.Token);
outcome.ShouldBe(TrapOutcome.ClientAborted);
_channel.Writes.ShouldNotBeEmpty();
_sink.DidNotReceiveWithAnyArgs().Publish(default!);
}
[Fact]
public async Task Does_not_store_rejected_private_ips_by_default()
{
_governor.TryAcquire(Arg.Any<TrapSession>(), out Arg.Any<IDisposable?>()).Returns(false);
await CreateRunner(TimeSpan.FromSeconds(1)).RunAsync(Context("10.0.0.5"), Open, CancellationToken.None);
_sink.DidNotReceiveWithAnyArgs().Publish(default!);
}
[Fact]
public async Task Stores_private_ips_when_option_is_off()
{
AllowAcquire();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
await CreateRunner(TimeSpan.FromMinutes(1), ignorePrivateNetworks: false).RunAsync(Context("192.168.1.20"), Open, cts.Token);
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.RemoteIp.Equals(IPAddress.Parse("192.168.1.20"))));
}
private IDisposable AllowAcquire()
@@ -76,18 +113,21 @@ public sealed class TrapRunnerTests
private ValueTask<ITrapChannel> Open(CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_channel);
private TrapRunner CreateRunner(TimeSpan maxHoldDuration)
private TrapRunner CreateRunner(TimeSpan maxHoldDuration, bool ignorePrivateNetworks = true)
{
var drip = new DripStrategy(TestOptions.Monitor(new DripOptions { Interval = TimeSpan.FromMilliseconds(20) }), TimeProvider.System);
var drip = new HtmlDripStrategy(
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(20) }),
new SeededRandomSource(7),
TimeProvider.System);
return new TrapRunner(
_governor,
[drip],
new ProtocolStrategySelector([drip]),
_sink,
TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }),
TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration, IgnorePrivateNetworks = ignorePrivateNetworks }),
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");
private static TrapContext Context(string ip = "203.0.113.9") =>
new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse(ip), DateTimeOffset.UtcNow), "GET /.env");
}
@@ -0,0 +1,10 @@
using Flypaper.Core.Abstractions;
namespace Flypaper.Tests.Fakes;
internal sealed class SeededRandomSource(int seed) : IRandomSource
{
private readonly Random _random = new(seed);
public int Next(int minValue, int maxValue) => _random.Next(minValue, maxValue);
}
@@ -0,0 +1,36 @@
using Flypaper.Storage;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Shouldly;
namespace Flypaper.Tests.Storage;
public sealed class MigrationTests : IDisposable
{
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-migration-{Guid.NewGuid():N}.db");
[Fact]
public async Task Removes_obsolete_drip_interval_override_from_existing_databases()
{
await using var db = new FlypaperDbContext(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite($"Data Source={_dbPath}").Options);
var migrator = db.GetService<IMigrator>();
await migrator.MigrateAsync("AddOrigin");
await db.Database.ExecuteSqlRawAsync(
"INSERT INTO \"Settings\" (\"Key\", \"Value\") VALUES ('Flypaper:Drip:Interval', '00:00:10'), ('Flypaper:MaxConnections', '50')");
await db.Database.MigrateAsync();
(await db.Settings.Select(s => s.Key).ToListAsync()).ShouldBe(["Flypaper:MaxConnections"]);
}
public void Dispose()
{
SqliteConnection.ClearAllPools();
foreach (var suffix in new[] { "", "-wal", "-shm" })
{
File.Delete(_dbPath + suffix);
}
}
}
@@ -1,6 +1,5 @@
using Flypaper.Core;
using Flypaper.Core.Settings;
using Flypaper.Core.Strategies;
using Flypaper.Http;
using Flypaper.Http.Matching;
using Flypaper.Storage;
@@ -74,16 +73,16 @@ public sealed class SettingsOverrideTests : IDisposable
await store.SaveAsync(new RuntimeSettings(
["/custom"],
TimeSpan.FromSeconds(3),
50,
4,
TimeSpan.FromMinutes(10),
["extra.example"]));
["extra.example"],
90,
true));
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.TrapPath);
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None);
matcher.Match("extra.example", "/").ShouldBe(TrapMatch.None);
host.Services.GetRequiredService<IOptionsMonitor<DripOptions>>().CurrentValue.Interval.ShouldBe(TimeSpan.FromSeconds(3));
(await store.HasOverridesAsync()).ShouldBeTrue();
await store.ResetAsync();
@@ -102,11 +101,12 @@ public sealed class SettingsOverrideTests : IDisposable
await host.Services.GetRequiredService<RuntimeSettingsStore>().SaveAsync(new RuntimeSettings(
[],
TimeSpan.FromSeconds(3),
50,
4,
TimeSpan.FromMinutes(10),
[]));
[],
90,
true));
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None);
}
@@ -0,0 +1,144 @@
using System.Net;
using Flypaper.Core.Models;
using Flypaper.Storage;
using Flypaper.Storage.Entities;
using Flypaper.Storage.Maintenance;
using Flypaper.Tests.Fakes;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
namespace Flypaper.Tests.Storage;
public sealed class TrapDataMaintenanceTests : IDisposable
{
private static readonly DateTimeOffset Now = new(2026, 11, 14, 12, 0, 0, TimeSpan.Zero);
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-maintenance-{Guid.NewGuid():N}.db");
private readonly IDbContextFactory<FlypaperDbContext> _dbContextFactory;
private readonly TrapDataMaintenance _maintenance;
public TrapDataMaintenanceTests()
{
_dbContextFactory = new TestDbContextFactory($"Data Source={_dbPath}");
using var db = _dbContextFactory.CreateDbContext();
db.Database.Migrate();
_maintenance = new TrapDataMaintenance(_dbContextFactory);
}
[Fact]
public async Task Deletes_only_events_from_private_networks()
{
await SeedAsync(
("203.0.113.9", 1),
("192.168.1.20", 1),
("172.19.0.1", 1),
("127.0.0.1", 1),
("fd00::1", 1),
("fe80::1", 1),
("172.32.0.1", 1),
("8.8.8.8", 1));
(await _maintenance.DeletePrivateAsync()).ShouldBe(5);
(await RemainingIpsAsync()).ShouldBe(["203.0.113.9", "172.32.0.1", "8.8.8.8"], ignoreOrder: true);
}
[Fact]
public async Task Deletes_all_events_but_keeps_settings()
{
await SeedAsync(("203.0.113.9", 1), ("8.8.8.8", 2));
await using (var db = await _dbContextFactory.CreateDbContextAsync())
{
db.Settings.Add(new SettingEntity { Key = "Flypaper:MaxConnections", Value = "5" });
await db.SaveChangesAsync();
}
(await _maintenance.DeleteAllAsync()).ShouldBe(2);
await _maintenance.VacuumAsync();
await using var check = await _dbContextFactory.CreateDbContextAsync();
(await check.TrapEvents.CountAsync()).ShouldBe(0);
(await check.Settings.CountAsync()).ShouldBe(1);
}
[Fact]
public async Task Reports_count_oldest_event_and_file_size()
{
await SeedAsync(("203.0.113.9", 10), ("8.8.8.8", 3));
var stats = await _maintenance.GetStatsAsync();
stats.Count.ShouldBe(2);
stats.Oldest.ShouldBe(Now.UtcDateTime.AddDays(-10));
stats.DatabaseBytes.ShouldNotBeNull().ShouldBeGreaterThan(0);
}
[Fact]
public async Task Retention_deletes_events_older_than_configured_days()
{
await SeedAsync(("203.0.113.9", 100), ("203.0.113.10", 91), ("203.0.113.11", 89), ("203.0.113.12", 1));
(await CreateCleanup(days: 90).CleanupAsync(CancellationToken.None)).ShouldBe(2);
(await RemainingIpsAsync()).ShouldBe(["203.0.113.11", "203.0.113.12"], ignoreOrder: true);
}
[Fact]
public async Task Retention_of_zero_days_keeps_everything()
{
await SeedAsync(("203.0.113.9", 4000));
(await CreateCleanup(days: 0).CleanupAsync(CancellationToken.None)).ShouldBe(0);
(await RemainingIpsAsync()).ShouldBe(["203.0.113.9"]);
}
private RetentionCleanup CreateCleanup(int days) => new(
_maintenance,
TestOptions.Monitor(new RetentionOptions { Days = days }),
new FixedTimeProvider(Now),
NullLogger<RetentionCleanup>.Instance);
private async Task SeedAsync(params (string Ip, int DaysAgo)[] events)
{
await using var db = await _dbContextFactory.CreateDbContextAsync();
foreach (var (ip, daysAgo) in events)
{
var started = Now.AddDays(-daysAgo);
db.TrapEvents.Add(TrapEventEntity.From(new TrapEvent(
Guid.NewGuid(),
TrapProtocol.Http,
IPAddress.Parse(ip),
"drip",
started,
started.AddSeconds(5),
5,
TrapOutcome.ClientAborted)));
}
await db.SaveChangesAsync();
}
private async Task<List<string>> RemainingIpsAsync()
{
await using var db = await _dbContextFactory.CreateDbContextAsync();
return await db.TrapEvents.Select(e => e.RemoteIp).ToListAsync();
}
public void Dispose()
{
SqliteConnection.ClearAllPools();
foreach (var suffix in new[] { "", "-wal", "-shm" })
{
File.Delete(_dbPath + suffix);
}
}
private sealed class TestDbContextFactory(string connectionString) : IDbContextFactory<FlypaperDbContext>
{
public FlypaperDbContext CreateDbContext() =>
new(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite(connectionString).Options);
}
}