Files
Heimdall/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.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

226 lines
8.4 KiB
C#

using System.Reflection;
using Heimdall.Agent.Services;
using Heimdall.Application.DTOs;
using Heimdall.Application.Security;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
namespace Heimdall.Agent.Tests;
public class ConfigReceiverServiceTests
{
private static ConfigReceiverService CreateService(AgentState? state = null, AgentCredentialStore? store = null)
{
state ??= new AgentState { AgentId = Guid.Empty };
var options = Options.Create(new AgentOptions
{
CentralUrl = "http://localhost:5000",
SiteToken = "test"
});
var logger = Substitute.For<ILogger<ConfigReceiverService>>();
var httpFactory = Substitute.For<IHttpClientFactory>();
var scanTrigger = new DiscoveryScanTrigger();
return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore());
}
[Fact]
public void Constructor_WithDependencies_DoesNotThrow()
{
var service = CreateService();
service.ShouldNotBeNull();
}
[Fact]
public async Task StartStop_WhenNotRegistered_StopsGracefully()
{
var state = new AgentState { AgentId = Guid.Empty };
var service = CreateService(state);
await service.StartAsync(CancellationToken.None);
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
await service.StopAsync(cts.Token);
}
[Fact]
public async Task StartStop_WhenRegistered_StopsGracefully()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
await service.StartAsync(CancellationToken.None);
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await service.StopAsync(cts.Token);
}
[Fact]
public async Task StopAsync_WithoutStart_DoesNotThrow()
{
var service = CreateService();
await service.StopAsync(CancellationToken.None);
}
[Fact]
public async Task ExecuteAsync_CancelledWhileWaitingForAgentId_StopsGracefully()
{
var state = new AgentState { AgentId = Guid.Empty };
var service = CreateService(state);
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
await service.StartAsync(cts.Token);
await service.StopAsync(CancellationToken.None);
}
[Fact]
public async Task ExecuteAsync_ConnectionRetriesThenCancels_StopsGracefully()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
await service.StartAsync(cts.Token);
await service.StopAsync(CancellationToken.None);
}
[Fact]
public void ApplySetting_InvalidHeartbeatValue_DoesNotThrow()
{
var service = CreateService();
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// Below minimum threshold (5)
Record.Exception(() => method.Invoke(service, ["heartbeat.interval.seconds", "3"]))
.ShouldBeNull();
// Non-numeric value
Record.Exception(() => method.Invoke(service, ["heartbeat.interval.seconds", "not-a-number"]))
.ShouldBeNull();
}
[Fact]
public void ApplySetting_KnownAndUnknownKeys_DoesNotThrow()
{
var service = CreateService();
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
Record.Exception(() => method.Invoke(service, ["log.level", "Debug"]))
.ShouldBeNull();
Record.Exception(() => method.Invoke(service, ["unknown.key", "some-value"]))
.ShouldBeNull();
}
[Fact]
public void ApplySetting_ValidHeartbeatInterval_DoesNotThrow()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
Record.Exception(() => method.Invoke(service, ["heartbeat.interval.seconds", "30"]))
.ShouldBeNull();
// The setting is applied live to the shared state
state.HeartbeatIntervalSeconds.ShouldBe(30);
}
[Fact]
public void ApplySetting_ScanRequested_DoesNotThrow()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// Scan request is fire-and-forget (triggered via DiscoveryScanTrigger)
Record.Exception(() => method.Invoke(service, ["discovery.scan.requested", "1"]))
.ShouldBeNull();
}
[Fact]
public void ApplySetting_CredentialPool_DecryptsAndStores()
{
const string apiKey = "test-agent-api-key";
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = apiKey };
var store = new AgentCredentialStore();
var service = CreateService(state, store);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
var key = AgentCredentialEnvelope.DeriveKeyFromApiKey(apiKey);
var envelope = AgentCredentialEnvelope.Encrypt(
[new AgentCameraCredential("admin", "admin", "secret")], key);
Record.Exception(() => method.Invoke(service, ["discovery.credentials", envelope]))
.ShouldBeNull();
store.Pool.Count.ShouldBe(1);
store.Pool[0].Label.ShouldBe("admin");
store.Pool[0].Password.ShouldBe("secret");
}
[Fact]
public void ApplySetting_CredentialPool_WrongKey_KeepsPreviousPool()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "real-key" };
var store = new AgentCredentialStore();
store.Set([new AgentCameraCredential("old", "old", "old")]);
var service = CreateService(state, store);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// Envelope encrypted with a DIFFERENT key than the agent's API key.
var wrongKey = AgentCredentialEnvelope.DeriveKeyFromApiKey("other-key");
var envelope = AgentCredentialEnvelope.Encrypt(
[new AgentCameraCredential("new", "new", "new")], wrongKey);
Record.Exception(() => method.Invoke(service, ["discovery.credentials", envelope]))
.ShouldBeNull();
store.Pool.Count.ShouldBe(1);
store.Pool[0].Label.ShouldBe("old");
}
[Fact]
public void ApplySetting_InvalidHeartbeatInterval_DoesNotMutateState()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// Below minimum (5)
method.Invoke(service, ["heartbeat.interval.seconds", "3"]);
state.HeartbeatIntervalSeconds.ShouldBeNull();
// Above maximum (300)
method.Invoke(service, ["heartbeat.interval.seconds", "999"]);
state.HeartbeatIntervalSeconds.ShouldBeNull();
// Non-numeric
method.Invoke(service, ["heartbeat.interval.seconds", "abc"]);
state.HeartbeatIntervalSeconds.ShouldBeNull();
}
[Fact]
public async Task StartStop_MultipleTimes_DoesNotThrow()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
// First start/stop cycle
await service.StartAsync(CancellationToken.None);
await service.StopAsync(CancellationToken.None);
// Second start/stop cycle
await service.StartAsync(CancellationToken.None);
await service.StopAsync(CancellationToken.None);
}
}