Remove trap paths and known hosts: catch everything on the trap port

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-15 18:56:35 +01:00
1 parent b9f2b0443c
commit 9a56fc5b48
31 files changed
+335 -462

No files matched your search

@@ -5,24 +5,15 @@ namespace Flypaper.Tests.Core;
public sealed class RuntimeSettingsParserTests
{
private static readonly RuntimeSettingsInput Valid = new(
"/.env\n/wp-admin/*\r\n /xmlrpc.php \n/.env",
"200",
"5",
"00:30:00",
"example.com\n*.example.org",
"90",
true);
private static readonly RuntimeSettingsInput Valid = new("200", "5", "00:30:00", "90", true);
[Fact]
public void Parses_valid_input_and_normalizes_lists()
public void Parses_valid_input()
{
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.MaxConnections.ShouldBe(200);
settings.MaxConnectionsPerIp.ShouldBe(5);
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(30));
@@ -54,38 +45,6 @@ public sealed class RuntimeSettingsParserTests
settings.ToConfiguration()[SettingKeys.IgnorePrivateNetworks].ShouldBe("false");
}
[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")]
+15
View File
@@ -0,0 +1,15 @@
using Microsoft.Extensions.Logging;
namespace Flypaper.Tests.Fakes;
internal sealed class ListLogger : ILogger
{
public List<(LogLevel Level, string Message)> Entries { get; } = [];
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) =>
Entries.Add((logLevel, formatter(state, exception)));
}
+1 -2
View File
@@ -48,8 +48,7 @@ public sealed class HealthProbeTests
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Flypaper:MaxConnections"] = "0",
["Flypaper:Http:KnownHosts:0"] = "dashboard.lan"
["Flypaper:MaxConnections"] = "0"
})
.Build();
+30 -22
View File
@@ -1,6 +1,7 @@
using System.Net;
using Flypaper.Core;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Flypaper.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
@@ -31,42 +32,49 @@ public sealed class PortSeparationTests
[Theory]
[InlineData("unknown.example", "/")]
[InlineData("203.0.113.7", "/settings")]
[InlineData("example.com", "/")]
[InlineData("example.com", "/.env")]
[InlineData("example.com", "/login")]
[InlineData("", "/wp-login.php")]
[InlineData("unknown.example", "/mcp")]
[InlineData("203.0.113.7", "/mcp")]
public async Task Trap_port_traps_unknown_hosts_and_trap_paths(string host, string path)
{
var (reachedApp, status) = await SendAsync(TrapPort, host, path);
reachedApp.ShouldBeFalse();
status.ShouldBe(StatusCodes.Status404NotFound);
}
[Theory]
[InlineData("/")]
[InlineData("/settings")]
[InlineData("/login")]
[InlineData("/mcp")]
public async Task Trap_port_answers_other_paths_of_known_hosts_with_plain_404(string path)
[InlineData("203.0.113.7", "/health")]
public async Task Trap_port_catches_every_host_and_path(string host, string path)
{
var sink = Substitute.For<ITrapEventSink>();
var (reachedApp, status) = await SendAsync(TrapPort, "example.com", path, sink);
var (reachedApp, status) = await SendAsync(TrapPort, host, path, sink);
reachedApp.ShouldBeFalse();
status.ShouldBe(StatusCodes.Status404NotFound);
sink.DidNotReceiveWithAnyArgs().Publish(default!);
sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.Rejected));
}
private static async Task<(bool ReachedApp, int Status)> SendAsync(int localPort, string host, string path, ITrapEventSink? sink = null)
[Fact]
public async Task Removed_settings_change_nothing()
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
var (reachedApp, _) = await SendAsync(
TrapPort,
"example.com",
"/",
extraSettings: new Dictionary<string, string?>
{
["Flypaper:MaxConnections"] = "0",
["Flypaper:Http:KnownHosts:0"] = "example.com",
["Flypaper:Http:TrapPaths:0"] = "/.env"
})
});
reachedApp.ShouldBeFalse();
}
private static async Task<(bool ReachedApp, int Status)> SendAsync(
int localPort,
string host,
string path,
ITrapEventSink? sink = null,
Dictionary<string, string?>? extraSettings = null)
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { ["Flypaper:MaxConnections"] = "0" })
.AddInMemoryCollection(extraSettings ?? [])
.Build();
var services = new ServiceCollection()
@@ -0,0 +1,41 @@
using Flypaper.Http;
using Flypaper.Tests.Fakes;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Shouldly;
namespace Flypaper.Tests.Http;
public sealed class RemovedSettingsTests
{
[Fact]
public void Warns_about_each_removed_setting_that_is_still_set()
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Flypaper:Http:KnownHosts:0"] = "example.com",
["Flypaper:Http:TrapPaths:0"] = "/.env",
["Flypaper:Http:TrustedProxies:0"] = "172.19.0.0/16"
})
.Build();
var logger = new ListLogger();
FlypaperHttpExtensions.WarnAboutRemovedSettings(configuration, logger);
logger.Entries.Count.ShouldBe(2);
logger.Entries.ShouldAllBe(e => e.Level == LogLevel.Warning);
logger.Entries.ShouldContain(e => e.Message.Contains("Flypaper__Http__KnownHosts"));
logger.Entries.ShouldContain(e => e.Message.Contains("Flypaper__Http__TrapPaths"));
}
[Fact]
public void Stays_silent_without_removed_settings()
{
var logger = new ListLogger();
FlypaperHttpExtensions.WarnAboutRemovedSettings(new ConfigurationBuilder().Build(), logger);
logger.Entries.ShouldBeEmpty();
}
}
@@ -1,42 +0,0 @@
using Flypaper.Http;
using Flypaper.Http.Matching;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Http;
public sealed class TrapMatcherTests
{
private readonly TrapMatcher _matcher = new(TestOptions.Monitor(new HttpTrapOptions
{
KnownHosts = ["example.com", "*.example.org"],
TrapPaths = ["/.env", "/.git/*", "/wp-login.php"]
}));
[Theory]
[InlineData("example.com", "/")]
[InlineData("EXAMPLE.com", "/index.html")]
[InlineData("app.example.org", "/api/items")]
[InlineData("example.com", "/.envelope")]
[InlineData("example.com", "/.git")]
public void Lets_normal_requests_pass(string host, string path) =>
_matcher.Match(host, path).ShouldBe(TrapMatch.None);
[Theory]
[InlineData("example.com", "/.env")]
[InlineData("example.com", "/.ENV")]
[InlineData("example.com", "/.env/")]
[InlineData("example.com", "/.git/config")]
[InlineData("app.example.org", "/wp-login.php")]
public void Traps_configured_paths(string host, string path) =>
_matcher.Match(host, path).ShouldBe(TrapMatch.TrapPath);
[Theory]
[InlineData("unknown.net", "/")]
[InlineData("203.0.113.7", "/")]
[InlineData("example.org", "/")]
[InlineData("", "/")]
[InlineData(null, "/")]
public void Traps_unknown_hosts(string? host, string path) =>
_matcher.Match(host, path).ShouldBe(TrapMatch.UnknownHost);
}
@@ -43,6 +43,22 @@ public sealed class MigrationTests : IDisposable
.ShouldBe(["GET /boaform/admin/formLogin", "GET example.com/.env"]);
}
[Fact]
public async Task Removes_obsolete_trap_path_and_known_host_overrides()
{
await using var db = new FlypaperDbContext(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite($"Data Source={_dbPath}").Options);
await db.GetService<IMigrator>().MigrateAsync("AddMcpTokens");
await db.Database.ExecuteSqlRawAsync(
"""
INSERT INTO "Settings" ("Key", "Value")
VALUES ('Flypaper:Http:ExtraKnownHosts', 'example.com'), ('Flypaper:Http:TrapPathsOverride', '/.env'), ('Flypaper:MaxConnections', '50')
""");
await db.Database.MigrateAsync();
(await db.Settings.Select(s => s.Key).ToListAsync()).ShouldBe(["Flypaper:MaxConnections"]);
}
public void Dispose()
{
SqliteConnection.ClearAllPools();
@@ -1,9 +1,9 @@
using Flypaper.Core;
using Flypaper.Core.Settings;
using Flypaper.Http;
using Flypaper.Http.Matching;
using Flypaper.Storage;
using Flypaper.Storage.Entities;
using Flypaper.Storage.Maintenance;
using Flypaper.Storage.Settings;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
@@ -28,8 +28,8 @@ public sealed class SettingsOverrideTests : IDisposable
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 = SettingKeys.RetentionDays, Value = "30" },
new SettingEntity { Key = "Flypaper:Http:TrustedProxies:0", Value = "203.0.113.0/24" },
new SettingEntity { Key = "Flypaper:Admin:Password", Value = "evil" });
await db.SaveChangesAsync();
}
@@ -38,14 +38,12 @@ public sealed class SettingsOverrideTests : IDisposable
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"]);
host.Services.GetRequiredService<IOptionsMonitor<RetentionOptions>>().CurrentValue.Days.ShouldBe(30);
host.Services.GetRequiredService<IOptionsMonitor<HttpTrapOptions>>().CurrentValue.TrustedProxies.ShouldBe(["172.18.0.0/16"]);
configuration["Flypaper:Admin:Password"].ShouldBe("secret");
}
@@ -56,61 +54,31 @@ public sealed class SettingsOverrideTests : IDisposable
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()
public async Task Saving_reloads_options_and_reset_restores_startup_values()
{
var host = BuildHost();
await host.Services.MigrateFlypaperDatabaseAsync();
var matcher = host.Services.GetRequiredService<TrapMatcher>();
var options = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>();
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(50, 4, TimeSpan.FromMinutes(10), 90, false));
await store.SaveAsync(new RuntimeSettings(
["/custom"],
50,
4,
TimeSpan.FromMinutes(10),
["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);
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();
await store.ResetAsync();
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.None);
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.TrapPath);
options.CurrentValue.MaxConnections.ShouldBe(100);
options.CurrentValue.IgnorePrivateNetworks.ShouldBeTrue();
(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(
[],
50,
4,
TimeSpan.FromMinutes(10),
[],
90,
true));
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None);
}
private IHost BuildHost()
{
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true });
@@ -119,8 +87,6 @@ public sealed class SettingsOverrideTests : IDisposable
["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"
});