Fix nullable camera access selectors (#288)
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

This commit is contained in:
arnaud.dartois committed 2026-11-08 19:24:08 +01:00
1 parent 5bcd4968a8
commit 1ca5f16527
8 files changed
+3200 -16

No files matched your search

@@ -0,0 +1,17 @@
---
name: camera-access-nullable-select
description: Keep nullable camera-access grant selectors type-consistent in the Heimdall Blazor UI and verify site-wide and camera-specific grants.
---
# Camera access nullable selectors
The grant form in `src/Heimdall.Web/Components/Pages/CameraAccessPanel.razor` stores the selected site and camera as `Guid?` because the form supports an unset selection. Keep each corresponding `MudSelect` and all of its `MudSelectItem` children explicitly typed as `Guid?`; cast non-nullable model IDs with `(Guid?)` in each item value. A plain `Guid` item can compile yet fail at runtime when MudBlazor dispatches the option click to its nullable parent.
When editing this form, preserve the two grant modes: site-wide grants save a site ID and null camera ID, while camera-specific grants save both IDs. Validate both selection interactions and the serialized saved grants.
## Acceptance workflow
1. Run the focused Web tests with `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore` and build `src/Heimdall.Web/Heimdall.Web.csproj` using the SDK pinned in `global.json`.
2. For behavior changes, follow [the disposable Compose recipe](../compose-disposable-recipe/SKILL.md): build the changed source using unique local image tags and isolated credentials, project, ports, network, and volumes.
3. Bootstrap an isolated administrator, use a real browser/UI-capable test to select a site-wide option and a camera option, and verify the saved grants contain respectively a null and non-null camera ID with no `InvalidCastException`.
4. Tear down only that Compose project. Verify its containers, volumes, and networks are absent; remove and verify absence of only the recipe's exact locally built tags, preserving shared base images.
@@ -11,7 +11,16 @@ public class UserCameraAccessConfiguration : IEntityTypeConfiguration<UserCamera
{
builder.ToTable("UserCameraAccesses");
builder.HasKey(eca => new { eca.UserId, eca.SiteId, eca.CameraId });
builder.HasKey(eca => eca.Id);
// A site-wide grant has a null CameraId, so it cannot participate in
// a primary key. Keep duplicate protection with two partial indexes.
builder.HasIndex(eca => new { eca.UserId, eca.SiteId })
.IsUnique()
.HasFilter("\"CameraId\" IS NULL");
builder.HasIndex(eca => new { eca.UserId, eca.SiteId, eca.CameraId })
.IsUnique()
.HasFilter("\"CameraId\" IS NOT NULL");
builder.HasOne<IdentityAppUser>()
.WithMany()
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,79 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AllowSiteWideCameraAccess : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_UserCameraAccesses",
table: "UserCameraAccesses");
migrationBuilder.AlterColumn<Guid>(
name: "CameraId",
table: "UserCameraAccesses",
type: "uuid",
nullable: true,
oldClrType: typeof(Guid),
oldType: "uuid");
migrationBuilder.AddPrimaryKey(
name: "PK_UserCameraAccesses",
table: "UserCameraAccesses",
column: "Id");
migrationBuilder.CreateIndex(
name: "IX_UserCameraAccesses_UserId_SiteId",
table: "UserCameraAccesses",
columns: new[] { "UserId", "SiteId" },
unique: true,
filter: "\"CameraId\" IS NULL");
migrationBuilder.CreateIndex(
name: "IX_UserCameraAccesses_UserId_SiteId_CameraId",
table: "UserCameraAccesses",
columns: new[] { "UserId", "SiteId", "CameraId" },
unique: true,
filter: "\"CameraId\" IS NOT NULL");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_UserCameraAccesses",
table: "UserCameraAccesses");
migrationBuilder.DropIndex(
name: "IX_UserCameraAccesses_UserId_SiteId",
table: "UserCameraAccesses");
migrationBuilder.DropIndex(
name: "IX_UserCameraAccesses_UserId_SiteId_CameraId",
table: "UserCameraAccesses");
// Downgrade cannot preserve site-wide grants in the old schema.
// Setting NOT NULL without a default deliberately fails while any
// such grants exist; export/remove them before rolling back.
migrationBuilder.AlterColumn<Guid>(
name: "CameraId",
table: "UserCameraAccesses",
type: "uuid",
nullable: false,
oldClrType: typeof(Guid),
oldType: "uuid",
oldNullable: true);
migrationBuilder.AddPrimaryKey(
name: "PK_UserCameraAccesses",
table: "UserCameraAccesses",
columns: new[] { "UserId", "SiteId", "CameraId" });
}
}
}
@@ -2018,30 +2018,39 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b =>
{
b.Property<Guid>("UserId")
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("SiteId")
.HasColumnType("uuid");
b.Property<Guid>("CameraId")
b.Property<Guid?>("CameraId")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("Id")
b.Property<Guid>("SiteId")
.HasColumnType("uuid");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("UserId", "SiteId", "CameraId");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("CameraId");
b.HasIndex("SiteId");
b.HasIndex("UserId", "SiteId")
.IsUnique()
.HasFilter("\"CameraId\" IS NULL");
b.HasIndex("UserId", "SiteId", "CameraId")
.IsUnique()
.HasFilter("\"CameraId\" IS NOT NULL");
b.ToTable("UserCameraAccesses", (string)null);
});
@@ -98,10 +98,10 @@
</MudSelect>
</MudItem>
<MudItem xs="12" md="6">
<MudSelect @bind-Value="_newAccessSiteId" Label="@Text["CameraAccess_Site"]" Variant="Variant.Outlined" Class="w-100">
<MudSelect T="Guid?" @bind-Value="_newAccessSiteId" Label="@Text["CameraAccess_Site"]" Variant="Variant.Outlined" Class="w-100">
@foreach (var site in _availableSites)
{
<MudSelectItem Value="@site.Id">@site.Name</MudSelectItem>
<MudSelectItem T="Guid?" Value="@((Guid?)site.Id)">@site.Name</MudSelectItem>
}
</MudSelect>
</MudItem>
@@ -109,10 +109,10 @@
@if (_newAccessType == AccessType.CameraSpecific)
{
<MudSelect @bind-Value="_newAccessCameraId" Label="@Text["CameraAccess_Camera"]" Variant="Variant.Outlined" Class="w-100 mb-4">
<MudSelect T="Guid?" @bind-Value="_newAccessCameraId" Label="@Text["CameraAccess_Camera"]" Variant="Variant.Outlined" Class="w-100 mb-4">
@foreach (var camera in _availableCameras)
{
<MudSelectItem Value="@camera.Id">@camera.Name (@GetSiteName(camera.SiteId))</MudSelectItem>
<MudSelectItem T="Guid?" Value="@((Guid?)camera.Id)">@camera.Name (@GetSiteName(camera.SiteId))</MudSelectItem>
}
</MudSelect>
}
+20 -4
View File
@@ -19,6 +19,7 @@ namespace Heimdall.E2E.Tests;
public abstract class E2ETestBase : IAsyncLifetime
{
private readonly string _connectionString;
private string? _externalBaseUrl;
private WebApplication? _app;
private int _port;
private IPage? _page;
@@ -31,7 +32,7 @@ public abstract class E2ETestBase : IAsyncLifetime
}
protected IPage Page => _page ?? throw new InvalidOperationException("Playwright not initialized");
protected string BaseUrl => $"http://127.0.0.1:{_port}";
protected string BaseUrl => _externalBaseUrl ?? $"http://127.0.0.1:{_port}";
protected WebApplication App => _app ?? throw new InvalidOperationException("App not initialized");
/// <summary>Seeded admin account (see Seed:AdminLogin/Seed:AdminPassword in-memory config).</summary>
@@ -72,8 +73,10 @@ public abstract class E2ETestBase : IAsyncLifetime
/// Logs in through the real Blazor UI. Navigates to /login, fills the form,
/// submits, and waits for the redirect to the dashboard.
/// </summary>
protected async Task LoginViaUiAsync(string email = AdminEmail, string password = AdminPassword)
protected async Task LoginViaUiAsync(string? email = null, string? password = null)
{
email ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_EMAIL") ?? AdminEmail;
password ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_PASSWORD") ?? AdminPassword;
await GotoWithCircuitAsync("/login");
await Page.WaitForSelectorAsync("input[autocomplete='email']", new() { Timeout = 15000 });
@@ -82,15 +85,21 @@ public abstract class E2ETestBase : IAsyncLifetime
await Page.ClickAsync("button:has-text('Se connecter')");
// After a successful login the app redirects to /dashboard
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
await Page.WaitForURLAsync("**/dashboard**", new()
{
Timeout = 20000,
WaitUntil = WaitUntilState.Commit
});
}
/// <summary>
/// Returns a JWT access token by calling the REST API directly (no browser).
/// Used by tests that need an authenticated HTTP client (e.g. admin setup).
/// </summary>
protected async Task<string> LoginViaApiAsync(string email = AdminEmail, string password = AdminPassword)
protected async Task<string> LoginViaApiAsync(string? email = null, string? password = null)
{
email ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_EMAIL") ?? AdminEmail;
password ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_PASSWORD") ?? AdminPassword;
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var response = await http.PostAsJsonAsync("/api/auth/login", new { email, password });
response.EnsureSuccessStatusCode();
@@ -102,6 +111,13 @@ public abstract class E2ETestBase : IAsyncLifetime
public virtual async Task InitializeAsync()
{
_externalBaseUrl = Environment.GetEnvironmentVariable("HEIMDALL_E2E_BASE_URL")?.TrimEnd('/');
if (!string.IsNullOrWhiteSpace(_externalBaseUrl))
{
await StartPlaywrightAsync();
return;
}
// Find a free TCP port
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, 0));
@@ -125,6 +125,154 @@ public class UserManagementTests : E2ETestBase
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()
{