Files
Heimdall/tests/Heimdall.E2E.Tests/Pages/AuthFlowTests.cs
T
Arnaud Dartois 53b6240a3e fix(auth): répare l'authentification de bout en bout (cookie + JWT + rendu Blazor)
Anomalies corrigées :
- MudPopoverProvider manquant dans les layouts → circuit Blazor mourait sur
  l'ouverture de menus/popovers (dashboard jamais rendu après login)
- AddIdentity redéfinissait le schéma par défaut sur Identity.Application
  alors que /_auth/signin signait avec Cookies → cookie posé mais jamais
  validé, tout rechargement de page redirigeait vers /login. Forçage du
  schéma par défaut sur Cookies + schémas JwtBearer explicites sur les
  endpoints API d'AuthController et SettingsController
- Policy 'AdminUsers' utilisée par register-admin mais jamais enregistrée
  → 500 à l'appel. Ajoutée (RequireRole Admin)
- HeimdallAuthStateProvider ne lisait que le sessionStorage navigateur :
  pendant le prerender SSR, HttpContext.User (cookie) n'était pas utilisé
  → pages protégées redirigées vers /login. Fallback cookie ajouté
- SameOriginHttpMessageHandler : résolution de l'origine via
  IServerAddressesFeature quand IHttpContextAccessor est null (circuit
  Blazor post-hydratation) au lieu de heimdall.local → DNS cassé
- UpdateUserValidator rejetait le thème 'Auto' (défaut de l'UI) → 400
  à l'édition. Accepte désormais auto (case-insensitive)

Tests :
- E2E Playwright complets (login/logout/register/user management) : 33/33
- Integration (Testcontainers PostgreSQL) : 120/120 (valeur 'bool' du
  valueType, bootstrap admin via /register auto-admin, header X-API-Key,
  /proc/meminfo optionnel pour les LXC restreints)
- Exécution E2E séquentielle (xunit.runner.json) pour éliminer le flakiness
2026-08-09 23:43:11 +02:00

154 lines
6.6 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Heimdall.TestCommon;
using Microsoft.Playwright;
using Shouldly;
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 public registration (with the feature flag enabled).
/// </summary>
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.ShouldBeGreaterThanOrEqualTo(1);
}
[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 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_creates_account_when_public_registration_enabled()
{
// Enable the public-registration feature flag as admin via the API
var token = await LoginViaApiAsync();
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
var setResp = await http.PostAsJsonAsync("/api/settings", new
{
key = "auth.public-registration.enabled",
value = "true",
category = "auth",
description = "Public registration enabled",
valueType = "bool"
});
setResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Created);
var email = $"e2e-register-{Guid.NewGuid():N}@heimdall.test";
await GotoWithCircuitAsync("/register");
await Page.FillAsync("input[autocomplete='name']", "E2E Register");
await Page.FillAsync("input[autocomplete='email']", email);
await Page.FillAsync("input[autocomplete='new-password']", "RegisterPass123!");
await Page.ClickAsync("button:has-text(\"S'inscrire\")");
// New viewer account lands on the dashboard
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
Page.Url.ShouldContain("/dashboard");
// Clean up: disable the flag again so other tests see the default state
var delResp = await http.DeleteAsync("/api/settings/auth.public-registration.enabled");
delResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.NotFound, HttpStatusCode.NoContent);
}
[Fact]
public async Task Register_is_blocked_when_public_registration_disabled()
{
var email = $"e2e-blocked-{Guid.NewGuid():N}@heimdall.test";
// The E2E suite shares one Postgres container; a previous test may have
// enabled public registration. Ensure the setting is OFF for this test.
var token = await LoginViaApiAsync();
using (var http = new HttpClient { BaseAddress = new Uri(BaseUrl) })
{
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
var del = await http.DeleteAsync("/api/settings/auth.public-registration.enabled");
del.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.NotFound, HttpStatusCode.NoContent);
}
await GotoWithCircuitAsync("/register");
await Page.FillAsync("input[autocomplete='name']", "E2E Blocked");
await Page.FillAsync("input[autocomplete='email']", email);
await Page.FillAsync("input[autocomplete='new-password']", "RegisterPass123!");
await Page.ClickAsync("button:has-text(\"S'inscrire\")");
// The UI shows a generic error and stays on the register page when the
// backend rejects the signup (public registration disabled).
await Page.WaitForSelectorAsync(".auth-error", new() { Timeout = 10000 });
var errorText = (await Page.Locator(".auth-error").TextContentAsync())!;
errorText.ShouldNotBeNullOrWhiteSpace();
Page.Url.ShouldContain("/register");
}
}