Files
Heimdall/tests/Heimdall.Agent.Tests/AgentStateTests.cs
T
Arnaud Dartois 17b973f010 fix(agent): chiffre l'API key au repos (IDataProtector) (#116)
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
2026-08-14 14:01:42 +02:00

195 lines
5.9 KiB
C#

using Heimdall.Agent.Services;
using Microsoft.AspNetCore.DataProtection;
namespace Heimdall.Agent.Tests;
public class AgentStateTests
{
/// <summary>Shared provider so save+load within a test use the same key.</summary>
private static readonly EphemeralDataProtectionProvider Provider = new();
private static IDataProtector CreateProtector() =>
Provider.CreateProtector(AgentState.KeyProtectionPurpose);
private static AgentState CreateState(string dir)
{
var state = new AgentState(CreateProtector());
state.ConfigureStateDirectory(dir);
return state;
}
[Fact]
public async Task SaveAndLoad_PersistsIdentity()
{
using var tmp = new TempDir();
var state = CreateState(tmp.Path);
state.AgentId = Guid.NewGuid();
state.ApiKey = "test-api-key-abc123";
state.ApiKeyPrefix = "abc";
state.PublicIp = "192.168.1.1";
await state.SaveAsync();
var loaded = CreateState(tmp.Path);
var result = await loaded.LoadAsync();
result.ShouldNotBeNull();
result!.AgentId.ShouldBe(state.AgentId);
result.ApiKey.ShouldBe("test-api-key-abc123");
result.ApiKeyPrefix.ShouldBe("abc");
result.PublicIp.ShouldBe("192.168.1.1");
}
[Fact]
public async Task Save_DoesNotPersistApiKeyInPlaintext()
{
using var tmp = new TempDir();
var state = CreateState(tmp.Path);
state.AgentId = Guid.NewGuid();
state.ApiKey = "super-secret-key-42";
state.ApiKeyPrefix = "ssk";
await state.SaveAsync();
var path = Path.Combine(tmp.Path, "agent-state.json");
File.Exists(path).ShouldBeTrue();
var json = await File.ReadAllTextAsync(path);
json.ShouldNotContain("super-secret-key-42");
json.ShouldContain("\"apiKeyProtected\":true");
}
[Fact]
public async Task Load_MigratesLegacyPlaintextFile()
{
using var tmp = new TempDir();
var agentId = Guid.NewGuid();
var legacyJson =
$$"""{"AgentId":"{{agentId}}","ApiKey":"legacy-plain-key","ApiKeyPrefix":"abc","PublicIp":"10.0.0.1","HeartbeatIntervalSeconds":null}""";
await File.WriteAllTextAsync(Path.Combine(tmp.Path, "agent-state.json"), legacyJson);
var result = await CreateState(tmp.Path).LoadAsync();
result.ShouldNotBeNull();
result!.AgentId.ShouldBe(agentId);
result.ApiKey.ShouldBe("legacy-plain-key");
// Migration: the file is rewritten encrypted, the key is no longer in clear.
var json = await File.ReadAllTextAsync(Path.Combine(tmp.Path, "agent-state.json"));
json.ShouldNotContain("legacy-plain-key");
json.ShouldContain("\"apiKeyProtected\":true");
// A second load decrypts the migrated file.
var again = await CreateState(tmp.Path).LoadAsync();
again.ShouldNotBeNull();
again!.ApiKey.ShouldBe("legacy-plain-key");
}
[Fact]
public async Task Load_WhenCipherCannotBeDecrypted_ReturnsNull()
{
using var tmp = new TempDir();
var state = CreateState(tmp.Path);
state.AgentId = Guid.NewGuid();
state.ApiKey = "key-encrypted-with-provider-a";
await state.SaveAsync();
// A different Data Protection provider holds a different key and cannot
// decrypt the ciphertext → treated like a corrupt state file.
var foreign = new AgentState(
new EphemeralDataProtectionProvider().CreateProtector(AgentState.KeyProtectionPurpose));
foreign.ConfigureStateDirectory(tmp.Path);
var result = await foreign.LoadAsync();
result.ShouldBeNull();
}
[Fact]
public async Task Save_WithoutProtector_Throws()
{
using var tmp = new TempDir();
var state = new AgentState(); // no protector
state.ConfigureStateDirectory(tmp.Path);
state.AgentId = Guid.NewGuid();
state.ApiKey = "should-not-be-saved";
await Should.ThrowAsync<InvalidOperationException>(state.SaveAsync());
// Nothing was persisted.
File.Exists(Path.Combine(tmp.Path, "agent-state.json")).ShouldBeFalse();
}
[Fact]
public async Task Load_WhenNoFile_ReturnsNull()
{
using var tmp = new TempDir();
var result = await CreateState(tmp.Path).LoadAsync();
result.ShouldBeNull();
}
[Fact]
public async Task Load_WhenFileIsCorrupt_ReturnsNull()
{
using var tmp = new TempDir();
Directory.CreateDirectory(tmp.Path);
await File.WriteAllTextAsync(Path.Combine(tmp.Path, "agent-state.json"), "not-json");
var result = await CreateState(tmp.Path).LoadAsync();
result.ShouldBeNull();
}
[Fact]
public async Task Clear_RemovesStateFile()
{
using var tmp = new TempDir();
var state = CreateState(tmp.Path);
state.AgentId = Guid.NewGuid();
await state.SaveAsync();
state.Clear();
File.Exists(Path.Combine(tmp.Path, "agent-state.json")).ShouldBeFalse();
}
[Fact]
public async Task Load_WhenAgentIdIsEmpty_ReturnsNull()
{
using var tmp = new TempDir();
var state = CreateState(tmp.Path);
state.AgentId = Guid.Empty;
state.ApiKey = "some-key";
await state.SaveAsync();
var result = await CreateState(tmp.Path).LoadAsync();
result.ShouldBeNull();
}
}
/// <summary>
/// Helper that creates a temporary directory and cleans it up on dispose.
/// </summary>
public sealed class TempDir : IDisposable
{
public string Path { get; } = System.IO.Path.Combine(
System.IO.Path.GetTempPath(),
"heimdall-agent-tests",
Guid.NewGuid().ToString("N"));
public TempDir() => Directory.CreateDirectory(Path);
public void Dispose()
{
try { Directory.Delete(Path, recursive: true); }
catch { /* best effort cleanup */ }
}
}