Add data management, randomized HTML drip and public README
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
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]
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
Reference in new issue
Block a user