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) { state ??= new AgentState { AgentId = Guid.Empty }; var options = Options.Create(new AgentOptions { CentralUrl = "http://localhost:5000", SiteToken = "test" }); var logger = Substitute.For>(); httpFactory ??= Substitute.For(); var scanTrigger = new DiscoveryScanTrigger(); runtimeLogLevel ??= CreateRuntimeLogLevel().Runtime; return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(), runtimeLogLevel); } /// /// 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. /// private static (RuntimeLogLevel Runtime, ILoggerFactory Factory) CreateRuntimeLogLevel(List? 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(); var options = sp.GetRequiredService>(); return (new RuntimeLogLevel(factory, options), factory); } [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(); 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(); 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(); 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 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); } /// Returns a fixed JSON body for any request (used to stub the Central config API). private sealed class StubHttpMessageHandler : HttpMessageHandler { private readonly string _json; public StubHttpMessageHandler(string json) => _json = json; protected override Task 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); } } /// Captures formatted log messages for assertions (in-memory, no sinks). private sealed class ListLoggerProvider : ILoggerProvider { private readonly List _captured; public ListLoggerProvider(List captured) => _captured = captured; public ILogger CreateLogger(string categoryName) => new ListLogger(_captured); public void Dispose() { } private sealed class ListLogger : ILogger { private readonly List _captured; public ListLogger(List captured) => _captured = captured; public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log( LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { _captured.Add(formatter(state, exception)); } } } }