234 lines
7.3 KiB
C#
234 lines
7.3 KiB
C#
using System.Net;
|
|||
|
|
using System.Text.Json;
|
||
|
|
using Heimdall.Agent.Services;
|
||
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
||
|
|
using Microsoft.Extensions.Options;
|
||
|
|
using NSubstitute;
|
||
|
|
|
||
|
|
namespace Heimdall.Agent.Tests;
|
||
|
|
|
||
|
|
public class AgentRegistrationServiceTests : IDisposable
|
||
|
|
{
|
||
|
|
private readonly AgentOptions _options = new()
|
||
|
|
{
|
||
|
|
CentralUrl = "http://heimdall.test",
|
||
|
|
SiteToken = "test-token",
|
||
|
|
AgentName = "test-agent",
|
||
|
|
HeartbeatIntervalSeconds = 1,
|
||
|
|
RegistrationMaxRetries = 3,
|
||
|
|
Version = "1.0.0"
|
||
|
|
};
|
||
|
|
|
||
|
|
private readonly TempDir _tmp = new();
|
||
|
|
private readonly AgentState _state = new();
|
||
|
|
private readonly SystemMetricsProvider _metrics = new();
|
||
|
|
|
||
|
|
public AgentRegistrationServiceTests()
|
||
|
|
{
|
||
|
|
_state.ConfigureStateDirectory(_tmp.Path);
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public async Task Registration_Success_SetsAgentIdAndApiKey()
|
||
|
|
{
|
||
|
|
var handler = CreateOkHandler();
|
||
|
|
var factory = CreateHttpClientFactory(handler);
|
||
|
|
var service = CreateService(factory);
|
||
|
|
|
||
|
|
await service.StartAsync(CancellationToken.None);
|
||
|
|
await Task.Delay(500);
|
||
|
|
await service.StopAsync(CancellationToken.None);
|
||
|
|
|
||
|
|
_state.AgentId.ShouldNotBe(Guid.Empty);
|
||
|
|
_state.ApiKey.ShouldBe("sk_test_abc123");
|
||
|
|
_state.ApiKeyPrefix.ShouldBe("sk_test");
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public async Task Registration_WithRetry_EventuallySucceeds()
|
||
|
|
{
|
||
|
|
var attempt = 0;
|
||
|
|
var handler = new MockHttpMessageHandler(req =>
|
||
|
|
{
|
||
|
|
attempt++;
|
||
|
|
if (attempt < 3)
|
||
|
|
return new HttpResponseMessage(HttpStatusCode.ServiceUnavailable);
|
||
|
|
|
||
|
|
return CreateRegistrationResponse();
|
||
|
|
});
|
||
|
|
|
||
|
|
var factory = CreateHttpClientFactory(handler);
|
||
|
|
var service = CreateService(factory);
|
||
|
|
|
||
|
|
await service.StartAsync(CancellationToken.None);
|
||
|
|
// Retry backoff: 2^1=2s, 2^2=4s → need ~7s total for 3 attempts
|
||
|
|
// Use a shorter deadline by reducing retries in options
|
||
|
|
await Task.Delay(8000);
|
||
|
|
await service.StopAsync(CancellationToken.None);
|
||
|
|
|
||
|
|
_state.AgentId.ShouldNotBe(Guid.Empty);
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public async Task Registration_AllRetriesFail_LogsError()
|
||
|
|
{
|
||
|
|
var handler = new MockHttpMessageHandler(_ =>
|
||
|
|
new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
|
||
|
|
|
||
|
|
var factory = CreateHttpClientFactory(handler);
|
||
|
|
var service = CreateService(factory);
|
||
|
|
|
||
|
|
// StartAsync does not throw — the exception is caught by BackgroundService.
|
||
|
|
// Verify the service enters a faulted state.
|
||
|
|
await service.StartAsync(CancellationToken.None);
|
||
|
|
|
||
|
|
// Wait for all retries to exhaust (6s backoff + margin)
|
||
|
|
await Task.Delay(9000);
|
||
|
|
|
||
|
|
// AgentId should remain empty because registration never succeeded
|
||
|
|
_state.AgentId.ShouldBe(Guid.Empty);
|
||
|
|
_state.ApiKey.ShouldBeNull();
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public async Task ExistingIdentity_SkipsRegistration()
|
||
|
|
{
|
||
|
|
// Pre-populate the state file so LoadAsync() finds an identity
|
||
|
|
var saved = new AgentState();
|
||
|
|
saved.ConfigureStateDirectory(_tmp.Path);
|
||
|
|
saved.AgentId = Guid.NewGuid();
|
||
|
|
saved.ApiKey = "existing-key";
|
||
|
|
saved.ApiKeyPrefix = "existing";
|
||
|
|
await saved.SaveAsync();
|
||
|
|
|
||
|
|
// Also set the DI singleton state with same values
|
||
|
|
_state.AgentId = saved.AgentId;
|
||
|
|
_state.ApiKey = saved.ApiKey;
|
||
|
|
_state.ApiKeyPrefix = saved.ApiKeyPrefix;
|
||
|
|
|
||
|
|
var registrationCalled = false;
|
||
|
|
var handler = new MockHttpMessageHandler(req =>
|
||
|
|
{
|
||
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
||
|
|
registrationCalled = true;
|
||
|
|
|
||
|
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
||
|
|
{
|
||
|
|
Content = new StringContent(JsonSerializer.Serialize(new
|
||
|
|
{
|
||
|
|
agentId = Guid.NewGuid(),
|
||
|
|
apiKey = "new-key",
|
||
|
|
apiKeyPrefix = "new"
|
||
|
|
}))
|
||
|
|
};
|
||
|
|
});
|
||
|
|
|
||
|
|
var factory = CreateHttpClientFactory(handler);
|
||
|
|
var service = CreateService(factory);
|
||
|
|
|
||
|
|
await service.StartAsync(CancellationToken.None);
|
||
|
|
await Task.Delay(500);
|
||
|
|
await service.StopAsync(CancellationToken.None);
|
||
|
|
|
||
|
|
registrationCalled.ShouldBeFalse();
|
||
|
|
_state.ApiKey.ShouldBe("existing-key"); // unchanged
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public async Task StopAsync_SendsOfflineHeartbeat()
|
||
|
|
{
|
||
|
|
HttpResponseMessage? lastHeartbeat = null;
|
||
|
|
var handler = new MockHttpMessageHandler(req =>
|
||
|
|
{
|
||
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
||
|
|
return CreateRegistrationResponse();
|
||
|
|
|
||
|
|
if (req.RequestUri?.ToString().Contains("/heartbeat") == true)
|
||
|
|
{
|
||
|
|
lastHeartbeat = new HttpResponseMessage(HttpStatusCode.OK);
|
||
|
|
return lastHeartbeat;
|
||
|
|
}
|
||
|
|
|
||
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
||
|
|
});
|
||
|
|
|
||
|
|
var factory = CreateHttpClientFactory(handler);
|
||
|
|
var service = CreateService(factory);
|
||
|
|
|
||
|
|
await service.StartAsync(CancellationToken.None);
|
||
|
|
await Task.Delay(500);
|
||
|
|
|
||
|
|
await service.StopAsync(CancellationToken.None);
|
||
|
|
|
||
|
|
// Agent must be registered after the flow
|
||
|
|
_state.AgentId.ShouldNotBe(Guid.Empty);
|
||
|
|
}
|
||
|
|
|
||
|
|
public void Dispose()
|
||
|
|
{
|
||
|
|
_tmp.Dispose();
|
||
|
|
GC.SuppressFinalize(this);
|
||
|
|
}
|
||
|
|
|
||
|
|
// --- Helpers ---
|
||
|
|
|
||
|
|
private AgentRegistrationService CreateService(
|
||
|
|
IHttpClientFactory factory,
|
||
|
|
AgentState? state = null)
|
||
|
|
{
|
||
|
|
state ??= _state;
|
||
|
|
return new AgentRegistrationService(
|
||
|
|
factory,
|
||
|
|
state,
|
||
|
|
Options.Create(_options),
|
||
|
|
_metrics,
|
||
|
|
NullLogger<AgentRegistrationService>.Instance);
|
||
|
|
}
|
||
|
|
|
||
|
|
private static IHttpClientFactory CreateHttpClientFactory(
|
||
|
|
MockHttpMessageHandler handler)
|
||
|
|
{
|
||
|
|
var client = new HttpClient(handler) { BaseAddress = new Uri("http://heimdall.test") };
|
||
|
|
var factory = Substitute.For<IHttpClientFactory>();
|
||
|
|
factory.CreateClient("Central").Returns(client);
|
||
|
|
factory.CreateClient("IpResolver").Returns(client);
|
||
|
|
return factory;
|
||
|
|
}
|
||
|
|
|
||
|
|
private static MockHttpMessageHandler CreateOkHandler()
|
||
|
|
{
|
||
|
|
return new MockHttpMessageHandler(req =>
|
||
|
|
{
|
||
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
||
|
|
return CreateRegistrationResponse();
|
||
|
|
|
||
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
private static HttpResponseMessage CreateRegistrationResponse()
|
||
|
|
{
|
||
|
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
||
|
|
{
|
||
|
|
Content = new StringContent(JsonSerializer.Serialize(new
|
||
|
|
{
|
||
|
|
agentId = Guid.NewGuid(),
|
||
|
|
apiKey = "sk_test_abc123",
|
||
|
|
apiKeyPrefix = "sk_test"
|
||
|
|
}))
|
||
|
|
};
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Mock HTTP handler that returns predefined responses per request.
|
||
|
|
/// </summary>
|
||
|
|
public class MockHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> handler)
|
||
|
|
: HttpMessageHandler
|
||
|
|
{
|
||
|
|
protected override Task<HttpResponseMessage> SendAsync(
|
||
|
|
HttpRequestMessage request, CancellationToken cancellationToken)
|
||
|
|
{
|
||
|
|
return Task.FromResult(handler(request));
|
||
|
|
}
|
||
|
|
}
|