Files
Heimdall/tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs
T
arnaud.dartois 1ca5f16527
Heimdall Gitea / Detect CI scope (pull_request) Successful in 7s
Heimdall Gitea / Build and tests (pull_request) Successful in 22m19s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Successful in 8m46s
Heimdall Gitea / Build and scan server image (pull_request) Successful in 11m19s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Successful in 17m37s
Heimdall Gitea / CI policy (pull_request) Successful in 2s
Fix nullable camera access selectors (#288)
2026-11-08 19:24:08 +01:00

325 lines
17 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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>
[Collection("E2E")]
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");
// Wait for the specific element that indicates the page is fully loaded
await Page.WaitForSelectorAsync("text=Nouvel utilisateur", new() { Timeout = 60000 });
await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);
await Task.Delay(3000);
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.GetByRole(AriaRole.Button, new() { Name = "Modifier l'utilisateur", Exact = true }).ClickAsync();
// Rename + grant Supervisor (scope to the edit dialog)
var dialog = Page.Locator(".mud-dialog");
await dialog.WaitForAsync(new() { Timeout = 10000 });
var nameInput = dialog.GetByLabel("Nom d'affichage", new() { Exact = true });
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_grant_site_wide_and_camera_access_without_nullable_select_cast()
{
if (string.Equals(Environment.GetEnvironmentVariable("HEIMDALL_E2E_BOOTSTRAP_ADMIN"), "true",
StringComparison.OrdinalIgnoreCase))
{
var bootstrapEmail = Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_EMAIL")
?? throw new InvalidOperationException("HEIMDALL_E2E_ADMIN_EMAIL is required for external acceptance.");
var bootstrapPassword = Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_PASSWORD")
?? throw new InvalidOperationException("HEIMDALL_E2E_ADMIN_PASSWORD is required for external acceptance.");
using var bootstrap = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var bootstrapResponse = await bootstrap.PostAsJsonAsync("api/auth/bootstrap-admin", new
{
email = bootstrapEmail,
password = bootstrapPassword,
displayName = "Disposable Acceptance Admin"
});
var bootstrapBody = await bootstrapResponse.Content.ReadAsStringAsync();
bootstrapResponse.StatusCode.ShouldBe(HttpStatusCode.OK,
$"Bootstrap status={bootstrapResponse.StatusCode}; response={bootstrapBody}");
// Bootstrap is performed through the supported one-time endpoint;
// the grant workflow below still logs in and operates through UI.
}
var token = await LoginViaApiAsync();
using var admin = new HttpClient { BaseAddress = new Uri(BaseUrl) };
admin.DefaultRequestHeaders.Authorization = new("Bearer", token);
// The panel loads the first page of sites; use a sortable prefix so a
// shared E2E database with older fixtures still includes this site.
var siteName = $"000 Nullable select {Guid.NewGuid():N}";
var siteResponse = await admin.PostAsJsonAsync("api/sites", new { name = siteName, timezone = "UTC" });
siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var siteId = (await siteResponse.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>())
.GetProperty("id").GetGuid();
var listedSites = await admin.GetFromJsonAsync<System.Text.Json.JsonElement>("api/sites?page=1&pageSize=20");
listedSites.GetProperty("items").EnumerateArray().ShouldContain(site =>
site.GetProperty("id").GetGuid() == siteId);
var cameraName = $"Nullable camera {Guid.NewGuid():N}";
var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new
{
siteId,
name = cameraName,
rtspUrl = $"rtsp://127.0.0.1/{Guid.NewGuid():N}"
});
cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var cameraId = (await cameraResponse.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>())
.GetProperty("id").GetGuid();
var email = $"nullable-select-{Guid.NewGuid():N}@heimdall.test";
var userResponse = await admin.PostAsJsonAsync("api/users", new
{
email,
password = "NullableSelect123!",
displayName = "Nullable Select Viewer",
roles = new[] { "Viewer" }
});
userResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var userId = (await userResponse.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>())
.GetProperty("id").GetGuid();
var pageErrors = new List<string>();
Page.PageError += (_, error) => pageErrors.Add(error);
// Use the real login page so the browser cookie and Blazor circuit's
// in-memory API token are both initialized for grant saves.
await LoginViaUiAsync();
await GotoWithCircuitAsync("/users");
var userRow = Page.Locator($"tr:has-text('{email}')");
await userRow.GetByRole(AriaRole.Button, new() { Name = "Gérer les caméras", Exact = true }).ClickAsync();
await Page.Locator(".camera-access-panel").WaitForAsync();
// Blazor Server executes HeimdallApiClient calls inside its circuit on
// the server, so api/sites is not a browser network response. The
// authenticated direct API list assertion above verifies its JSON data.
await Page.Locator(".camera-access-panel .mud-progress-circular").WaitForAsync(
new() { State = WaitForSelectorState.Detached, Timeout = 15000 });
(await Page.Locator(".camera-access-panel .mud-alert-error").CountAsync()).ShouldBe(0);
var form = Page.Locator(".camera-access-panel");
var siteSelect = form.Locator(".mud-select:has(label.mud-input-label:text-is('Site'))").First;
var accessTypeSelect = form.Locator(".mud-select:has(label.mud-input-label:text-is('Type d’accès'))").First;
await siteSelect.ClickAsync();
// MudSelect renders its option list in a page-level popover, outside
// .camera-access-panel; wait for the option after opening the popover.
var siteOption = Page.Locator(".mud-popover-open .mud-list-item")
.Filter(new() { HasText = siteName });
try
{
await siteOption.WaitForAsync(new() { Timeout = 10000 });
}
catch (TimeoutException)
{
var popoverTexts = await Page.Locator(".mud-popover-open").AllInnerTextsAsync();
var loading = await Page.Locator(".camera-access-panel .mud-progress-circular").CountAsync();
var alerts = await Page.Locator(".camera-access-panel .mud-alert").AllInnerTextsAsync();
var gridText = await form.Locator(".mud-grid").InnerTextAsync();
var selectorCount = await form.Locator(".mud-grid .mud-select").CountAsync();
throw new Xunit.Sdk.XunitException($"Site option missing. Popovers=[{string.Join(" | ", popoverTexts)}], grid=[{gridText}], gridSelectors={selectorCount}, loading={loading}, alerts=[{string.Join(" | ", alerts)}]");
}
await siteOption.ClickAsync();
await form.GetByRole(AriaRole.Button, new() { Name = "Ajouter à la liste", Exact = true }).ClickAsync();
await form.Locator(".mud-table").First.GetByText(siteName, new() { Exact = true })
.WaitForAsync(new() { Timeout = 10000 });
var unsavedNotice = form.GetByText("Les changements ne sont appliqués qu’après l’enregistrement.",
new() { Exact = true });
await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 5000 });
await form.GetByRole(AriaRole.Button, new() { Name = "Enregistrer les accès", Exact = true }).ClickAsync();
await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Detached, Timeout = 15000 });
var saveErrorText = string.Join(" | ", await form.Locator(".mud-alert").AllInnerTextsAsync());
var siteGrantReadback = await admin.GetFromJsonAsync<System.Text.Json.JsonElement>(
$"api/user-camera-access/user/{userId}");
var siteGrantItems = siteGrantReadback.GetProperty("items").EnumerateArray().ToArray();
siteGrantItems.ShouldContain(grant => grant.GetProperty("siteId").GetGuid() == siteId
&& grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.Null,
customMessage: $"Save errors=[{saveErrorText}], API returned count={siteGrantItems.Length}, site matches={siteGrantItems.Count(grant => grant.GetProperty("siteId").GetGuid() == siteId)}, null camera count={siteGrantItems.Count(grant => grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.Null)}");
await accessTypeSelect.ClickAsync();
await Page.Locator(".mud-popover-open .mud-list-item")
.Filter(new() { HasText = "spécifique" }).ClickAsync();
var cameraSelect = form.Locator(".mud-select:has(label.mud-input-label:text-is('Caméra'))").First;
await cameraSelect.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 10000 });
await siteSelect.ClickAsync();
siteOption = Page.Locator(".mud-popover-open .mud-list-item")
.Filter(new() { HasText = siteName });
await siteOption.ClickAsync();
await cameraSelect.ClickAsync();
var cameraOption = Page.Locator(".mud-popover-open .mud-list-item")
.Filter(new() { HasText = cameraName });
await cameraOption.WaitForAsync(new() { Timeout = 10000 });
await cameraOption.ClickAsync();
await form.GetByRole(AriaRole.Button, new() { Name = "Ajouter à la liste", Exact = true }).ClickAsync();
await form.Locator(".mud-table").Last.GetByText(cameraName, new() { Exact = false })
.WaitForAsync(new() { Timeout = 10000 });
unsavedNotice = form.GetByText("Les changements ne sont appliqués qu’après l’enregistrement.",
new() { Exact = true });
await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 5000 });
await form.GetByRole(AriaRole.Button, new() { Name = "Enregistrer les accès", Exact = true }).ClickAsync();
await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Detached, Timeout = 15000 });
var saved = await admin.GetFromJsonAsync<System.Text.Json.JsonElement>(
$"api/user-camera-access/user/{userId}");
var grants = saved.GetProperty("items").EnumerateArray().ToArray();
grants.ShouldContain(grant => grant.GetProperty("siteId").GetGuid() == siteId
&& grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.Null);
grants.ShouldContain(grant => grant.GetProperty("siteId").GetGuid() == siteId
&& grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.String
&& grant.GetProperty("cameraId").GetGuid() == cameraId);
pageErrors.ShouldBeEmpty();
}
[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.GetByRole(AriaRole.Button, new() { Name = "Modifier l'utilisateur", Exact = true }).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 });
}
[Fact]
public async Task Admin_can_edit_role_permissions_in_the_permissions_ui()
{
await LoginViaUiAsync();
await GotoWithCircuitAsync("/admin/claims");
await Page.WaitForSelectorAsync("text=Matrice des permissions", new() { Timeout = 20000 });
var row = Page.Locator("tr").Filter(new() { HasText = "Écriture des caméras" });
await row.WaitForAsync(new() { Timeout = 10000 });
var roleChecks = row.Locator("input[type='checkbox']");
await roleChecks.Nth(1).UncheckAsync(); // Supervisor; Admin stays immutable.
var saveButtons = Page.GetByRole(AriaRole.Button, new() { Name = "Enregistrer", Exact = true });
await saveButtons.Nth(0).ClickAsync();
await Page.WaitForSelectorAsync("text=Droits du rôle enregistrés", new() { Timeout = 10000 });
(await roleChecks.Nth(1).IsCheckedAsync()).ShouldBeFalse();
(await roleChecks.Nth(0).IsCheckedAsync()).ShouldBeTrue();
}
}