157 lines
6.4 KiB
C#
157 lines
6.4 KiB
C#
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);
|
|
}
|
|
}
|
|
}
|