diff --git a/src/Heimdall.Web/Hubs/NotificationsHub.cs b/src/Heimdall.Web/Hubs/NotificationsHub.cs index f546c1c..415edee 100644 --- a/src/Heimdall.Web/Hubs/NotificationsHub.cs +++ b/src/Heimdall.Web/Hubs/NotificationsHub.cs @@ -20,9 +20,16 @@ public class NotificationsHub : Hub private readonly ILogger _logger; private readonly ResourceAccess _access; private readonly LiveSubscriptions _subscriptions; + private readonly INotificationService _notifications; - public NotificationsHub(ILogger logger, ResourceAccess access, LiveSubscriptions subscriptions) - { _logger = logger; _access = access; _subscriptions = subscriptions; } + public NotificationsHub(ILogger logger, ResourceAccess access, + LiveSubscriptions subscriptions, INotificationService notifications) + { + _logger = logger; + _access = access; + _subscriptions = subscriptions; + _notifications = notifications; + } /// /// Clients call this to join their personal notification channel. @@ -36,6 +43,8 @@ public class NotificationsHub : Hub var userId = requester.Id.ToString(); _subscriptions.Join("notifications", Context.ConnectionId, userId, Context.User!); _logger.LogDebug("Client {ConnectionId} joined personal notifications for user {UserId}", Context.ConnectionId, userId); + var unreadCount = await _notifications.GetUnreadCountAsync(requester.Id, Context.ConnectionAborted); + await Clients.Caller.SendAsync("UnreadCount", new { count = unreadCount }, Context.ConnectionAborted); } public Task LeavePersonalNotifications() diff --git a/src/Heimdall.Web/Services/NotificationsHubClient.cs b/src/Heimdall.Web/Services/NotificationsHubClient.cs index fef44e2..b610c65 100644 --- a/src/Heimdall.Web/Services/NotificationsHubClient.cs +++ b/src/Heimdall.Web/Services/NotificationsHubClient.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.SignalR.Client; @@ -52,18 +53,18 @@ public class NotificationsHubClient : IAsyncDisposable, IDisposable .WithAutomaticReconnect() .Build(); - _connection.On("UnreadCount", (payload) => + _connection.On("UnreadCount", (payload) => { - try + if (payload.ValueKind != JsonValueKind.Object || + !payload.TryGetProperty("count", out var countElement) || + !countElement.TryGetInt32(out var count) || count < 0) { - var count = (int)((IDictionary)payload)["count"]; - UnreadCount = count; - UnreadCountChanged?.Invoke(count); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "NotificationsHubClient: UnreadCount payload inattendu"); + _logger.LogWarning("NotificationsHubClient: unread count payload inattendu"); + return; } + + UnreadCount = count; + UnreadCountChanged?.Invoke(count); }); _connection.On("NewNotification", (_) => diff --git a/tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs b/tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs new file mode 100644 index 0000000..4894ca6 --- /dev/null +++ b/tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs @@ -0,0 +1,229 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Heimdall.TestCommon; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Playwright; +using Shouldly; + +namespace Heimdall.E2E.Tests.Pages; + +public sealed class DetectionFlowTests(PostgreSqlContainerFixture postgres) : E2ETestBase(postgres) +{ + private const string SnapshotJpegBase64 = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAgADADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAb/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCCAWkoAAAAAAAAAB//2Q=="; + + [Fact] + public async Task Assigned_agent_event_is_stored_notified_and_visible_only_with_camera_access() + { + var storageRoot = Path.Combine(Path.GetTempPath(), $"heimdall-e2e-storage-{Guid.NewGuid():N}"); + var admin = new HttpClient { BaseAddress = new Uri(BaseUrl) }; + admin.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await LoginViaApiAsync()); + string? originalStoragePath = null; + string? originalStorageProvider = null; + + try + { + var storedPath = await admin.GetAsync("api/settings/storage.local.path"); + storedPath.StatusCode.ShouldBe(HttpStatusCode.OK); + var setting = await storedPath.Content.ReadFromJsonAsync(); + originalStoragePath = setting.GetProperty("value").GetString(); + var providerResponse = await admin.GetAsync("api/settings/storage.provider"); + providerResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var providerSetting = await providerResponse.Content.ReadFromJsonAsync(); + originalStorageProvider = providerSetting.GetProperty("value").GetString(); + (await admin.PutAsJsonAsync("api/settings/storage.provider", new { value = "Local" })) + .StatusCode.ShouldBe(HttpStatusCode.OK); + (await admin.PutAsJsonAsync("api/settings/storage.local.path", new { value = storageRoot })) + .StatusCode.ShouldBe(HttpStatusCode.OK); + var initialUnreadResponse = await admin.GetAsync("api/notifications/unread-count"); + initialUnreadResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var initialUnread = (await initialUnreadResponse.Content.ReadFromJsonAsync()) + .GetProperty("count").GetInt32(); + + var siteId = await CreateSiteAsync(admin, "QA source"); + var otherSiteId = await CreateSiteAsync(admin, "QA other"); + var agent = await RegisterOnlineAgentAsync(admin, siteId); + var assignedCameraId = await CreateCameraAsync(admin, siteId, "QA assigned camera"); + var otherCameraId = await CreateCameraAsync(admin, otherSiteId, "QA other-site camera"); + (await admin.PostAsJsonAsync("api/assignments", new { cameraId = assignedCameraId, agentId = agent.Id })) + .StatusCode.ShouldBe(HttpStatusCode.OK); + + var viewerEmail = $"qa-flow-{Guid.NewGuid():N}@heimdall.test"; + const string viewerPassword = "QaFlowViewer123!"; + var userResponse = await admin.PostAsJsonAsync("api/users", new + { + email = viewerEmail, + password = viewerPassword, + displayName = "QA Flow Viewer", + roles = new[] { "Viewer" } + }); + userResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var viewerUserId = (await userResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + await ConfirmUserAsync(viewerEmail); + using var viewer = new HttpClient { BaseAddress = new Uri(BaseUrl) }; + viewer.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( + "Bearer", await LoginViaApiAsync(viewerEmail, viewerPassword)); + + (await viewer.GetAsync($"api/cameras/{assignedCameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + (await viewer.GetAsync($"api/cameras/{otherCameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + var grant = await admin.PostAsJsonAsync("api/user-camera-access", new + { + userId = viewerUserId, + siteId, + cameraId = assignedCameraId + }); + grant.StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/cameras/{assignedCameraId}")).StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/cameras/{otherCameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + + using var agentClient = AgentClient(agent.ApiKey); + var occurredAt = DateTime.UtcNow; + var eventId = Guid.NewGuid(); + var label = $"qa-flow-{Guid.NewGuid():N}"; + var eventRequest = new + { + cameraId = assignedCameraId, + type = (int)EventType.PersonDetected, + confidence = 0.97, + label, + occurredAt, + eventId + }; + (await agentClient.PostAsJsonAsync("api/events", new + { + cameraId = otherCameraId, + type = (int)EventType.PersonDetected, + confidence = 0.9, + label = "wrong-site" + })).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + + var createdEvent = await agentClient.PostAsJsonAsync("api/events", eventRequest); + createdEvent.StatusCode.ShouldBe(HttpStatusCode.OK); + var eventResponse = await createdEvent.Content.ReadFromJsonAsync(); + eventResponse.GetProperty("id").GetGuid().ShouldBe(eventId); + + // The agent outbox may retry an accepted event. Its deterministic ID must + // preserve a single event and a single in-app notification per recipient. + (await agentClient.PostAsJsonAsync("api/events", eventRequest)).StatusCode.ShouldBe(HttpStatusCode.OK); + + using var image = new ByteArrayContent(Convert.FromBase64String(SnapshotJpegBase64)); + image.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); + var uploaded = await agentClient.PutAsync($"api/events/{eventId:D}/snapshot/content", image); + uploaded.StatusCode.ShouldBe(HttpStatusCode.OK); + + foreach (var client in new[] { admin, viewer }) + { + var notificationsResponse = await client.GetAsync("api/notifications?isRead=false&page=1&pageSize=100"); + notificationsResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var notifications = await notificationsResponse.Content.ReadFromJsonAsync(); + var matchingNotifications = notifications.GetProperty("items").EnumerateArray() + .Where(item => item.GetProperty("cameraId").GetGuid() == assignedCameraId) + .ToArray(); + matchingNotifications.Length.ShouldBe(1); + matchingNotifications[0].GetProperty("eventType").GetString().ShouldBe(nameof(EventType.PersonDetected)); + } + + (await viewer.GetAsync($"api/events/{eventId:D}")).StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/events/{eventId:D}/snapshot/content")).StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/events/{Guid.NewGuid():D}/snapshot/content")).StatusCode + .ShouldBe(HttpStatusCode.Forbidden); + + await LoginViaUiAsync(); + await Page.Locator(".mud-badge").WaitForAsync(new() { Timeout = 15000 }); + (await Page.Locator(".mud-badge").First.TextContentAsync()).ShouldContain((initialUnread + 1).ToString()); + await GotoWithCircuitAsync("/events"); + await Page.GetByText(label, new() { Exact = true }).WaitForAsync(new() { Timeout = 15000 }); + } + finally + { + if (originalStorageProvider is not null) + { + try + { + var restore = await admin.PutAsJsonAsync("api/settings/storage.provider", + new { value = originalStorageProvider }); + restore.Dispose(); + } + catch { /* Keep test cleanup from hiding the original failure. */ } + } + if (originalStoragePath is not null) + { + try + { + var restore = await admin.PutAsJsonAsync("api/settings/storage.local.path", + new { value = originalStoragePath }); + restore.Dispose(); + } + catch { /* Keep test cleanup from hiding the original failure. */ } + } + admin.Dispose(); + if (Directory.Exists(storageRoot)) Directory.Delete(storageRoot, recursive: true); + } + } + + private async Task CreateSiteAsync(HttpClient admin, string name) + { + var response = await admin.PostAsJsonAsync("api/sites", new { name = $"{name} {Guid.NewGuid():N}", timezone = "UTC" }); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + return (await response.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + } + + private async Task CreateCameraAsync(HttpClient admin, Guid siteId, string name) + { + var response = await admin.PostAsJsonAsync("api/cameras", new + { + siteId, + name, + rtspUrl = $"rtsp://127.0.0.1/{Guid.NewGuid():N}" + }); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + return (await response.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + } + + private async Task<(Guid Id, string ApiKey)> RegisterOnlineAgentAsync(HttpClient admin, Guid siteId) + { + var tokenResponse = await admin.PostAsync($"api/sites/{siteId}/tokens", null); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var token = (await tokenResponse.Content.ReadFromJsonAsync()).GetProperty("token").GetString()!; + var registration = await admin.PostAsJsonAsync("api/agents/register", new + { + token, + hostname = $"qa-flow-agent-{Guid.NewGuid():N}", + version = "1.0.0-test" + }); + registration.StatusCode.ShouldBe(HttpStatusCode.OK); + var agent = await registration.Content.ReadFromJsonAsync(); + var id = agent.GetProperty("agentId").GetGuid(); + var apiKey = agent.GetProperty("apiKey").GetString()!; + using var agentClient = AgentClient(apiKey); + var heartbeat = await agentClient.PostAsJsonAsync($"api/agents/{id:D}/heartbeat", new + { + publicIp = "127.0.0.1", + cpuCores = 4, + memoryMb = 4096 + }); + heartbeat.StatusCode.ShouldBe(HttpStatusCode.OK); + return (id, apiKey); + } + + private async Task ConfirmUserAsync(string email) + { + await using var scope = App.Services.CreateAsyncScope(); + var dbFactory = scope.ServiceProvider.GetRequiredService>(); + await using var db = await dbFactory.CreateDbContextAsync(); + var user = await db.Users.SingleAsync(candidate => candidate.Email == email); + user.EmailConfirmed = true; + await db.SaveChangesAsync(); + } + + private HttpClient AgentClient(string apiKey) + { + var client = new HttpClient { BaseAddress = new Uri(BaseUrl) }; + client.DefaultRequestHeaders.Add("X-API-Key", apiKey); + return client; + } +} diff --git a/todo.md b/todo.md index 68a392a..ce6e62a 100644 --- a/todo.md +++ b/todo.md @@ -30,7 +30,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif. - [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage. - [ ] **Accès caméra #141** La PR #65 ajoute les scénarios API de grant caméra direct, refus cross-camera, suppression logique et restrictions des routes groupes, ainsi que les tests du filtre d’affectations et des hubs après suppression logique ; sa CI est passée. La PR #88 ajoute le remplacement UI atomique, le chargement complet paginé, la protection du brouillon, et la révocation individuelle des accès excédant la limite de 500. La PR #100 ajoute un gate CI strict (>80 % de lignes par classe ciblée) et étend les tests Application, Infrastructure et Web. Le run PR #319 a mesuré : `CameraAccessService` 100 %, `ResourceAccess` 88,46 %, `ResourceAccessFilter` 82,54 %, `UserCameraAccessController` 83,33 % ; handlers/queries/mapping Application de 90 % à 100 %. Restent la validation produit des accès directs/groupes (#133/#134). -- [ ] **QA-01** Ajouter scénarios transversaux API → Agent → stockage → événement → UI → notification, dont périmètres de site et droits caméra ; mesurer couverture utile sans compter les tests ignorés comme succès. +- [ ] **QA-01** Un parcours E2E Playwright est en préparation : Agent enregistré simulé, événement et reprise idempotente, snapshot dans un stockage local temporaire, notification persistée, droit caméra accordé/refusé selon le périmètre, puis affichage de l’événement et du compteur initial dans l’UI. La PR qui ajoute ce scénario et le chargement du compteur à la connexion du hub doit encore passer la CI ; ses sorties distinguent les tests ignorés des tests réussis. - [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. ## P2 — fonctionnalités et exploitation