using System.Globalization; 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() ?? string.Empty) .ShouldContain((initialUnread + 1).ToString(CultureInfo.InvariantCulture)); 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 static 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 static 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; } }