Files
Heimdall/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs
T

564 lines
23 KiB
C#

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SignalR;
using System.Reflection;
using Heimdall.Agent.Services;
using Heimdall.Application.DTOs;
using Heimdall.Application.Security;
using Microsoft.Extensions.DependencyInjection;
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,
RuntimeLogLevel? runtimeLogLevel = null,
IHttpClientFactory? httpFactory = null,
CameraConfigStore? cameraStore = null,
string centralUrl = "http://localhost:5000",
ILogger<ConfigReceiverService>? logger = null)
{
state ??= new AgentState { AgentId = Guid.Empty };
var options = Options.Create(new AgentOptions
{
CentralUrl = centralUrl,
SiteToken = "test"
});
logger ??= Substitute.For<ILogger<ConfigReceiverService>>();
httpFactory ??= Substitute.For<IHttpClientFactory>();
var scanTrigger = new DiscoveryScanTrigger();
runtimeLogLevel ??= CreateRuntimeLogLevel().Runtime;
return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(), runtimeLogLevel, cameraStore ?? new CameraConfigStore());
}
/// <summary>
/// Builds a RuntimeLogLevel sharing the exact LoggerFilterOptions instance
/// used by its LoggerFactory — mirrors the production DI wiring and makes
/// live log-level changes observable on existing loggers.
/// </summary>
private static (RuntimeLogLevel Runtime, ILoggerFactory Factory) CreateRuntimeLogLevel(List<string>? captured = null)
{
var services = new ServiceCollection();
services.AddLogging(builder =>
{
if (captured is not null)
builder.AddProvider(new ListLoggerProvider(captured));
});
var sp = services.BuildServiceProvider();
var factory = sp.GetRequiredService<ILoggerFactory>();
var options = sp.GetRequiredService<IOptions<LoggerFilterOptions>>();
return (new RuntimeLogLevel(factory, options), factory);
}
[Fact]
public async Task SignalRReconnect_Rejoins_AndReplacesCompleteCameraSnapshot()
{
var initialId = Guid.NewGuid();
var nextId = Guid.NewGuid();
IReadOnlyDictionary<string, string> config = new Dictionary<string, string>
{ [$"camera.{initialId}.rtsp"] = "rtsp://initial" };
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Logging.ClearProviders();
builder.Services.AddSignalR();
await using var app = builder.Build();
app.MapHub<ReconnectFixtureHub>("/hubs/config");
app.MapGet("/api/settings/agent/{id}", () => Volatile.Read(ref config));
await app.StartAsync();
var factory = Substitute.For<IHttpClientFactory>();
factory.CreateClient("Central").Returns(_ => new HttpClient());
var store = new CameraConfigStore();
using var receiver = CreateService(new AgentState { AgentId = Guid.NewGuid(), ApiKey = "fixture" },
httpFactory: factory, cameraStore: store, centralUrl: app.Urls.Single());
await receiver.StartAsync(CancellationToken.None);
try
{
await WaitForAsync(() => store.Cameras.Any(c => c.CameraId == initialId));
Volatile.Write(ref config, new Dictionary<string, string>
{ [$"camera.{nextId}.rtsp"] = "rtsp://next", [$"camera.{nextId}.enabled"] = "false" });
// Abort the HTTP transport without sending a SignalR close message.
ReconnectFixtureHub.AbortTransport!();
await WaitForAsync(() => store.Cameras.Count == 1 && store.Cameras[0].CameraId == nextId &&
ReconnectFixtureHub.JoinCount >= 2);
store.Cameras.Single().Enabled.ShouldBeFalse();
}
finally { await receiver.StopAsync(CancellationToken.None); }
}
private static async Task WaitForAsync(Func<bool> condition)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
while (!condition()) await Task.Delay(50, timeout.Token);
}
[Fact]
public void Sensitive_setting_values_are_never_logged_even_when_invalid_or_unknown()
{
var messages = new List<string>();
using var factory = LoggerFactory.Create(b => b.SetMinimumLevel(LogLevel.Trace).AddProvider(new ListLoggerProvider(messages)));
using var service = CreateService(logger: factory.CreateLogger<ConfigReceiverService>());
var apply = typeof(ConfigReceiverService).GetMethod("ApplySetting", BindingFlags.NonPublic | BindingFlags.Instance)!;
foreach (var key in new[] { "heartbeat.interval.seconds", "log.level", "autoUpdateEnabled", "unknown.setting", "model.api_key", "discovery.credentials" })
apply.Invoke(service, [key, "SENSITIVE_VALUE_SENTINEL"]);
messages.ShouldNotBeEmpty();
string.Join("\n", messages).ShouldNotContain("SENSITIVE_VALUE_SENTINEL");
}
[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 void ApplySetting_LogLevel_AppliesLive()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var runtime = CreateRuntimeLogLevel().Runtime;
var service = CreateService(state, runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
method.Invoke(service, ["log.level", "Warning"]);
// The setting is applied live to the shared runtime level (observable effect)
runtime.Level.ShouldBe(LogLevel.Warning);
}
[Fact]
public void ApplySetting_LogLevel_HasObservableEffectOnExistingLoggers()
{
var captured = new List<string>();
var (runtime, factory) = CreateRuntimeLogLevel(captured);
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state, runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// A logger created BEFORE the change…
var logger = factory.CreateLogger("Heimdall.Agent.SomeService");
logger.IsEnabled(LogLevel.Information).ShouldBeTrue();
logger.LogInformation("before-change");
// …must re-filter immediately after a remote log.level change.
method.Invoke(service, ["log.level", "Warning"]);
logger.IsEnabled(LogLevel.Information).ShouldBeFalse();
logger.IsEnabled(LogLevel.Warning).ShouldBeTrue();
// The real log pipeline reflects the new minimum: Information is
// dropped, Warning passes through.
logger.LogInformation("after-change-info");
logger.LogWarning("after-change-warning");
captured.ShouldNotContain(m => m.Contains("after-change-info", StringComparison.Ordinal));
captured.ShouldContain(m => m.Contains("after-change-warning", StringComparison.Ordinal));
}
[Fact]
public void ApplySetting_LogLevel_CanBeLoweredAgain()
{
var captured = new List<string>();
var (runtime, factory) = CreateRuntimeLogLevel(captured);
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state, runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
var logger = factory.CreateLogger("Heimdall.Agent.SomeService");
method.Invoke(service, ["log.level", "Warning"]);
logger.IsEnabled(LogLevel.Information).ShouldBeFalse();
// Lowering back to Debug must not be blocked by a stale Warning rule
method.Invoke(service, ["log.level", "Debug"]);
logger.IsEnabled(LogLevel.Debug).ShouldBeTrue();
}
[Fact]
public void ApplySetting_LogLevel_InvalidValue_KeepsCurrentLevel()
{
var runtime = CreateRuntimeLogLevel().Runtime;
var service = CreateService(runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
method.Invoke(service, ["log.level", "NotALevel"]);
runtime.Level.ShouldBe(LogLevel.Information);
}
[Fact]
public void ApplySetting_RestartRequiredKey_LogsExplicitly()
{
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, ["ai.detection.enabled", "true"]))
.ShouldBeNull();
}
[Fact]
public async Task FetchFullConfigAsync_AppliesAllSettings()
{
const string apiKey = "test-agent-api-key";
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = apiKey };
var store = new AgentCredentialStore();
var runtime = CreateRuntimeLogLevel().Runtime;
var key = AgentCredentialEnvelope.DeriveKeyFromApiKey(apiKey);
var envelope = AgentCredentialEnvelope.Encrypt(
[new AgentCameraCredential("admin", "admin", "secret")], key);
var json = $$"""
{
"heartbeat.interval.seconds": "60",
"log.level": "Warning",
"ai.detection.enabled": "true",
"discovery.credentials": "{{envelope}}"
}
""";
var httpFactory = Substitute.For<IHttpClientFactory>();
httpFactory.CreateClient("Central").Returns(new HttpClient(new StubHttpMessageHandler(json)));
var service = CreateService(state, store, runtime, httpFactory);
var method = typeof(ConfigReceiverService).GetMethod("FetchFullConfigAsync",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
await (Task)method.Invoke(service, [CancellationToken.None])!;
// Heartbeat applied live from full reload
state.HeartbeatIntervalSeconds.ShouldBe(60);
// Log level applied live from full reload
runtime.Level.ShouldBe(LogLevel.Warning);
// Credential pool decrypted and stored from full reload
store.Pool.Count.ShouldBe(1);
store.Pool[0].Password.ShouldBe("secret");
}
[Fact]
public async Task FetchFullConfigAsync_AppliesCameraKeys_AndDropsLocalFallback()
{
const string apiKey = "test-agent-api-key";
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = apiKey };
var cameraStore = new CameraConfigStore();
cameraStore.SetLocalFallback(
[new AgentCameraConfig(Guid.NewGuid(), "Locale", "rtsp://local/stream", null, true)]);
var cameraId = Guid.NewGuid();
var json = $$"""
{
"camera.{{cameraId}}.name": "Entrée",
"camera.{{cameraId}}.rtsp": "rtsp://central/stream",
"camera.{{cameraId}}.enabled": "true"
}
""";
var httpFactory = Substitute.For<IHttpClientFactory>();
httpFactory.CreateClient("Central").Returns(new HttpClient(new StubHttpMessageHandler(json)));
var service = CreateService(state, httpFactory: httpFactory, cameraStore: cameraStore);
var method = typeof(ConfigReceiverService).GetMethod("FetchFullConfigAsync",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
await (Task)method.Invoke(service, [CancellationToken.None])!;
// Central camera list replaced the local fallback.
var camera = cameraStore.Cameras.ShouldHaveSingleItem();
camera.CameraId.ShouldBe(cameraId);
camera.Name.ShouldBe("Entrée");
camera.RtspUrl.ShouldBe("rtsp://central/stream");
camera.Enabled.ShouldBeTrue();
}
[Fact]
public void ApplySetting_CameraKey_UpdatesCameraStore()
{
var cameraStore = new CameraConfigStore();
var service = CreateService(cameraStore: cameraStore);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
var id = Guid.NewGuid();
method.Invoke(service, [$"camera.{id}.rtsp", "rtsp://live/stream"]);
method.Invoke(service, [$"camera.{id}.enabled", "false"]);
var camera = cameraStore.Cameras.ShouldHaveSingleItem();
camera.RtspUrl.ShouldBe("rtsp://live/stream");
camera.Enabled.ShouldBeFalse();
}
[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);
}
/// <summary>Returns a fixed JSON body for any request (used to stub the Central config API).</summary>
private sealed class StubHttpMessageHandler : HttpMessageHandler
{
private readonly string _json;
public StubHttpMessageHandler(string json) => _json = json;
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new StringContent(_json, System.Text.Encoding.UTF8, "application/json")
};
return Task.FromResult(response);
}
}
/// <summary>Captures formatted log messages for assertions (in-memory, no sinks).</summary>
private sealed class ListLoggerProvider : ILoggerProvider
{
private readonly List<string> _captured;
public ListLoggerProvider(List<string> captured) => _captured = captured;
public ILogger CreateLogger(string categoryName) => new ListLogger(_captured);
public void Dispose() { }
private sealed class ListLogger : ILogger
{
private readonly List<string> _captured;
public ListLogger(List<string> captured) => _captured = captured;
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
_captured.Add(formatter(state, exception));
}
}
}
}
public sealed class ReconnectFixtureHub : Hub
{
public static Action? AbortTransport { get; private set; }
private static int _joinCount;
public static int JoinCount => Volatile.Read(ref _joinCount);
public Task JoinAgentGroup(string agentId)
{
Interlocked.Increment(ref _joinCount);
AbortTransport = Context.GetHttpContext()!.Abort;
return Groups.AddToGroupAsync(Context.ConnectionId, $"agent_{agentId}");
}
}