Add persisted runtime settings page with cookie login
This commit is contained in:
1 parent
b561924efa
commit
37987a394a
43 files changed
+1346
-61
No files matched your search
@@ -1,6 +1,5 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests;
|
||||
@@ -70,7 +69,7 @@ public sealed class ConnectionGovernorTests
|
||||
}
|
||||
|
||||
private static ConnectionGovernor CreateGovernor(int maxConnections, int maxPerIp) =>
|
||||
new(Options.Create(new FlypaperOptions { MaxConnections = maxConnections, MaxConnectionsPerIp = maxPerIp }));
|
||||
new(TestOptions.Monitor(new FlypaperOptions { MaxConnections = maxConnections, MaxConnectionsPerIp = maxPerIp }));
|
||||
|
||||
private static TrapSession Session(IPAddress ip) => new(Guid.NewGuid(), TrapProtocol.Http, ip, DateTimeOffset.UtcNow);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests;
|
||||
@@ -39,5 +38,5 @@ public sealed class DripStrategyTests
|
||||
CreateStrategy(TimeSpan.FromSeconds(1)).Supports(protocol).ShouldBe(expected);
|
||||
|
||||
private static DripStrategy CreateStrategy(TimeSpan interval) =>
|
||||
new(Options.Create(new DripOptions { Interval = interval }), TimeProvider.System);
|
||||
new(TestOptions.Monitor(new DripOptions { Interval = interval }), TimeProvider.System);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using Flypaper.Core;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests;
|
||||
|
||||
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,140 @@
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Flypaper.Http;
|
||||
using Flypaper.Storage;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests;
|
||||
|
||||
public sealed class SettingsOverrideTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-test-{Guid.NewGuid():N}.db");
|
||||
private IHost? _host;
|
||||
|
||||
[Fact]
|
||||
public async Task Db_overrides_startup_values_for_whitelisted_keys_only()
|
||||
{
|
||||
await using (var db = new FlypaperDbContext(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite($"Data Source={_dbPath}").Options))
|
||||
{
|
||||
await db.Database.MigrateAsync();
|
||||
db.Settings.AddRange(
|
||||
new SettingEntity { Key = SettingKeys.MaxConnections, Value = "5" },
|
||||
new SettingEntity { Key = SettingKeys.TrapPaths, Value = "/custom\n/other/*" },
|
||||
new SettingEntity { Key = SettingKeys.ExtraKnownHosts, Value = "extra.example" },
|
||||
new SettingEntity { Key = "Flypaper:Admin:Password", Value = "evil" });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var host = BuildHost();
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
|
||||
var core = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>().CurrentValue;
|
||||
var http = host.Services.GetRequiredService<IOptionsMonitor<HttpTrapOptions>>().CurrentValue;
|
||||
var configuration = host.Services.GetRequiredService<IConfiguration>();
|
||||
|
||||
core.MaxConnections.ShouldBe(5);
|
||||
core.MaxConnectionsPerIp.ShouldBe(10);
|
||||
http.TrapPaths.ShouldBe(["/custom", "/other/*"]);
|
||||
http.KnownHosts.ShouldBe(["dashboard.lan", "extra.example"]);
|
||||
http.TrustedProxies.ShouldBe(["172.18.0.0/16"]);
|
||||
configuration["Flypaper:Admin:Password"].ShouldBe("secret");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_db_overrides_leave_startup_values_untouched()
|
||||
{
|
||||
var host = BuildHost();
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
|
||||
host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>().CurrentValue.MaxConnections.ShouldBe(100);
|
||||
host.Services.GetRequiredService<IOptionsMonitor<HttpTrapOptions>>().CurrentValue.TrapPaths.ShouldBe(["/.env"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Saving_reloads_trap_matcher_and_reset_restores_startup_values()
|
||||
{
|
||||
var host = BuildHost();
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
var matcher = host.Services.GetRequiredService<TrapMatcher>();
|
||||
var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
|
||||
|
||||
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.None);
|
||||
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.TrapPath);
|
||||
matcher.Match("extra.example", "/").ShouldBe(TrapMatch.UnknownHost);
|
||||
|
||||
await store.SaveAsync(new RuntimeSettings(
|
||||
["/custom"],
|
||||
TimeSpan.FromSeconds(3),
|
||||
50,
|
||||
4,
|
||||
TimeSpan.FromMinutes(10),
|
||||
["extra.example"]));
|
||||
|
||||
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();
|
||||
|
||||
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.None);
|
||||
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.TrapPath);
|
||||
(await store.HasOverridesAsync()).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Saved_empty_trap_path_list_disables_path_traps()
|
||||
{
|
||||
var host = BuildHost();
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
var matcher = host.Services.GetRequiredService<TrapMatcher>();
|
||||
|
||||
await host.Services.GetRequiredService<RuntimeSettingsStore>().SaveAsync(new RuntimeSettings(
|
||||
[],
|
||||
TimeSpan.FromSeconds(3),
|
||||
50,
|
||||
4,
|
||||
TimeSpan.FromMinutes(10),
|
||||
[]));
|
||||
|
||||
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None);
|
||||
}
|
||||
|
||||
private IHost BuildHost()
|
||||
{
|
||||
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true });
|
||||
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["ConnectionStrings:Flypaper"] = $"Data Source={_dbPath}",
|
||||
["Flypaper:MaxConnections"] = "100",
|
||||
["Flypaper:MaxConnectionsPerIp"] = "10",
|
||||
["Flypaper:Http:TrapPaths:0"] = "/.env",
|
||||
["Flypaper:Http:KnownHosts:0"] = "dashboard.lan",
|
||||
["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16",
|
||||
["Flypaper:Admin:Password"] = "secret"
|
||||
});
|
||||
builder.AddFlypaperStorage();
|
||||
builder.Services.AddLogging();
|
||||
builder.Services.AddFlypaperCore(builder.Configuration);
|
||||
builder.Services.AddFlypaperHttp(builder.Configuration);
|
||||
|
||||
return _host = builder.Build();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_host?.Dispose();
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
File.Delete(_dbPath + suffix);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Flypaper.Tests;
|
||||
|
||||
internal static class TestOptions
|
||||
{
|
||||
public static IOptionsMonitor<T> Monitor<T>(T value) where T : class
|
||||
{
|
||||
var monitor = Substitute.For<IOptionsMonitor<T>>();
|
||||
monitor.CurrentValue.Returns(value);
|
||||
return monitor;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
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
|
||||
private readonly TrapMatcher _matcher = new(TestOptions.Monitor(new HttpTrapOptions
|
||||
{
|
||||
KnownHosts = ["example.com", "*.example.org"],
|
||||
TrapPaths = ["/.env", "/.git/*", "/wp-login.php"]
|
||||
|
||||
@@ -2,7 +2,6 @@ using System.Net;
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
@@ -75,12 +74,12 @@ public sealed class TrapRunnerTests
|
||||
|
||||
private TrapRunner CreateRunner(TimeSpan maxHoldDuration)
|
||||
{
|
||||
var drip = new DripStrategy(Options.Create(new DripOptions { Interval = TimeSpan.FromMilliseconds(20) }), TimeProvider.System);
|
||||
var drip = new DripStrategy(TestOptions.Monitor(new DripOptions { Interval = TimeSpan.FromMilliseconds(20) }), TimeProvider.System);
|
||||
return new TrapRunner(
|
||||
_governor,
|
||||
[drip],
|
||||
_sink,
|
||||
Options.Create(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }),
|
||||
TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }),
|
||||
TimeProvider.System,
|
||||
NullLogger<TrapRunner>.Instance);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user