2026-07-18 14:16:13 +00:00
|
|
|
using System.Net;
|
|
|
|
|
using System.Text.Json;
|
|
|
|
|
using Heimdall.Agent.Services;
|
2026-08-14 14:01:42 +02:00
|
|
|
using Microsoft.AspNetCore.DataProtection;
|
2026-07-18 14:16:13 +00:00
|
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
|
|
|
using Microsoft.Extensions.Options;
|
|
|
|
|
using NSubstitute;
|
|
|
|
|
|
|
|
|
|
namespace Heimdall.Agent.Tests;
|
|
|
|
|
|
|
|
|
|
public class AgentRegistrationServiceTests : IDisposable
|
|
|
|
|
{
|
2026-08-14 14:01:42 +02:00
|
|
|
/// <summary>Shared provider so the file written by the fixture can be read
|
|
|
|
|
/// back by the singleton state (same Data Protection key).</summary>
|
|
|
|
|
private static readonly EphemeralDataProtectionProvider Provider = new();
|
|
|
|
|
|
2026-07-18 14:16:13 +00:00
|
|
|
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();
|
2026-08-14 14:01:42 +02:00
|
|
|
private readonly AgentState _state = new(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
2026-07-18 14:16:13 +00:00
|
|
|
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);
|
2026-08-18 08:22:47 +02:00
|
|
|
// Retry backoff: 2^1=2s, 2^2=4s → ~7s for 3 attempts.
|
|
|
|
|
// Poll instead of a fixed delay: under parallel CI load the
|
|
|
|
|
// background service can be delayed beyond 8s (flaky #2228).
|
|
|
|
|
var deadline = DateTime.UtcNow.AddSeconds(25);
|
|
|
|
|
while (DateTime.UtcNow < deadline && _state.AgentId == Guid.Empty)
|
|
|
|
|
await Task.Delay(250);
|
2026-07-18 14:16:13 +00:00
|
|
|
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);
|
|
|
|
|
|
2026-08-18 08:22:47 +02:00
|
|
|
// Wait for all retries to exhaust (backoff 2+4+8s under parallel CI load).
|
|
|
|
|
// Poll instead of a fixed delay to avoid flaky timing.
|
|
|
|
|
var deadline = DateTime.UtcNow.AddSeconds(30);
|
|
|
|
|
while (DateTime.UtcNow < deadline && _state.ApiKey is null)
|
|
|
|
|
await Task.Delay(250);
|
|
|
|
|
await service.StopAsync(CancellationToken.None);
|
2026-07-18 14:16:13 +00:00
|
|
|
|
|
|
|
|
// 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
|
2026-08-14 14:01:42 +02:00
|
|
|
var saved = new AgentState(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
2026-07-18 14:16:13 +00:00
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-10 10:09:27 +02:00
|
|
|
[Fact]
|
|
|
|
|
public async Task Heartbeat_UsesXApiKeyHeader_NotBearer()
|
|
|
|
|
{
|
|
|
|
|
string? xApiKey = null;
|
|
|
|
|
string? authorization = null;
|
|
|
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
|
|
|
{
|
|
|
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
|
|
|
|
return CreateRegistrationResponse();
|
|
|
|
|
|
|
|
|
|
if (req.RequestUri?.ToString().Contains("/heartbeat") == true)
|
|
|
|
|
{
|
|
|
|
|
xApiKey = req.Headers.TryGetValues("X-API-Key", out var values)
|
|
|
|
|
? values.FirstOrDefault()
|
|
|
|
|
: null;
|
|
|
|
|
authorization = req.Headers.Authorization?.ToString();
|
|
|
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
|
|
|
var service = CreateService(factory);
|
|
|
|
|
|
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
2026-08-18 08:22:47 +02:00
|
|
|
// Registration first, then heartbeat (interval 1s). Poll for the
|
|
|
|
|
// heartbeat instead of a fixed 500ms delay (flaky under CI load).
|
|
|
|
|
var deadline = DateTime.UtcNow.AddSeconds(10);
|
|
|
|
|
while (DateTime.UtcNow < deadline && xApiKey is null)
|
|
|
|
|
await Task.Delay(100);
|
2026-08-10 10:09:27 +02:00
|
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
|
|
|
|
|
|
xApiKey.ShouldNotBeNull(); // API key sent via X-API-Key header
|
|
|
|
|
authorization.ShouldBeNull(); // never as Bearer
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Fact]
|
|
|
|
|
public async Task ExistingIdentity_Heartbeat_UsesXApiKeyHeader()
|
|
|
|
|
{
|
|
|
|
|
// Pre-populate the state file so LoadAsync() finds an identity
|
2026-08-14 14:01:42 +02:00
|
|
|
var saved = new AgentState(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
2026-08-10 10:09:27 +02:00
|
|
|
saved.ConfigureStateDirectory(_tmp.Path);
|
|
|
|
|
saved.AgentId = Guid.NewGuid();
|
|
|
|
|
saved.ApiKey = "existing-key";
|
|
|
|
|
saved.ApiKeyPrefix = "existing";
|
|
|
|
|
await saved.SaveAsync();
|
|
|
|
|
|
|
|
|
|
_state.AgentId = saved.AgentId;
|
|
|
|
|
_state.ApiKey = saved.ApiKey;
|
|
|
|
|
_state.ApiKeyPrefix = saved.ApiKeyPrefix;
|
|
|
|
|
|
|
|
|
|
string? xApiKey = null;
|
|
|
|
|
string? authorization = null;
|
|
|
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
|
|
|
{
|
|
|
|
|
if (req.RequestUri?.ToString().Contains("/heartbeat") == true)
|
|
|
|
|
{
|
|
|
|
|
xApiKey = req.Headers.TryGetValues("X-API-Key", out var values)
|
|
|
|
|
? values.FirstOrDefault()
|
|
|
|
|
: null;
|
|
|
|
|
authorization = req.Headers.Authorization?.ToString();
|
|
|
|
|
}
|
|
|
|
|
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);
|
|
|
|
|
|
|
|
|
|
xApiKey.ShouldBe("existing-key");
|
|
|
|
|
authorization.ShouldBeNull();
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-18 14:16:13 +00:00
|
|
|
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,
|
2026-08-11 18:51:52 +02:00
|
|
|
new Logging.LogBufferService(),
|
2026-07-18 14:16:13 +00:00
|
|
|
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));
|
|
|
|
|
}
|
|
|
|
|
}
|