Closes #21 L'API key de l'agent était persistée **en clair** dans `agent-state.json` (0600). Ce fix la chiffre au repos avec ASP.NET Core Data Protection (`IDataProtector`) : - `AgentState.SaveAsync` écrit `apiKey` chiffrée + marqueur `apiKeyProtected: true` (format camelCase, lecture case-insensitive pour compat) - Key ring Data Protection dans `{StateDirectory}/dp-keys` (0700), persisté pour survivre aux redémarrages - **Migration automatique** : les fichiers legacy en clair sont détectés au `LoadAsync` et réécrits chiffrés immédiatement - `SaveAsync` échoue si aucun protector n'est fourni — pas de fallback plaintext silencieux - Key ring non déchiffrable → état traité comme corrompu, l'agent se ré-enregistre (log warning) ## Vérifications - `dotnet build` : 0 warning / 0 erreur (TreatWarningsAsErrors) - Tests Agent : **197/197 ✅** (dont 5 nouveaux : pas de clair sur disque, migration legacy, échec déchiffrement, fail-fast sans protector) - Suite complète : Domain 142, Application 391, Web 225, Api 2, Integration 125 ✅ (en isolation) - Échecs Infrastructure (24) : **préexistants sur main** (fixture Testcontainers `PostgreSqlContainer` — vérifié sur worktree baseline origin/main) ## Prod hardening (option documentée dans le code) IDataProtector protège contre la lecture du fichier d'état seul. Contre une compromission complète du volume (qui exposerait aussi le key ring), binder le key ring à un TPM/HSM ou le monter hors du volume sauvegardé. Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/116
316 lines
10 KiB
C#
316 lines
10 KiB
C#
using System.Net;
|
|
using System.Text.Json;
|
|
using Heimdall.Agent.Services;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
using NSubstitute;
|
|
|
|
namespace Heimdall.Agent.Tests;
|
|
|
|
public class AgentRegistrationServiceTests : IDisposable
|
|
{
|
|
/// <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();
|
|
|
|
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(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
|
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(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
|
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);
|
|
}
|
|
|
|
[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);
|
|
await Task.Delay(500);
|
|
|
|
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
|
|
var saved = new AgentState(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
|
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();
|
|
}
|
|
|
|
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,
|
|
new Logging.LogBufferService(),
|
|
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));
|
|
}
|
|
}
|