Make the hold method configurable in the dashboard
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9a56fc5b48
commit
6b9bf3cd5f
40 files changed
+815
-134
No files matched your search
@@ -0,0 +1,73 @@
|
||||
using Flypaper.Core.Settings;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Core;
|
||||
|
||||
public sealed class HoldMethodParserTests
|
||||
{
|
||||
private static readonly HoldMethodInput Valid = new("Alternating", "50", "1000", "1", "64", "01:00:00");
|
||||
|
||||
[Fact]
|
||||
public void Parses_valid_input()
|
||||
{
|
||||
var settings = RuntimeSettingsParser.ParseHoldMethod(Valid).Settings.ShouldNotBeNull();
|
||||
|
||||
settings.Content.ShouldBe(DripContent.Alternating);
|
||||
settings.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));
|
||||
settings.MaxDelay.ShouldBe(TimeSpan.FromSeconds(1));
|
||||
settings.MinChunkSize.ShouldBe(1);
|
||||
settings.MaxChunkSize.ShouldBe(64);
|
||||
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1));
|
||||
settings.ToConfiguration().Keys.ShouldBe(SettingKeys.HoldMethod, ignoreOrder: true);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("html", DripContent.Html)]
|
||||
[InlineData("Text", DripContent.Text)]
|
||||
public void Accepts_content_case_insensitively(string value, DripContent expected) =>
|
||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { Content = value }).Settings.ShouldNotBeNull().Content.ShouldBe(expected);
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("fake-env")]
|
||||
[InlineData("7")]
|
||||
public void Rejects_unknown_content(string value) =>
|
||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { Content = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.Content)]);
|
||||
|
||||
[Theory]
|
||||
[InlineData("9", "1000")]
|
||||
[InlineData("50", "30001")]
|
||||
[InlineData("x", "1000")]
|
||||
public void Rejects_delays_out_of_range(string min, string max) =>
|
||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { MinDelayMs = min, MaxDelayMs = max }).Settings.ShouldBeNull();
|
||||
|
||||
[Theory]
|
||||
[InlineData("0", "64")]
|
||||
[InlineData("1", "4097")]
|
||||
public void Rejects_chunk_sizes_out_of_range(string min, string max) =>
|
||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { MinChunkSize = min, MaxChunkSize = max }).Settings.ShouldBeNull();
|
||||
|
||||
[Fact]
|
||||
public void Requires_minimum_not_above_maximum()
|
||||
{
|
||||
var errors = RuntimeSettingsParser.ParseHoldMethod(Valid with { MinDelayMs = "2000", MaxDelayMs = "1000", MinChunkSize = "100", MaxChunkSize = "10" }).Errors;
|
||||
|
||||
errors.Keys.ShouldBe([nameof(HoldMethodInput.MaxDelayMs), nameof(HoldMethodInput.MaxChunkSize)], ignoreOrder: true);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("10")]
|
||||
[InlineData("00:00:00")]
|
||||
[InlineData("8.00:00:00")]
|
||||
public void Rejects_invalid_hold_durations(string value) =>
|
||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { MaxHoldDuration = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.MaxHoldDuration)]);
|
||||
|
||||
[Fact]
|
||||
public void Computes_average_bandwidth()
|
||||
{
|
||||
HoldMethodSettings.AverageBytesPerSecond(TimeSpan.FromMilliseconds(50), TimeSpan.FromSeconds(1), 1, 64)
|
||||
.ShouldBe(61.9, tolerance: 0.1);
|
||||
HoldMethodSettings.AverageBytesPerSecond(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), 10, 10).ShouldBe(10);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ namespace Flypaper.Tests.Core;
|
||||
|
||||
public sealed class RuntimeSettingsParserTests
|
||||
{
|
||||
private static readonly RuntimeSettingsInput Valid = new("200", "5", "00:30:00", "90", true);
|
||||
private static readonly RuntimeSettingsInput Valid = new("200", "5", "90", true);
|
||||
|
||||
[Fact]
|
||||
public void Parses_valid_input()
|
||||
@@ -16,7 +16,6 @@ public sealed class RuntimeSettingsParserTests
|
||||
var settings = result.Settings.ShouldNotBeNull();
|
||||
settings.MaxConnections.ShouldBe(200);
|
||||
settings.MaxConnectionsPerIp.ShouldBe(5);
|
||||
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(30));
|
||||
settings.RetentionDays.ShouldBe(90);
|
||||
settings.IgnorePrivateNetworks.ShouldBeTrue();
|
||||
}
|
||||
@@ -45,19 +44,6 @@ public sealed class RuntimeSettingsParserTests
|
||||
settings.ToConfiguration()[SettingKeys.IgnorePrivateNetworks].ShouldBe("false");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("10")]
|
||||
[InlineData("abc")]
|
||||
[InlineData("")]
|
||||
[InlineData("00:00:00")]
|
||||
[InlineData("8.00:00:00")]
|
||||
public void Rejects_invalid_hold_durations(string value)
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { MaxHoldDuration = value });
|
||||
|
||||
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.MaxHoldDuration));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("0")]
|
||||
[InlineData("-3")]
|
||||
@@ -81,19 +67,11 @@ public sealed class RuntimeSettingsParserTests
|
||||
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);
|
||||
keys.ShouldBe(SettingKeys.General, ignoreOrder: true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Core.Runtime;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Flypaper.Tests.Fakes;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Core;
|
||||
|
||||
public sealed class StrategySelectionTests
|
||||
{
|
||||
private static readonly TrapContext Http =
|
||||
new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow));
|
||||
|
||||
[Theory]
|
||||
[InlineData(DripContent.Html, "html-drip")]
|
||||
[InlineData(DripContent.Text, "text-drip")]
|
||||
public void Selects_the_configured_content(DripContent content, string expected) =>
|
||||
Selector(content).Select(Http).ShouldNotBeNull().Name.ShouldBe(expected);
|
||||
|
||||
[Fact]
|
||||
public void Alternating_picks_both_strategies()
|
||||
{
|
||||
var selector = Selector(DripContent.Alternating);
|
||||
|
||||
var names = Enumerable.Range(0, 50).Select(_ => selector.Select(Http)!.Name).Distinct().ToList();
|
||||
|
||||
names.ShouldBe(["html-drip", "text-drip"], ignoreOrder: true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Returns_nothing_for_unsupported_protocols()
|
||||
{
|
||||
var ssh = Http with { Session = Http.Session with { Protocol = TrapProtocol.Ssh } };
|
||||
|
||||
Selector(DripContent.Html).Select(ssh).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Strategies_describe_themselves_with_their_parameters()
|
||||
{
|
||||
var options = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(100), MaxDelay = TimeSpan.FromMilliseconds(250), MinChunkSize = 2, MaxChunkSize = 8 });
|
||||
var text = new TextDripStrategy(options, new SeededRandomSource(1), TimeProvider.System);
|
||||
|
||||
text.Describe().ShouldBe("text-drip 100-250ms 2-8B");
|
||||
text.MediaType.ShouldStartWith("text/plain");
|
||||
new HtmlDripStrategy(options, new SeededRandomSource(1), TimeProvider.System).MediaType.ShouldStartWith("text/html");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Text_strategy_drips_plain_text()
|
||||
{
|
||||
var strategy = new TextDripStrategy(
|
||||
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(2), MinChunkSize = 32, MaxChunkSize = 64 }),
|
||||
new SeededRandomSource(3),
|
||||
TimeProvider.System);
|
||||
var channel = new FakeTrapChannel();
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
|
||||
|
||||
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
|
||||
|
||||
var text = Encoding.UTF8.GetString(channel.Writes.SelectMany(w => w).ToArray());
|
||||
text.Length.ShouldBeGreaterThan(200);
|
||||
text.ShouldNotContain("<");
|
||||
text.ShouldContain("\n");
|
||||
}
|
||||
|
||||
private static ConfiguredStrategySelector Selector(DripContent content)
|
||||
{
|
||||
var options = TestOptions.Monitor(new DripOptions { Content = content });
|
||||
var random = new SeededRandomSource(11);
|
||||
return new ConfiguredStrategySelector(
|
||||
[new HtmlDripStrategy(options, random, TimeProvider.System), new TextDripStrategy(options, random, TimeProvider.System)],
|
||||
options,
|
||||
random);
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ public sealed class TrapRunnerTests
|
||||
|
||||
var outcome = await CreateRunner(TimeSpan.FromSeconds(1)).RunAsync(
|
||||
Context(),
|
||||
_ =>
|
||||
(_, _) =>
|
||||
{
|
||||
opened = true;
|
||||
return ValueTask.FromResult<ITrapChannel>(_channel);
|
||||
@@ -59,7 +59,7 @@ 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 == "html-drip"));
|
||||
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "html-drip 5-20ms 1-64B"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -111,17 +111,16 @@ public sealed class TrapRunnerTests
|
||||
return lease;
|
||||
}
|
||||
|
||||
private ValueTask<ITrapChannel> Open(CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_channel);
|
||||
private ValueTask<ITrapChannel> Open(ITarpitStrategy strategy, CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_channel);
|
||||
|
||||
private TrapRunner CreateRunner(TimeSpan maxHoldDuration, bool ignorePrivateNetworks = true)
|
||||
{
|
||||
var drip = new HtmlDripStrategy(
|
||||
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(20) }),
|
||||
new SeededRandomSource(7),
|
||||
TimeProvider.System);
|
||||
var dripOptions = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(20) });
|
||||
var random = new SeededRandomSource(7);
|
||||
var drip = new HtmlDripStrategy(dripOptions, random, TimeProvider.System);
|
||||
return new TrapRunner(
|
||||
_governor,
|
||||
new ProtocolStrategySelector([drip]),
|
||||
new ConfiguredStrategySelector([drip], dripOptions, random),
|
||||
_sink,
|
||||
TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration, IgnorePrivateNetworks = ignorePrivateNetworks }),
|
||||
TimeProvider.System,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Abstractions;
|
||||
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 ContentTypeTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("Html", "text/html; charset=utf-8")]
|
||||
[InlineData("Text", "text/plain; charset=utf-8")]
|
||||
public async Task Trap_answers_with_the_media_type_of_the_selected_strategy(string content, string expected)
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Flypaper:MaxHoldDuration"] = "00:00:00.100",
|
||||
["Flypaper:Drip:Content"] = content,
|
||||
["Flypaper:Drip:MinDelay"] = "00:00:00.005",
|
||||
["Flypaper:Drip:MaxDelay"] = "00:00:00.010"
|
||||
})
|
||||
.Build();
|
||||
var services = new ServiceCollection()
|
||||
.AddLogging()
|
||||
.AddSingleton(Substitute.For<ITrapEventSink>())
|
||||
.AddFlypaperCore(configuration)
|
||||
.AddFlypaperHttp(configuration)
|
||||
.BuildServiceProvider();
|
||||
|
||||
var app = new ApplicationBuilder(services);
|
||||
app.UseFlypaper();
|
||||
var context = new DefaultHttpContext { RequestServices = services };
|
||||
context.Connection.RemoteIpAddress = IPAddress.Parse("203.0.113.9");
|
||||
context.Connection.LocalPort = 8080;
|
||||
context.Request.Path = "/";
|
||||
|
||||
await app.Build()(context);
|
||||
|
||||
context.Response.StatusCode.ShouldBe(StatusCodes.Status200OK);
|
||||
context.Response.ContentType.ShouldBe(expected);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Settings;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Flypaper.Http;
|
||||
using Flypaper.Storage;
|
||||
using Flypaper.Storage.Entities;
|
||||
@@ -64,11 +65,10 @@ public sealed class SettingsOverrideTests : IDisposable
|
||||
var options = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>();
|
||||
var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
|
||||
|
||||
await store.SaveAsync(new RuntimeSettings(50, 4, TimeSpan.FromMinutes(10), 90, false));
|
||||
await store.SaveAsync(new RuntimeSettings(50, 4, 90, false));
|
||||
|
||||
options.CurrentValue.MaxConnections.ShouldBe(50);
|
||||
options.CurrentValue.MaxConnectionsPerIp.ShouldBe(4);
|
||||
options.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(10));
|
||||
options.CurrentValue.IgnorePrivateNetworks.ShouldBeFalse();
|
||||
(await store.HasOverridesAsync()).ShouldBeTrue();
|
||||
|
||||
@@ -79,6 +79,36 @@ public sealed class SettingsOverrideTests : IDisposable
|
||||
(await store.HasOverridesAsync()).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hold_method_is_saved_and_reset_separately_from_general_settings()
|
||||
{
|
||||
var host = BuildHost();
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
var core = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>();
|
||||
var drip = host.Services.GetRequiredService<IOptionsMonitor<DripOptions>>();
|
||||
var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
|
||||
string[] holdKeys = [.. SettingKeys.HoldMethod];
|
||||
|
||||
await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, TimeSpan.FromMinutes(5)));
|
||||
await store.SaveAsync(new RuntimeSettings(50, 4, 90, true));
|
||||
|
||||
drip.CurrentValue.Content.ShouldBe(DripContent.Text);
|
||||
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(200));
|
||||
drip.CurrentValue.MaxChunkSize.ShouldBe(16);
|
||||
core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(5));
|
||||
core.CurrentValue.MaxConnections.ShouldBe(50);
|
||||
(await store.HasOverridesAsync(holdKeys)).ShouldBeTrue();
|
||||
|
||||
await store.ResetAsync(holdKeys);
|
||||
|
||||
drip.CurrentValue.Content.ShouldBe(DripContent.Html);
|
||||
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));
|
||||
core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1));
|
||||
core.CurrentValue.MaxConnections.ShouldBe(50);
|
||||
(await store.HasOverridesAsync(holdKeys)).ShouldBeFalse();
|
||||
(await store.HasOverridesAsync()).ShouldBeTrue();
|
||||
}
|
||||
|
||||
private IHost BuildHost()
|
||||
{
|
||||
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true });
|
||||
|
||||
Reference in new issue
Block a user