Files
Heimdall/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs
T

197 lines
8.8 KiB
C#
Raw Normal View History

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 Heimdall.Domain.Enums;
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<Site>? sites = null,
List<SiteCredential>? credentials = null,
List<Camera>? cameras = 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.Sites.Returns(MockDbSetHelper.CreateFor<Site>(sites ?? []));
context.SiteCredentials.Returns(MockDbSetHelper.CreateFor<SiteCredential>(credentials ?? []));
context.Cameras.Returns(MockDbSetHelper.CreateFor<Camera>(cameras ?? []));
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_apply_site_update_override_after_global_and_ignore_agent_override()
{
var site = new Site("site");
site.SetAutoUpdate(true);
var agent = new Agent(site.Id, "agent-1", "host1", "1.0.0");
var appSettings = new List<AppSetting> { new("autoupdateenabled", "false") };
var agentSettings = new List<AgentSetting> { new(agent.Id, "autoupdateenabled", "false") };
var context = CreateContext(appSettings: appSettings, agentSettings: agentSettings,
agents: [agent], sites: [site]);
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agent.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!["autoupdateenabled"].ShouldBe("true");
}
[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.ShouldNotContainKey("agent.only");
}
[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");
}
[Fact]
public async Task Get_effective_config_should_ship_assigned_cameras()
{
var agent = new Agent(SiteId, "agent-1", "host1", "1.0.0");
agent.Register(ApiKeyHash, ApiKeyHash[..8]);
var camera = new Camera(SiteId, "Entrée", "rtsp://camera/stream1");
camera.AssignAgent(agent.Id);
camera.SetStatus(CameraStatus.Online);
camera.SetStreamTestResult("rtsp://camera/sub", "[]", 1920, 1080, 120);
var otherCamera = new Camera(SiteId, "Autre agent", "rtsp://other/stream");
otherCamera.AssignAgent(Guid.NewGuid());
var deletedCamera = new Camera(SiteId, "Supprimée", "rtsp://deleted/stream");
deletedCamera.AssignAgent(agent.Id);
deletedCamera.SoftDelete();
var context = CreateContext(agents: [agent], cameras: [camera, otherCamera, deletedCamera]);
var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector);
var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agent.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
var prefix = $"camera.{camera.Id}";
result.Data[prefix + ".name"].ShouldBe("Entrée");
result.Data[prefix + ".rtsp"].ShouldBe("rtsp://camera/stream1");
result.Data[prefix + ".sub_rtsp"].ShouldBe("rtsp://camera/sub");
result.Data[prefix + ".enabled"].ShouldBe("true");
// Cameras of other agents and soft-deleted cameras must not leak.
result.Data!.ShouldNotContainKey($"camera.{otherCamera.Id}.name");
result.Data.ShouldNotContainKey($"camera.{deletedCamera.Id}.name");
}
[Fact]
public async Task Get_effective_config_disabled_camera_should_be_shipped_as_disabled()
{
var agent = new Agent(SiteId, "agent-1", "host1", "1.0.0");
agent.Register(ApiKeyHash, ApiKeyHash[..8]);
var camera = new Camera(SiteId, "Cam off", "rtsp://camera/stream");
camera.AssignAgent(agent.Id);
camera.SetStatus(CameraStatus.Disabled);
var context = CreateContext(agents: [agent], cameras: [camera]);
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[$"camera.{camera.Id}.enabled"].ShouldBe("false");
}
}