Files
Heimdall/tests/Heimdall.E2E.Tests/Pages/AuthFlowTests.cs
T

251 lines
10 KiB
C#
Raw Normal View History

using System.Buffers.Binary;
using System.Net.Http.Json;
using System.Security.Cryptography;
using Heimdall.Domain.Entities;
using Heimdall.TestCommon;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Playwright;
using Shouldly;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.E2E.Tests.Pages;
/// <summary>
/// Full authentication flow tests driven through the real Blazor UI:
/// login success/failure, validation, logout, protected-route redirects
/// and the one-time administrator setup gate.
/// </summary>
[Collection("E2E")]
public class AuthFlowTests : E2ETestBase
{
public AuthFlowTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
[Fact]
public async Task Login_page_renders()
{
await Page.GotoAsync($"{BaseUrl}/login");
await Page.WaitForSelectorAsync("input[autocomplete='email']", new() { Timeout = 15000 });
(await Page.Locator("h1").TextContentAsync())!.ShouldContain("Heimdall");
var regCount = await Page.Locator("a[href='/register']").CountAsync();
regCount.ShouldBe(0);
}
[Fact]
public async Task First_run_requires_setup_and_creates_the_initial_admin()
{
using (var scope = App.Services.CreateScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
foreach (var user in users.Users.ToList())
{
var deleted = await users.DeleteAsync(user);
deleted.Succeeded.ShouldBeTrue();
}
}
try
{
await Page.GotoAsync($"{BaseUrl}/login");
await Page.WaitForURLAsync("**/setup**", new() { Timeout = 15000 });
await GotoWithCircuitAsync("/setup");
await Page.FillAsync("input[autocomplete='name']", "Initial Admin");
await Page.FillAsync("input[autocomplete='email']", $"bootstrap-{Guid.NewGuid():N}@heimdall.test");
var passwordFields = Page.Locator("input[autocomplete='new-password']");
await passwordFields.Nth(0).FillAsync("FirstAdmin!Pass123456");
await passwordFields.Nth(1).FillAsync("FirstAdmin!Pass123456");
await Page.ClickAsync("button:has-text('Créer l’administrateur')");
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var status = await http.GetFromJsonAsync<BootstrapStatus>("/api/auth/bootstrap-status");
status!.SetupRequired.ShouldBeFalse();
}
finally
{
using var scope = App.Services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
foreach (var user in users.Users.ToList())
await users.DeleteAsync(user);
await Program.SeedAsync(App, App.Configuration);
}
}
[Fact]
public async Task Login_with_valid_admin_credentials_redirects_to_dashboard()
{
await LoginViaUiAsync();
// Blazor renders the dashboard content asynchronously after navigation.
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
(await Page.Locator("body").TextContentAsync())!.ShouldContain("Bienvenue");
// Nav bar should show the main items for an admin
var navCount = await Page.Locator("a[href='/users']").CountAsync();
navCount.ShouldBeGreaterThanOrEqualTo(1);
}
[Fact]
public async Task Authenticator_2fa_login_creates_a_usable_browser_cookie()
{
const string password = "BrowserTwoFactorPass123!";
var email = $"e2e-2fa-{Guid.NewGuid():N}@heimdall.test";
IdentityAppUser? user = null;
try
{
using (var scope = App.Services.CreateScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
user = new IdentityAppUser
{
Id = Guid.NewGuid(),
Email = email,
UserName = email,
EmailConfirmed = true
};
(await users.CreateAsync(user, password)).Succeeded.ShouldBeTrue();
(await users.AddToRoleAsync(user, "Viewer")).Succeeded.ShouldBeTrue();
(await users.ResetAuthenticatorKeyAsync(user)).Succeeded.ShouldBeTrue();
(await users.SetTwoFactorEnabledAsync(user, true)).Succeeded.ShouldBeTrue();
}
await GotoWithCircuitAsync("/login");
await Page.FillAsync("input[autocomplete='email']", email);
await Page.FillAsync("input[autocomplete='current-password']", password);
await Page.ClickAsync("button:has-text('Se connecter')");
var codeInput = Page.Locator("input[autocomplete='one-time-code']");
await codeInput.WaitForAsync(new() { Timeout = 15000 });
string authenticatorKey;
using (var scope = App.Services.CreateScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
var storedUser = await users.FindByIdAsync(user!.Id.ToString());
authenticatorKey = (await users.GetAuthenticatorKeyAsync(storedUser!))!;
}
await codeInput.FillAsync(GenerateTotp(authenticatorKey));
await Page.ClickAsync("button:has-text('Vérifier')");
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
var cookies = await Page.Context.CookiesAsync([BaseUrl]);
var authCookie = cookies.SingleOrDefault(cookie => cookie.Name == ".Heimdall.Auth");
authCookie.ShouldNotBeNull();
using var authenticated = new HttpClient();
authenticated.DefaultRequestHeaders.Add("Cookie", $".Heimdall.Auth={authCookie!.Value}");
var response = await authenticated.GetAsync($"{BaseUrl}/api/users/me");
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
}
finally
{
if (user is not null)
{
using var scope = App.Services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
var storedUser = await users.FindByIdAsync(user.Id.ToString());
if (storedUser is not null)
(await users.DeleteAsync(storedUser)).Succeeded.ShouldBeTrue();
}
}
}
[Fact]
public async Task Login_with_wrong_password_shows_error()
{
await GotoWithCircuitAsync("/login");
await Page.FillAsync("input[autocomplete='email']", AdminEmail);
await Page.FillAsync("input[autocomplete='current-password']", "WrongPassword123!");
await Page.ClickAsync("button:has-text('Se connecter')");
await Page.WaitForSelectorAsync(".auth-error", new() { Timeout = 10000 });
(await Page.Locator(".auth-error").TextContentAsync())!.ShouldContain("Email ou mot de passe invalide");
Page.Url.ShouldContain("/login");
}
[Fact]
public async Task Login_with_unknown_email_shows_error()
{
await GotoWithCircuitAsync("/login");
await Page.FillAsync("input[autocomplete='email']", "nobody@heimdall.test");
await Page.FillAsync("input[autocomplete='current-password']", AdminPassword);
await Page.ClickAsync("button:has-text('Se connecter')");
await Page.WaitForSelectorAsync(".auth-error", new() { Timeout = 10000 });
(await Page.Locator(".auth-error").TextContentAsync())!.ShouldContain("Email ou mot de passe invalide");
}
[Fact]
public async Task Protected_page_redirects_to_login_when_unauthenticated()
{
await Page.GotoAsync($"{BaseUrl}/users");
await Page.WaitForURLAsync("**/login**", new() { Timeout = 15000 });
}
[Fact]
public async Task Logout_returns_to_login()
{
await LoginViaUiAsync();
// Logout is a MudMenuItem in the user menu
await Page.ClickAsync("text=Déconnexion").ContinueWith(_ => { });
// Fallback: navigate via the /_auth/signout endpoint if the button isn't present
if (Page.Url.Contains("/dashboard"))
{
await Page.EvaluateAsync("fetch('/_auth/signout', { method: 'POST' })");
await Page.GotoAsync($"{BaseUrl}/dashboard");
}
await Page.WaitForURLAsync("**/login**", new() { Timeout = 15000 });
}
[Fact]
public async Task Register_route_redirects_to_login_after_initial_setup()
{
await Page.GotoAsync($"{BaseUrl}/register");
await Page.WaitForURLAsync("**/login**", new() { Timeout = 15000 });
}
[Fact]
public async Task AnonymousRegistrationApi_route_is_not_available()
{
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var response = await http.PostAsJsonAsync("/api/auth/register", new
{
email = $"e2e-register-{Guid.NewGuid():N}@heimdall.test",
password = "RegisterPass123!",
displayName = "E2E Register"
});
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound);
}
private sealed record BootstrapStatus(bool SetupRequired);
#pragma warning disable CA5350
private static string GenerateTotp(string base32Key)
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
var key = new List<byte>();
var buffer = 0;
var bits = 0;
foreach (var character in base32Key.TrimEnd('='))
{
buffer = (buffer << 5) | alphabet.IndexOf(character);
bits += 5;
if (bits < 8) continue;
bits -= 8;
key.Add((byte)(buffer >> bits));
}
Span<byte> message = stackalloc byte[8];
BinaryPrimitives.WriteInt64BigEndian(message, DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30);
var hash = HMACSHA1.HashData(key.ToArray(), message);
var offset = hash[^1] & 0x0f;
var binary = ((hash[offset] & 0x7f) << 24) | (hash[offset + 1] << 16)
| (hash[offset + 2] << 8) | hash[offset + 3];
return (binary % 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture);
}
#pragma warning restore CA5350
}