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
This commit is contained in:
Arnaud Dartois authored and Arnaud Dartois committed 2026-08-14 14:01:42 +02:00
1 parent 1b55660513
commit 17b973f010
5 files changed
+234 -28

No files matched your search

+19 -1
View File
@@ -4,6 +4,7 @@ using Heimdall.Agent;
using Heimdall.Agent.Logging;
using Heimdall.Agent.Services;
using Heimdall.Application.Discovery;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
@@ -50,10 +51,27 @@ builder.Services.AddHttpClient("IpResolver", client =>
client.Timeout = TimeSpan.FromSeconds(5);
});
// Data Protection — encrypts the agent API key at rest (issue #21). The key
// ring is persisted next to the state file so the agent can decrypt its
// identity after a restart. Directory locked to owner-only (0700). For
// production hardening against full-volume compromise, bind the key ring to a
// TPM/HSM-backed store or mount it outside the backed-up volume.
var stateDir = builder.Configuration["Agent:StateDirectory"]
?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
var keysDir = Path.Combine(stateDir, "dp-keys");
Directory.CreateDirectory(keysDir);
if (OperatingSystem.IsLinux())
File.SetUnixFileMode(keysDir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
builder.Services.AddDataProtection()
.SetApplicationName("Heimdall.Agent")
.PersistKeysToFileSystem(new DirectoryInfo(keysDir));
// Agent services
builder.Services.AddSingleton<AgentState>(sp =>
{
var state = new AgentState();
var state = new AgentState(
sp.GetRequiredService<IDataProtectionProvider>().CreateProtector(AgentState.KeyProtectionPurpose),
sp.GetRequiredService<ILogger<AgentState>>());
var options = sp.GetRequiredService<IOptions<AgentOptions>>().Value;
var stateDir = options.StateDirectory