Files
Heimdall/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.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

155 lines
6.5 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Heimdall.TestCommon;
using Microsoft.Playwright;
using Shouldly;
namespace Heimdall.E2E.Tests.Pages;
/// <summary>
/// User-management tests driven through the real Blazor UI (/users):
/// list, create, edit roles, lock/unlock, reset password — as the seeded admin.
/// </summary>
public class UserManagementTests : E2ETestBase
{
public UserManagementTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
[Fact]
public async Task Users_page_lists_admin_when_authenticated()
{
await LoginViaUiAsync();
await GotoWithCircuitAsync("/users");
await Page.WaitForSelectorAsync("text=Nouvel utilisateur", new() { Timeout = 20000 });
var body = (await Page.Locator("body").TextContentAsync())!;
body.ShouldContain(AdminEmail);
body.ShouldContain("Admin Test");
}
[Fact]
public async Task Admin_can_create_a_viewer_user_via_the_dialog()
{
await LoginViaUiAsync();
await GotoWithCircuitAsync("/users");
await Page.WaitForSelectorAsync("text=Nouvel utilisateur", new() { Timeout = 20000 });
await Page.ClickAsync("text=Nouvel utilisateur");
var dialog = Page.Locator(".mud-dialog");
await dialog.WaitForAsync(new() { Timeout = 10000 });
await dialog.Locator("input[autocomplete='email']").WaitForAsync(new() { Timeout = 10000 });
var email = $"e2e-user-{Guid.NewGuid():N}@heimdall.test";
await dialog.Locator("input[autocomplete='email']").FillAsync(email);
await dialog.Locator("input[autocomplete='name']").FillAsync("E2E Viewer");
await dialog.Locator("input[autocomplete='new-password']").FillAsync("ViewerPass123!");
// Role defaults to Viewer in the select — create directly
await dialog.Locator("button:has-text('Créer')").ClickAsync();
// Dialog closes, table reloads and contains the new user
await Page.WaitForSelectorAsync($"text={email}", new() { Timeout = 15000 });
var body = (await Page.Locator("body").TextContentAsync())!;
body.ShouldContain("E2E Viewer");
}
[Fact]
public async Task New_user_can_log_in_with_viewer_role()
{
// Create a viewer through the API (admin token), then sign in via the UI
var email = $"e2e-viewer-{Guid.NewGuid():N}@heimdall.test";
var password = "ViewerPass123!";
var token = await LoginViaApiAsync();
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
var createResp = await http.PostAsJsonAsync("/api/users", new
{
email,
password,
displayName = "E2E Viewer Login",
roles = new[] { "Viewer" }
});
createResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Created);
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')");
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
await Page.WaitForSelectorAsync("text=Bienvenue", new() { Timeout = 15000 });
(await Page.Locator("body").TextContentAsync())!.ShouldContain("Bienvenue");
// A viewer must NOT see the admin Users page in the nav
var usersNav = await Page.Locator("a[href='/users']").CountAsync();
usersNav.ShouldBe(0);
}
[Fact]
public async Task Admin_can_edit_user_display_name_and_roles()
{
// Create a throwaway user via the API
var email = $"e2e-edit-{Guid.NewGuid():N}@heimdall.test";
var token = await LoginViaApiAsync();
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
var createResp = await http.PostAsJsonAsync("/api/users", new
{
email,
password = "EditPass123!",
displayName = "Avant Modification",
roles = new[] { "Viewer" }
});
createResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Created);
await LoginViaUiAsync();
await GotoWithCircuitAsync("/users");
await Page.WaitForSelectorAsync($"text={email}", new() { Timeout = 20000 });
// Open the edit dialog via the pencil icon in the user row
var row = Page.Locator($"tr:has-text('{email}')");
await row.Locator("button").First.ClickAsync();
// Rename + grant Supervisor (scope to the edit dialog)
var dialog = Page.Locator(".mud-dialog");
await dialog.WaitForAsync(new() { Timeout = 10000 });
// The display-name field is the first text input in the dialog
var nameInput = dialog.Locator("input:not([type='password'])").First;
await nameInput.WaitForAsync(new() { Timeout = 10000 });
await nameInput.FillAsync("Après Modification");
await dialog.Locator("label:has-text('Supervisor')").ClickAsync();
await dialog.Locator("button:has-text('Enregistrer')").ClickAsync();
await Page.WaitForSelectorAsync("text=Après Modification", new() { Timeout = 15000 });
}
[Fact]
public async Task Admin_can_reset_user_password()
{
var email = $"e2e-reset-{Guid.NewGuid():N}@heimdall.test";
var token = await LoginViaApiAsync();
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
http.DefaultRequestHeaders.Authorization = new("Bearer", token);
var createResp = await http.PostAsJsonAsync("/api/users", new
{
email,
password = "ResetPass123!",
displayName = "E2E Reset",
roles = new[] { "Viewer" }
});
createResp.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Created);
await LoginViaUiAsync();
await GotoWithCircuitAsync("/users");
await Page.WaitForSelectorAsync($"text={email}", new() { Timeout = 20000 });
var row = Page.Locator($"tr:has-text('{email}')");
await row.Locator("button").First.ClickAsync();
var dialog = Page.Locator(".mud-dialog");
await dialog.WaitForAsync(new() { Timeout = 10000 });
await dialog.Locator("button:has-text('Réinitialiser le mot de passe')").ClickAsync();
// The dialog reveals a temporary password
await dialog.Locator("text=temporaire").WaitForAsync(new() { Timeout = 10000 });
}
}