using Heimdall.Agent.Services;
using Microsoft.AspNetCore.DataProtection;
namespace Heimdall.Agent.Tests;
public class AgentStateTests
{
/// Shared provider so save+load within a test use the same key.
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(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();
}
}
///
/// Helper that creates a temporary directory and cleans it up on dispose.
///
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 */ }
}
}