Separate dashboard port, first-run password setup and default trusted proxies
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a34ff96490
commit
c22d452720
25 files changed
+654
-109
No files matched your search
@@ -50,13 +50,38 @@ public sealed class ForwardedHeadersTests
|
||||
ip.ShouldBe(sender);
|
||||
}
|
||||
|
||||
private static async Task<IPAddress?> SendAsync(IPAddress remoteIp, params (string Name, string Value)[] headers)
|
||||
[Theory]
|
||||
[InlineData("172.19.0.3")]
|
||||
[InlineData("10.1.2.3")]
|
||||
[InlineData("192.168.1.2")]
|
||||
[InlineData("127.0.0.1")]
|
||||
[InlineData("fd00::2")]
|
||||
public async Task Trusts_private_networks_by_default(string proxy)
|
||||
{
|
||||
var ip = await SendAsync(IPAddress.Parse(proxy), trustedProxy: null, ("X-Real-IP", Client));
|
||||
|
||||
ip.ShouldBe(IPAddress.Parse(Client));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Configured_proxies_replace_the_default_networks()
|
||||
{
|
||||
var sender = IPAddress.Parse("192.168.1.2");
|
||||
|
||||
var ip = await SendAsync(sender, ("X-Real-IP", Client));
|
||||
|
||||
ip.ShouldBe(sender);
|
||||
}
|
||||
|
||||
private static Task<IPAddress?> SendAsync(IPAddress remoteIp, params (string Name, string Value)[] headers) =>
|
||||
SendAsync(remoteIp, "172.18.0.0/16", headers);
|
||||
|
||||
private static async Task<IPAddress?> SendAsync(IPAddress remoteIp, string? trustedProxy, params (string Name, string Value)[] headers)
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Flypaper:Http:KnownHosts:0"] = "dashboard.lan",
|
||||
["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16"
|
||||
["Flypaper:Http:TrustedProxies:0"] = trustedProxy
|
||||
})
|
||||
.Build();
|
||||
|
||||
@@ -78,6 +103,7 @@ public sealed class ForwardedHeadersTests
|
||||
|
||||
var httpContext = new DefaultHttpContext { RequestServices = services };
|
||||
httpContext.Connection.RemoteIpAddress = remoteIp;
|
||||
httpContext.Connection.LocalPort = 8081;
|
||||
httpContext.Request.Host = new HostString("dashboard.lan");
|
||||
httpContext.Request.Path = "/";
|
||||
foreach (var (name, value) in headers)
|
||||
|
||||
@@ -71,6 +71,7 @@ public sealed class HealthProbeTests
|
||||
|
||||
var httpContext = new DefaultHttpContext { RequestServices = services };
|
||||
httpContext.Connection.RemoteIpAddress = remoteIp;
|
||||
httpContext.Connection.LocalPort = 8080;
|
||||
httpContext.Request.Host = new HostString("flypaper:8080");
|
||||
httpContext.Request.Path = path;
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
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 PortSeparationTests
|
||||
{
|
||||
private const int TrapPort = 8080;
|
||||
private const int DashboardPort = 8081;
|
||||
private static readonly IPAddress PublicIp = IPAddress.Parse("203.0.113.9");
|
||||
|
||||
[Theory]
|
||||
[InlineData("unknown.example", "/")]
|
||||
[InlineData("unknown.example", "/.env")]
|
||||
[InlineData("203.0.113.7", "/wp-login.php")]
|
||||
public async Task Dashboard_port_never_traps(string host, string path)
|
||||
{
|
||||
var (reachedApp, _) = await SendAsync(DashboardPort, host, path);
|
||||
|
||||
reachedApp.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("unknown.example", "/")]
|
||||
[InlineData("203.0.113.7", "/settings")]
|
||||
[InlineData("example.com", "/.env")]
|
||||
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")]
|
||||
public async Task Trap_port_answers_other_paths_of_known_hosts_with_plain_404(string path)
|
||||
{
|
||||
var sink = Substitute.For<ITrapEventSink>();
|
||||
|
||||
var (reachedApp, status) = await SendAsync(TrapPort, "example.com", path, sink);
|
||||
|
||||
reachedApp.ShouldBeFalse();
|
||||
status.ShouldBe(StatusCodes.Status404NotFound);
|
||||
sink.DidNotReceiveWithAnyArgs().Publish(default!);
|
||||
}
|
||||
|
||||
private static async Task<(bool ReachedApp, int Status)> SendAsync(int localPort, string host, string path, ITrapEventSink? sink = null)
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Flypaper:MaxConnections"] = "0",
|
||||
["Flypaper:Http:KnownHosts:0"] = "example.com",
|
||||
["Flypaper:Http:TrapPaths:0"] = "/.env"
|
||||
})
|
||||
.Build();
|
||||
|
||||
var services = new ServiceCollection()
|
||||
.AddLogging()
|
||||
.AddSingleton(sink ?? Substitute.For<ITrapEventSink>())
|
||||
.AddFlypaperCore(configuration)
|
||||
.AddFlypaperHttp(configuration)
|
||||
.BuildServiceProvider();
|
||||
|
||||
var reachedApp = false;
|
||||
var app = new ApplicationBuilder(services);
|
||||
app.UseFlypaper();
|
||||
app.Run(_ =>
|
||||
{
|
||||
reachedApp = true;
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
var httpContext = new DefaultHttpContext { RequestServices = services };
|
||||
httpContext.Connection.RemoteIpAddress = PublicIp;
|
||||
httpContext.Connection.LocalPort = localPort;
|
||||
httpContext.Request.Host = new HostString(host);
|
||||
httpContext.Request.Path = path;
|
||||
|
||||
await app.Build()(httpContext);
|
||||
return (reachedApp, httpContext.Response.StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using Flypaper.Web.Auth;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Web;
|
||||
|
||||
public sealed partial class AdminSetupTests : IDisposable
|
||||
{
|
||||
private const string Password = "correct-horse-battery";
|
||||
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-setup-{Guid.NewGuid():N}.db");
|
||||
private readonly List<WebApplicationFactory<Program>> _factories = [];
|
||||
|
||||
[Fact]
|
||||
public async Task Without_password_login_leads_to_setup()
|
||||
{
|
||||
using var client = CreateClient(environmentPassword: null);
|
||||
|
||||
var response = await client.GetAsync("/login");
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
|
||||
response.Headers.Location!.OriginalString.ShouldEndWith("/setup");
|
||||
(await client.GetAsync("/setup")).StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Setup_sets_password_signs_in_and_closes_itself()
|
||||
{
|
||||
using var client = CreateClient(environmentPassword: null);
|
||||
|
||||
var response = await PostFormAsync(client, "/setup", "/auth/setup", ("password", Password), ("confirmation", Password));
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
|
||||
response.Headers.Location!.OriginalString.ShouldBe("/");
|
||||
(await client.GetAsync("/")).StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
|
||||
var setupAgain = await client.GetAsync("/setup");
|
||||
setupAgain.StatusCode.ShouldBe(HttpStatusCode.Redirect);
|
||||
setupAgain.Headers.Location!.OriginalString.ShouldEndWith("/login");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Second_setup_cannot_replace_the_password()
|
||||
{
|
||||
using var first = CreateClient(environmentPassword: null);
|
||||
await PostFormAsync(first, "/setup", "/auth/setup", ("password", Password), ("confirmation", Password));
|
||||
|
||||
using var attacker = CreateClient(environmentPassword: null);
|
||||
var token = await AntiforgeryTokenAsync(attacker, "/login");
|
||||
var response = await attacker.PostAsync("/auth/setup", Form(token, ("password", "attacker-password-1"), ("confirmation", "attacker-password-1")));
|
||||
|
||||
response.Headers.Location!.OriginalString.ShouldBe("/login");
|
||||
var admin = _factories[0].Services.GetRequiredService<AdminAuthenticator>();
|
||||
(await admin.VerifyAsync(Password)).ShouldBeTrue();
|
||||
(await admin.VerifyAsync("attacker-password-1")).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("short", "short")]
|
||||
[InlineData("long-enough-password", "other-long-password")]
|
||||
public async Task Setup_rejects_weak_or_mismatched_passwords(string password, string confirmation)
|
||||
{
|
||||
using var client = CreateClient(environmentPassword: null);
|
||||
|
||||
var response = await PostFormAsync(client, "/setup", "/auth/setup", ("password", password), ("confirmation", confirmation));
|
||||
|
||||
response.Headers.Location!.OriginalString.ShouldStartWith("/setup?error=");
|
||||
(await _factories[0].Services.GetRequiredService<AdminAuthenticator>().IsConfiguredAsync()).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Environment_password_overrides_setup()
|
||||
{
|
||||
using var client = CreateClient(environmentPassword: Password);
|
||||
|
||||
var setup = await client.GetAsync("/setup");
|
||||
setup.StatusCode.ShouldBe(HttpStatusCode.Redirect);
|
||||
setup.Headers.Location!.OriginalString.ShouldEndWith("/login");
|
||||
|
||||
var login = await PostFormAsync(client, "/login", "/auth/login", ("password", Password));
|
||||
login.Headers.Location!.OriginalString.ShouldBe("/");
|
||||
|
||||
var admin = _factories[0].Services.GetRequiredService<AdminAuthenticator>();
|
||||
admin.UsesEnvironmentPassword.ShouldBeTrue();
|
||||
(await admin.TrySetInitialPasswordAsync("another-long-password")).ShouldBeFalse();
|
||||
(await admin.TryChangePasswordAsync(Password, "another-long-password")).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Password_can_be_changed_with_the_current_one()
|
||||
{
|
||||
using var client = CreateClient(environmentPassword: null);
|
||||
var admin = _factories[0].Services.GetRequiredService<AdminAuthenticator>();
|
||||
(await admin.TrySetInitialPasswordAsync(Password)).ShouldBeTrue();
|
||||
|
||||
(await admin.TryChangePasswordAsync("wrong-current-pw", "new-password-12345")).ShouldBeFalse();
|
||||
(await admin.TryChangePasswordAsync(Password, "new-password-12345")).ShouldBeTrue();
|
||||
|
||||
(await admin.VerifyAsync(Password)).ShouldBeFalse();
|
||||
(await admin.VerifyAsync("new-password-12345")).ShouldBeTrue();
|
||||
}
|
||||
|
||||
private HttpClient CreateClient(string? environmentPassword)
|
||||
{
|
||||
var factory = _factories.FirstOrDefault() ?? new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}");
|
||||
builder.UseSetting("Flypaper:Ports:Dashboard", "0");
|
||||
builder.UseSetting("Flypaper:Admin:Password", environmentPassword ?? "");
|
||||
});
|
||||
|
||||
if (_factories.Count == 0)
|
||||
{
|
||||
_factories.Add(factory);
|
||||
}
|
||||
|
||||
return factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> PostFormAsync(
|
||||
HttpClient client,
|
||||
string formPage,
|
||||
string action,
|
||||
params (string Name, string Value)[] fields) =>
|
||||
await client.PostAsync(action, Form(await AntiforgeryTokenAsync(client, formPage), fields));
|
||||
|
||||
private static async Task<string> AntiforgeryTokenAsync(HttpClient client, string page)
|
||||
{
|
||||
var html = await client.GetStringAsync(page);
|
||||
return TokenPattern().Match(html).Groups[1].Value;
|
||||
}
|
||||
|
||||
private static FormUrlEncodedContent Form(string token, params (string Name, string Value)[] fields) =>
|
||||
new(fields.Select(f => KeyValuePair.Create(f.Name, f.Value)).Append(KeyValuePair.Create("__RequestVerificationToken", token)));
|
||||
|
||||
[GeneratedRegex("name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"")]
|
||||
private static partial Regex TokenPattern();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var factory in _factories)
|
||||
{
|
||||
factory.Dispose();
|
||||
}
|
||||
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
File.Delete(_dbPath + suffix);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ public sealed class HealthEndpointTests : IDisposable
|
||||
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}");
|
||||
builder.UseSetting("Flypaper:Http:KnownHosts:0", "localhost");
|
||||
builder.UseSetting("Flypaper:Ports:Dashboard", "0");
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user