Files
Heimdall/tests/Heimdall.Infrastructure.Tests/AgentDiscoveryServiceTests.cs
T
Arnaud Dartoisandnonobis f8f2b08d29 feat(agent): enrichissement ONVIF authentifié côté agent — pool chiffré via config (#49)
## What

L'enrichissement ONVIF authentifié est déplacé côté **agent**. Le pool de credentials du site (login/mdp) est exposé à l'agent via `GET /api/settings/agent/{id}` sous forme d'enveloppe AES-256-GCM (`AgentCredentialEnvelope`, clé dérivée du SHA-256 de l'API key) — déchiffrable uniquement côté agent. `NetworkCameraScanner` tente `GetDeviceInformation` avec chaque couple du pool (PasswordDigest puis PasswordText) et remonte des devices **déjà identifiés** (fabricant/modèle ONVIF + `CredentialLabel`). Le central persiste et marque le credential utilisé (`LastUsedAt`) — plus aucun appel réseau ONVIF côté central.

## Why

Le central n'est généralement **pas** sur le réseau des caméras : les appels ONVIF authentifiés qu'il faisait après réception des devices bruts échouaient. L'agent, lui, est sur le sous-réseau des caméras — c'est lui qui doit porter l'auth. Enrichissement et identification se font au moment du scan, avant la remontée.

## How

- `AgentCredentialEnvelope` (Application/Security) : AES-256-GCM, clé = SHA-256 de l'API key ; central chiffre (via l'`ApiKeyHash` stocké), agent déchiffre (via sa clé en clair).
- `GetEffectiveAgentConfigQuery` : ajoute `discovery.credentials` (pool chiffré) au dict de config.
- `SettingsController.GetEffectiveConfig` : accepte l'API key agent (vérification par site) en plus du JWT admin — corrige au passage un 403 latent sur cet endpoint.
- `NetworkCameraScanner` : probe ONVIF authentifié avec le pool (anonyme d'abord, puis chaque couple).
- `AgentCredentialStore` (mémoire, jamais sur disque) : reçoit le pool déchiffré par `ConfigReceiverService`, lu par `AgentDiscoveryService`.
- `CameraDiscoveryService` : suppression de l'enrichissement réseau ; persistance + `MarkUsed` via `CredentialLabel` ; vendor déduit du fabricant ONVIF remonté.
- `SitesController` : broadcast `ConfigReload` après add/delete credential pour que les agents re-fetch leur pool.
- Multi-agents : inchangé — upsert par (site, IP) et anti-doublon IP/MAC à la confirmation évitent les caméras en double même si un agent est éteint.

## Testing

- `dotnet build Heimdall.slnx` : 0 erreur / 0 warning.
- Application 346 verts, Agent 108 verts, Infrastructure 143 verts (hors Testcontainers).
- Web.Tests 213 verts — nouveaux bUnit : DiscoveriesPage (5) + SiteDetail credentials (4).

## Breaking Changes

Aucun changement de schéma (pas de migration). Comportement API : `GET /api/settings/agent/{id}` accepte désormais l'API key agent (accès élargi au cas d'usage prévu).

Related to #48

Co-authored-by: nonobis <nonobis@tordais.cc>
Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/49
2026-08-11 16:15:41 +02:00

279 lines
12 KiB
C#

using Heimdall.Application.Common;
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 NSubstitute;
using Shouldly;
namespace Heimdall.Infrastructure.Tests;
public class AgentDiscoveryServiceTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly IOnvifProbeService _onvif = Substitute.For<IOnvifProbeService>();
private readonly ICredentialProtector _protector = Substitute.For<ICredentialProtector>();
private readonly ILogger<CameraDiscoveryService> _logger = Substitute.For<ILogger<CameraDiscoveryService>>();
public AgentDiscoveryServiceTests()
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
_dbFactory = CreateFactory(_connection);
_protector.Encrypt(Arg.Any<string>()).Returns(c => $"enc_{c.Arg<string>()}");
_protector.Decrypt(Arg.Any<string>()).Returns(c => (c.Arg<string>() ?? "").Replace("enc_", ""));
}
public void Dispose()
{
_connection?.Close();
_connection?.Dispose();
GC.SuppressFinalize(this);
}
private static TestDbContextFactory CreateFactory(SqliteConnection connection)
{
var opts = new DbContextOptionsBuilder<AppDbContext>()
.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<IMdnsProbeService>(),
Substitute.For<IHttpProbeService>(),
Substitute.For<IArpProbeService>(),
Substitute.For<IPortScanService>(),
new StreamTesterService(Substitute.For<IHttpClientFactory>(), Substitute.For<ILogger<StreamTesterService>>()),
_protector, _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", 80)], 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<string>(), Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
await _onvif.DidNotReceiveWithAnyArgs().ProbeDeviceServiceAsync(
Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
[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", 80), Device("192.168.1.11", 80)], CancellationToken.None);
// Reject one of them
await using (var db = await _dbFactory.CreateDbContextAsync())
{
var first = await db.CameraDiscoveryResults.FirstAsync();
first.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", 80)], 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", 80)], 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<AppDbContext> opts)
: IDbContextFactory<AppDbContext>
{
private static readonly AuditInterceptor Audit = new();
public AppDbContext CreateDbContext() => new(opts, Audit);
public Task<AppDbContext> CreateDbContextAsync(CancellationToken ct = default)
=> Task.FromResult(new AppDbContext(opts, Audit));
}
}