## 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
118 lines
5.2 KiB
C#
118 lines
5.2 KiB
C#
using Heimdall.Application.Common;
|
|
using Heimdall.Application.DTOs;
|
|
using Heimdall.Application.Security;
|
|
using Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig;
|
|
using Heimdall.Application.Tests.Common;
|
|
using Heimdall.Domain.Entities;
|
|
using NSubstitute;
|
|
|
|
namespace Heimdall.Application.Tests.Handlers.Settings;
|
|
|
|
public class GetEffectiveAgentConfigHandlerTests
|
|
{
|
|
private static readonly ICredentialProtector Protector = Substitute.For<ICredentialProtector>();
|
|
private static readonly Guid AgentId = Guid.NewGuid();
|
|
private static readonly Guid SiteId = Guid.NewGuid();
|
|
|
|
// Hex SHA-256 of "test-agent-api-key" — a realistic ApiKeyHash as stored on Agent.
|
|
private static readonly string ApiKeyHash =
|
|
Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(
|
|
System.Text.Encoding.UTF8.GetBytes("test-agent-api-key"))).ToLowerInvariant();
|
|
|
|
private static IApplicationDbContext CreateContext(
|
|
List<AppSetting>? appSettings = null,
|
|
List<AgentSetting>? agentSettings = null,
|
|
List<Agent>? agents = null,
|
|
List<SiteCredential>? credentials = null)
|
|
{
|
|
var context = Substitute.For<IApplicationDbContext>();
|
|
context.AppSettings.Returns(MockDbSetHelper.CreateFor<AppSetting>(appSettings ?? []));
|
|
context.AgentSettings.Returns(MockDbSetHelper.CreateFor<AgentSetting>(agentSettings ?? []));
|
|
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>(agents ?? []));
|
|
context.SiteCredentials.Returns(MockDbSetHelper.CreateFor<SiteCredential>(credentials ?? []));
|
|
|
|
Protector.Encrypt(Arg.Any<string>()).Returns(c => $"enc_{c.Arg<string>()}");
|
|
Protector.Decrypt(Arg.Any<string>()).Returns(c => (c.Arg<string>() ?? "").Replace("enc_", ""));
|
|
return context;
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Get_effective_config_should_merge_app_and_agent_settings()
|
|
{
|
|
var appSettings = new List<AppSetting>
|
|
{
|
|
new("global.key", "global-value", "General"),
|
|
new("shared.key", "app-value", "General"),
|
|
};
|
|
var agentSettings = new List<AgentSetting>
|
|
{
|
|
new(AgentId, "shared.key", "agent-override"),
|
|
new(AgentId, "agent.only", "agent-value"),
|
|
};
|
|
var context = CreateContext(appSettings: appSettings, agentSettings: agentSettings);
|
|
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
|
|
|
|
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(AgentId), CancellationToken.None);
|
|
|
|
result.IsSuccess.ShouldBeTrue();
|
|
result.Data.ShouldNotBeNull();
|
|
result.Data["global.key"].ShouldBe("global-value");
|
|
result.Data["shared.key"].ShouldBe("agent-override");
|
|
result.Data["agent.only"].ShouldBe("agent-value");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Get_effective_config_unknown_agent_should_not_include_credential_pool()
|
|
{
|
|
var context = CreateContext();
|
|
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
|
|
|
|
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(Guid.NewGuid()), CancellationToken.None);
|
|
|
|
result.IsSuccess.ShouldBeTrue();
|
|
result.Data.ShouldNotBeNull();
|
|
result.Data!.ShouldNotContainKey("discovery.credentials");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Get_effective_config_agent_with_pool_should_ship_encrypted_credentials()
|
|
{
|
|
var agent = new Agent(SiteId, "agent-1", "host1", "1.0.0");
|
|
agent.Register(ApiKeyHash, ApiKeyHash[..8]);
|
|
var credentials = new List<SiteCredential>
|
|
{
|
|
new(SiteId, "admin principal", "admin", Protector.Encrypt("secret-1")),
|
|
new(SiteId, "compte NVR", "nvr", Protector.Encrypt("secret-2")),
|
|
};
|
|
var context = CreateContext(agents: [agent], credentials: credentials);
|
|
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
|
|
|
|
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agent.Id), CancellationToken.None);
|
|
|
|
result.IsSuccess.ShouldBeTrue();
|
|
result.Data.ShouldNotBeNull();
|
|
result.Data.ShouldContainKey("discovery.credentials");
|
|
|
|
// The envelope must decrypt only with the agent's key and reveal the pairs.
|
|
var key = AgentCredentialEnvelope.DeriveKeyFromApiKeyHash(ApiKeyHash);
|
|
var pool = AgentCredentialEnvelope.Decrypt(result.Data["discovery.credentials"], key);
|
|
pool.Count.ShouldBe(2);
|
|
pool.ShouldContain(c => c.Label == "admin principal" && c.Username == "admin" && c.Password == "secret-1");
|
|
pool.ShouldContain(c => c.Label == "compte NVR" && c.Username == "nvr" && c.Password == "secret-2");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Get_effective_config_agent_without_api_key_hash_should_not_ship_pool()
|
|
{
|
|
var agent = new Agent(SiteId, "agent-1", "host1", "1.0.0"); // never registered → no ApiKeyHash
|
|
var context = CreateContext(agents: [agent]);
|
|
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
|
|
|
|
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agent.Id), CancellationToken.None);
|
|
|
|
result.IsSuccess.ShouldBeTrue();
|
|
result.Data.ShouldNotBeNull();
|
|
result.Data!.ShouldNotContainKey("discovery.credentials");
|
|
}
|
|
}
|