using System.Net.Http.Json; using System.Text.Json; using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Storage; using Heimdall.IntegrationTests.Factories; using Microsoft.Extensions.DependencyInjection; using Shouldly; namespace Heimdall.IntegrationTests.Controllers; public class EventsControllerTests : PostgresTestBase { private HttpClient? _cachedClient; public EventsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } private async Task AdminClient() { if (_cachedClient is not null) return _cachedClient; _cachedClient = await Factory.CreateAdminClientAsync(); return _cachedClient; } [Fact] public async Task CreateEvent_WithoutAuth_ReturnsUnauthorized() { // Events endpoint requires ApiKey auth (agents), not JWT var client = Factory.CreateClient(); var response = await client.PostAsJsonAsync("api/events", new { cameraId = Guid.NewGuid(), type = 0, confidence = 0.95 }); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); } [Fact] public async Task GetEventById_RequiresAuth_ReturnsUnauthorized() { var client = Factory.CreateClient(); var response = await client.GetAsync($"api/events/{Guid.NewGuid()}"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); } [Fact] public async Task QueryEvents_RequiresAuth_ReturnsUnauthorized() { var client = Factory.CreateClient(); var response = await client.GetAsync("api/events"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); } [Fact] public async Task GetEventById_UnknownId_ReturnsForbidden() { var client = await AdminClient(); var response = await client.GetAsync($"api/events/{Guid.NewGuid()}"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden); } [Fact] public async Task QueryEvents_NoFilters_ReturnsOk() { var client = await AdminClient(); var response = await client.GetAsync("api/events?page=1&pageSize=10"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var content = await response.Content.ReadFromJsonAsync(); content.GetProperty("items").GetArrayLength().ShouldBe(0); content.GetProperty("totalCount").GetInt32().ShouldBe(0); } [Fact] public async Task QuerySnapshots_SearchesCameraNameAndFiltersBeforePagination_OnPostgres() { var client = await AdminClient(); var site = new Site($"Gallery {Guid.NewGuid():N}"); var matchingCamera = new Camera(site.Id, "North Gate"); var otherCamera = new Camera(site.Id, "South Hall"); var now = DateTime.UtcNow; var newestSnapshot = Snapshot(matchingCamera.Id, now.AddMinutes(-3), "North newest", hasSnapshot: true); var noSnapshot = Snapshot(matchingCamera.Id, now.AddMinutes(-2), "North no image", hasSnapshot: false); var otherCameraSnapshot = Snapshot(otherCamera.Id, now.AddMinutes(-1), "South image", hasSnapshot: true); var secondSnapshot = Snapshot(matchingCamera.Id, now.AddMinutes(-4), "North second", hasSnapshot: true); await using (var scope = Factory.Services.CreateAsyncScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.Sites.Add(site); db.Cameras.AddRange(matchingCamera, otherCamera); db.CameraEvents.AddRange(newestSnapshot, noSnapshot, otherCameraSnapshot, secondSnapshot); await db.SaveChangesAsync(); } var response = await client.GetAsync("api/events?q=gAtE&hasSnapshot=true&page=2&pageSize=1"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var content = await response.Content.ReadFromJsonAsync(); content.GetProperty("totalCount").GetInt32().ShouldBe(2); content.GetProperty("page").GetInt32().ShouldBe(2); content.GetProperty("pageSize").GetInt32().ShouldBe(1); var items = content.GetProperty("items"); items.GetArrayLength().ShouldBe(1); items[0].GetProperty("label").GetString().ShouldBe("North second"); } [Fact] public async Task StoredSnapshot_IsReadFromCapturedLocation_OnlyWithCameraAccess() { var directory = Path.Combine(Path.GetTempPath(), $"heimdall-event-snapshot-{Guid.NewGuid():N}"); try { var site = new Site($"Snapshot {Guid.NewGuid():N}"); var camera = new Camera(site.Id, "Stored JPEG"); var ev = new CameraEvent(camera.Id, EventType.PersonDetected, 0.9); var location = new StorageLocation(StorageProvider.Local, LocalRoot: directory); var key = $"snapshots/{camera.Id:D}/{ev.Id:D}.jpg"; ev.SetStoredSnapshot(key, location); var bytes = new byte[] { 0xff, 0xd8, 0xff, 0xd9 }; await using (var scope = Factory.Services.CreateAsyncScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.Sites.Add(site); db.Cameras.Add(camera); db.CameraEvents.Add(ev); await db.SaveChangesAsync(); var storage = scope.ServiceProvider.GetRequiredService(); await using var content = new MemoryStream(bytes); await storage.UploadAsync(key, content, "image/jpeg", location); } var anonymous = await Factory.CreateClient().GetAsync($"api/events/{ev.Id:D}/snapshot/content"); anonymous.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); var response = await (await AdminClient()).GetAsync($"api/events/{ev.Id:D}/snapshot/content"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); (response.Content.Headers.ContentType?.MediaType).ShouldBe("image/jpeg"); (await response.Content.ReadAsByteArrayAsync()).ShouldBe(bytes); } finally { if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); } } private static CameraEvent Snapshot(Guid cameraId, DateTime occurredAt, string label, bool hasSnapshot) { var cameraEvent = new CameraEvent(cameraId, EventType.PersonDetected, 0.9, occurredAt); cameraEvent.SetMetadata(label, null); if (hasSnapshot) cameraEvent.SetSnapshot($"snapshots/{label}.jpg"); return cameraEvent; } [Fact] public async Task GetRecentByCamera_UnknownCamera_ReturnsForbidden() { var client = await AdminClient(); var response = await client.GetAsync($"api/events/camera/{Guid.NewGuid()}"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden); } }