using Heimdall.Application.Common; using Heimdall.Application.Discovery; using Heimdall.Application.DTOs; using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Data.Interceptors; using Heimdall.Infrastructure.Services; using Heimdall.Infrastructure.Services.Discovery; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; using Shouldly; namespace Heimdall.Infrastructure.Tests; public class AgentDiscoveryServiceTests : IDisposable { private readonly SqliteConnection _connection; private readonly IDbContextFactory _dbFactory; private readonly IOnvifProbeService _onvif = Substitute.For(); private readonly ICredentialProtector _protector = Substitute.For(); private readonly ILogger _logger = Substitute.For>(); public AgentDiscoveryServiceTests() { _connection = new SqliteConnection("DataSource=:memory:"); _connection.Open(); _dbFactory = CreateFactory(_connection); _protector.Encrypt(Arg.Any()).Returns(c => $"enc_{c.Arg()}"); _protector.Decrypt(Arg.Any()).Returns(c => (c.Arg() ?? "").Replace("enc_", "")); } public void Dispose() { _connection?.Close(); _connection?.Dispose(); GC.SuppressFinalize(this); } private static TestDbContextFactory CreateFactory(SqliteConnection connection) { var opts = new DbContextOptionsBuilder() .UseSqlite(connection) .Options; using var ctx = new AppDbContext(opts, new AuditInterceptor()); ctx.Database.EnsureCreated(); return new TestDbContextFactory(opts); } private CameraDiscoveryService CreateService() => new( _dbFactory, _onvif, Substitute.For(), Substitute.For(), Substitute.For(), Substitute.For(), new StreamTesterService(Substitute.For(), Substitute.For>()), _protector, new SqliteCameraDatabase(NullLogger.Instance), _logger); private async Task<(Guid SiteId, Guid AgentId)> SeedSiteAndAgentAsync(string siteName = "Site A") { await using var db = await _dbFactory.CreateDbContextAsync(); var site = new Site(siteName); var agent = new Agent(site.Id, "Agent 1", "host1", "1.0.0"); db.Sites.Add(site); db.Agents.Add(agent); await db.SaveChangesAsync(); return (site.Id, agent.Id); } private static AgentDiscoveredDevice Device(string ip, params int[] ports) => new( ip, true, ports, "AA:BB:CC:DD:EE:FF", null, null, null, null, null, null, null, null, ports.Contains(3702) ? 3702 : null, null, null, null); // ─── Submit ──────────────────────────────────────────────────── [Fact] public async Task Submit_new_devices_should_create_discovery_results() { var (siteId, agentId) = await SeedSiteAndAgentAsync(); var service = CreateService(); var result = await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80, 554)], CancellationToken.None); result.IsSuccess.ShouldBeTrue(); result.Data.ShouldNotBeNull(); result.Data.Received.ShouldBe(1); result.Data.New.ShouldBe(1); result.Data.Updated.ShouldBe(0); await using var db = await _dbFactory.CreateDbContextAsync(); var saved = await db.CameraDiscoveryResults.SingleAsync(); saved.ShouldNotBeNull(); saved.SiteId.ShouldBe(siteId); saved.IpAddress.ShouldBe("192.168.1.10"); saved.MacAddress.ShouldBe("AA:BB:CC:DD:EE:FF"); saved.IsProcessed.ShouldBeFalse(); saved.OpenPorts.ShouldBe([80, 554]); } [Fact] public async Task Submit_same_ip_should_update_not_duplicate() { var (_, agentId) = await SeedSiteAndAgentAsync(); var service = CreateService(); await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 554)], CancellationToken.None); var result = await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80, 554)], CancellationToken.None); result.Data.ShouldNotBeNull(); result.Data.New.ShouldBe(0); result.Data.Updated.ShouldBe(1); await using var db = await _dbFactory.CreateDbContextAsync(); db.CameraDiscoveryResults.Count().ShouldBe(1); var savedAgain = await db.CameraDiscoveryResults.SingleAsync(); savedAgain.ShouldNotBeNull(); savedAgain.OpenPorts.ShouldBe([80, 554]); } [Fact] public async Task Submit_unknown_agent_should_not_found() { var service = CreateService(); var result = await service.SubmitAgentDiscoveriesAsync(Guid.NewGuid(), [Device("192.168.1.10", 80)], CancellationToken.None); result.IsSuccess.ShouldBeFalse(); result.StatusCode.ShouldBe(404); } [Fact] public async Task Submit_should_persist_agent_enriched_onvif_and_mark_credential_used() { var (siteId, agentId) = await SeedSiteAndAgentAsync(); await using (var seedDb = await _dbFactory.CreateDbContextAsync()) { seedDb.SiteCredentials.Add(new SiteCredential(siteId, "admin", "admin", _protector.Encrypt("secret"))); await seedDb.SaveChangesAsync(); } var service = CreateService(); // The agent is on the camera network: it already performed the authenticated // ONVIF enrichment (OnvifName = manufacturer, OnvifHardware = model) and // reports which credential label succeeded. The Central only persists. var device = new AgentDiscoveredDevice( "192.168.1.10", true, [3702], "3C:EF:8C:12:34:56", null, null, null, null, null, "http://192.168.1.10/onvif/device_service", "Hikvision", "DS-2CD2T47", 3702, null, null, null, CredentialLabel: "admin"); await service.SubmitAgentDiscoveriesAsync(agentId, [device], CancellationToken.None); await using var db = await _dbFactory.CreateDbContextAsync(); var saved = await db.CameraDiscoveryResults.Include(r => r.DiscoveredStreams).SingleAsync(); saved.OnvifHardware.ShouldBe("DS-2CD2T47"); saved.OnvifName.ShouldBe("Hikvision"); saved.Vendor.ShouldBe("hikvision"); // normalisé depuis le fabricant ONVIF remonté par l'agent saved.OnvifDeviceServiceUrl.ShouldBe("http://192.168.1.10/onvif/device_service"); saved.DiscoveredStreams.Count.ShouldBeGreaterThan(0); var cred = await db.SiteCredentials.SingleAsync(); cred.LastUsedAt.ShouldNotBeNull(); // marqué via CredentialLabel remonté par l'agent } [Fact] public async Task Submit_should_not_call_onvif_probe_on_central() { // The Central is not on the camera network: it must never probe ONVIF // itself for agent-submitted devices (authenticated enrichment is the // agent's job). Persisting raw data without enrichment must not throw. var (_, agentId) = await SeedSiteAndAgentAsync(); var service = CreateService(); var device = Device("192.168.1.10", 3702); var result = await service.SubmitAgentDiscoveriesAsync(agentId, [device], CancellationToken.None); result.IsSuccess.ShouldBeTrue(); await _onvif.DidNotReceiveWithAnyArgs().ProbeWithCredentialsAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _onvif.DidNotReceiveWithAnyArgs().ProbeDeviceServiceAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] public async Task Submit_should_build_candidate_stream_urls() { var (_, agentId) = await SeedSiteAndAgentAsync(); var service = CreateService(); await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.20", 554)], CancellationToken.None); await using var db = await _dbFactory.CreateDbContextAsync(); var saved = await db.CameraDiscoveryResults.Include(r => r.DiscoveredStreams).SingleAsync(); saved.DiscoveredStreams.Select(s => s.Url).ShouldContain(u => u.Contains("192.168.1.20")); } // ─── List pending ───────────────────────────────────────────── [Fact] public async Task List_pending_should_return_only_unprocessed_results() { var (siteId, agentId) = await SeedSiteAndAgentAsync(); var service = CreateService(); await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 554), Device("192.168.1.11", 554)], CancellationToken.None); // Reject one of them — target the exact IP so the assertion below is // deterministic (FirstAsync() without ORDER BY is not stable across // providers: SQLite local vs PostgreSQL CI). await using (var db = await _dbFactory.CreateDbContextAsync()) { var toReject = await db.CameraDiscoveryResults.FirstAsync(r => r.IpAddress == "192.168.1.10"); toReject.MarkProcessed(); await db.SaveChangesAsync(); } var result = await service.ListPendingDiscoveriesAsync(siteId, CancellationToken.None); result.IsSuccess.ShouldBeTrue(); result.Data.ShouldNotBeNull(); result.Data.Count.ShouldBe(1); result.Data[0].IpAddress.ShouldBe("192.168.1.11"); result.Data.ShouldNotContain(d => d.IpAddress == "192.168.1.10"); } [Fact] public async Task List_pending_unknown_site_returns_empty() { var service = CreateService(); var result = await service.ListPendingDiscoveriesAsync(Guid.NewGuid(), CancellationToken.None); result.IsSuccess.ShouldBeTrue(); result.Data.ShouldBeEmpty(); } // ─── Reject ─────────────────────────────────────────────────── [Fact] public async Task Reject_should_mark_result_processed() { var (_, agentId) = await SeedSiteAndAgentAsync(); var service = CreateService(); await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 554)], CancellationToken.None); await using (var db = await _dbFactory.CreateDbContextAsync()) { var saved = await db.CameraDiscoveryResults.SingleAsync(); var result = await service.RejectDiscoveryAsync(saved.Id, CancellationToken.None); result.IsSuccess.ShouldBeTrue(); } await using var db2 = await _dbFactory.CreateDbContextAsync(); (await db2.CameraDiscoveryResults.SingleAsync()).IsProcessed.ShouldBeTrue(); } [Fact] public async Task Reject_already_processed_should_not_found() { var (_, agentId) = await SeedSiteAndAgentAsync(); var service = CreateService(); await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 554)], CancellationToken.None); await using (var db = await _dbFactory.CreateDbContextAsync()) { var saved = await db.CameraDiscoveryResults.SingleAsync(); saved.ShouldNotBeNull(); await service.RejectDiscoveryAsync(saved.Id, CancellationToken.None); var result = await service.RejectDiscoveryAsync(saved.Id, CancellationToken.None); result.IsSuccess.ShouldBeFalse(); result.StatusCode.ShouldBe(404); } } private sealed class TestDbContextFactory(DbContextOptions opts) : IDbContextFactory { private static readonly AuditInterceptor Audit = new(); public AppDbContext CreateDbContext() => new(opts, Audit); public Task CreateDbContextAsync(CancellationToken ct = default) => Task.FromResult(new AppDbContext(opts, Audit)); } }