using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using Heimdall.IntegrationTests.Factories; using Shouldly; namespace Heimdall.IntegrationTests.Controllers; /// /// Integration tests for SettingsController (api/settings). /// /// NOTE: Rate limit is 10 auth req/min so we cache admin + viewer tokens /// statically (xUnit creates a new class instance per test). /// public class SettingsControllerTests : PostgresTestBase { private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; private static string? _adminToken; private static string? _viewerToken; private static readonly object TokenLock = new(); public SettingsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } /// /// Clear static token cache before each test because the DB is truncated /// (cached tokens reference users that no longer exist after reset). /// public override async Task InitializeAsync() { await base.InitializeAsync(); _adminToken = null; _viewerToken = null; _seeded = false; } /// Get a shared admin-authenticated HttpClient (lazy, cached token). private async Task GetAdminClientAsync() { var token = _adminToken; if (token is null) { token = await RegisterAdminAsync(); lock (TokenLock) { _adminToken ??= token; } token = _adminToken!; } var client = Factory.CreateClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); return client; } /// Get a shared viewer-authenticated HttpClient (lazy, cached token). private async Task GetViewerClientAsync() { var token = _viewerToken; if (token is null) { token = await RegisterViewerAsync(); lock (TokenLock) { _viewerToken ??= token; } token = _viewerToken!; } var client = Factory.CreateClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); return client; } /// /// Bootstrap an admin token: the first registered user becomes Admin /// automatically. (register-admin itself requires an existing admin token.) /// private async Task RegisterAdminAsync() { var email = $"admin-{Guid.NewGuid()}@heimdall.test"; var client = Factory.CreateClient(); var response = await client.PostAsJsonAsync("api/auth/register", new { email, password = "AdminPwd123!", displayName = "Settings Admin" }); var content = await response.Content.ReadFromJsonAsync(JsonOptions); return content.GetProperty("accessToken").GetString()!; } private async Task RegisterViewerAsync() { // Ensure public registration is enabled (seed via an admin) await EnsurePublicRegistrationAsync(); var email = $"viewer-{Guid.NewGuid()}@heimdall.test"; var client = Factory.CreateClient(); var response = await client.PostAsJsonAsync("api/auth/register", new { email, password = "ViewerPwd123!", displayName = "Settings Viewer" }); var content = await response.Content.ReadFromJsonAsync(JsonOptions); return content.GetProperty("accessToken").GetString()!; } private static bool _seeded; private static readonly object _seedLock = new(); /// Seeds the public registration setting via admin API (runs once per test class). private async Task EnsurePublicRegistrationAsync() { if (_seeded) return; lock (_seedLock) { if (_seeded) return; } var client = Factory.CreateClient(); // First registration is auto-admin (no prior users in the DB) var adminEmail = $"seed-admin-{Guid.NewGuid()}@heimdall.test"; var regResponse = await client.PostAsJsonAsync("api/auth/register", new { email = adminEmail, password = "AdminPwd123!", displayName = "Seed Admin" }); var content = await regResponse.Content.ReadFromJsonAsync(JsonOptions); var token = content.GetProperty("accessToken").GetString()!; // Use admin token to create the public registration setting var adminClient = Factory.CreateClient(); adminClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); await adminClient.PostAsJsonAsync("api/settings", new { key = "auth.public-registration.enabled", value = "true", valueType = "bool", category = "Auth" }); _seeded = true; } /// /// Create a site + agent and return the agent ID. /// private async Task CreateAgentAsync() { var admin = await GetAdminClientAsync(); var siteResponse = await admin.PostAsJsonAsync("api/sites", new { name = $"SettingsTest_{Guid.NewGuid():N}", timezone = "UTC" }); var siteContent = await siteResponse.Content.ReadFromJsonAsync(JsonOptions); var siteId = siteContent.GetProperty("id").GetGuid(); var tokenResponse = await admin.PostAsync($"api/sites/{siteId}/tokens", null); var tokenContent = await tokenResponse.Content.ReadFromJsonAsync(JsonOptions); var token = tokenContent.GetProperty("token").GetString()!; var agentResponse = await admin.PostAsJsonAsync("api/agents/register", new { token, hostname = $"settings-agent-{Guid.NewGuid():N}", version = "1.0.0-test" }); var agentContent = await agentResponse.Content.ReadFromJsonAsync(JsonOptions); return agentContent.GetProperty("agentId").GetGuid(); } // ──────────────────────────── AUTH ──────────────────────────── [Fact] public async Task ListAll_WithoutAuth_ReturnsUnauthorized() { var client = Factory.CreateClient(); var response = await client.GetAsync("api/settings"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); } [Fact] public async Task ListAll_WithNonAdminUser_ReturnsForbidden() { var client = await GetViewerClientAsync(); var response = await client.GetAsync("api/settings"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden); } [Fact] public async Task CreateSetting_WithoutAuth_ReturnsUnauthorized() { var client = Factory.CreateClient(); var response = await client.PostAsJsonAsync("api/settings", new { key = "test.setting.unauth", value = "test", category = "Testing" }); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); } [Fact] public async Task CreateSetting_WithNonAdminUser_ReturnsForbidden() { var client = await GetViewerClientAsync(); var response = await client.PostAsJsonAsync("api/settings", new { key = $"test.setting.forbid.{Guid.NewGuid()}", value = "test", category = "Testing" }); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden); } // ──────────────────────────── GLOBAL SETTINGS CRUD ──────────────────────────── [Fact] public async Task CreateSetting_WithAdmin_ReturnsOk() { var client = await GetAdminClientAsync(); var response = await client.PostAsJsonAsync("api/settings", new { key = $"create.setting.{Guid.NewGuid()}", value = "test-value", category = "Testing", description = "Test setting created by integration test" }); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var content = await response.Content.ReadFromJsonAsync(JsonOptions); content.GetProperty("key").GetString().ShouldNotBeNullOrEmpty(); content.GetProperty("value").GetString().ShouldBe("test-value"); content.GetProperty("category").GetString().ShouldBe("Testing"); } [Fact] public async Task CreateSetting_DuplicateKey_ReturnsConflict() { var client = await GetAdminClientAsync(); var key = $"dup.setting.{Guid.NewGuid()}"; var first = await client.PostAsJsonAsync("api/settings", new { key, value = "first-value", category = "Testing" }); first.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var second = await client.PostAsJsonAsync("api/settings", new { key, value = "second-value", category = "Testing" }); second.StatusCode.ShouldBe(System.Net.HttpStatusCode.Conflict); } [Fact] public async Task ListAll_WithAdmin_ReturnsAllSettings() { var client = await GetAdminClientAsync(); var key1 = $"list.test.1.{Guid.NewGuid()}"; var key2 = $"list.test.2.{Guid.NewGuid()}"; await client.PostAsJsonAsync("api/settings", new { key = key1, value = "v1", category = "Testing" }); await client.PostAsJsonAsync("api/settings", new { key = key2, value = "v2", category = "Testing" }); var response = await client.GetAsync("api/settings"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var content = await response.Content.ReadFromJsonAsync(JsonOptions); var settings = content.EnumerateArray().ToList(); settings.Any(s => s.GetProperty("key").GetString() == key1).ShouldBeTrue(); settings.Any(s => s.GetProperty("key").GetString() == key2).ShouldBeTrue(); } [Fact] public async Task GetByKey_ExistingKey_ReturnsSetting() { var client = await GetAdminClientAsync(); var key = $"get.by.key.{Guid.NewGuid()}"; await client.PostAsJsonAsync("api/settings", new { key, value = "get-value", category = "Testing" }); var response = await client.GetAsync($"api/settings/{key}"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var content = await response.Content.ReadFromJsonAsync(JsonOptions); content.GetProperty("key").GetString().ShouldBe(key); content.GetProperty("value").GetString().ShouldBe("get-value"); } [Fact] public async Task GetByKey_NonExistentKey_ReturnsNotFound() { var client = await GetAdminClientAsync(); var response = await client.GetAsync("api/settings/nonexistent.setting.key"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound); } [Fact] public async Task UpdateSetting_ExistingKey_ReturnsUpdatedValue() { var client = await GetAdminClientAsync(); var key = $"update.setting.{Guid.NewGuid()}"; await client.PostAsJsonAsync("api/settings", new { key, value = "original-value", category = "Testing" }); var response = await client.PutAsJsonAsync($"api/settings/{key}", new { value = "updated-value", description = "Updated description" }); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var content = await response.Content.ReadFromJsonAsync(JsonOptions); content.GetProperty("key").GetString().ShouldBe(key); content.GetProperty("value").GetString().ShouldBe("updated-value"); } [Fact] public async Task UpdateSetting_NonExistentKey_ReturnsNotFound() { var client = await GetAdminClientAsync(); var response = await client.PutAsJsonAsync("api/settings/nonexistent.update.key", new { value = "updated-value" }); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound); } [Fact] public async Task DeleteSetting_ExistingKey_ReturnsNoContent() { var client = await GetAdminClientAsync(); var key = $"delete.setting.{Guid.NewGuid()}"; await client.PostAsJsonAsync("api/settings", new { key, value = "to-delete", category = "Testing" }); var response = await client.DeleteAsync($"api/settings/{key}"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NoContent); } [Fact] public async Task DeleteSetting_NonExistentKey_ReturnsNotFound() { var client = await GetAdminClientAsync(); var response = await client.DeleteAsync("api/settings/nonexistent.delete.key"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound); } // ──────────────────────────── AGENT EFFECTIVE CONFIG ──────────────────────────── [Fact] public async Task GetEffectiveConfig_WithGlobalSettings_ReturnsDictionary() { var admin = await GetAdminClientAsync(); var agentId = await CreateAgentAsync(); var key = $"eff.config.{Guid.NewGuid()}"; await admin.PostAsJsonAsync("api/settings", new { key, value = "eff-value", category = "Testing" }); var response = await admin.GetAsync($"api/settings/agent/{agentId}"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var content = await response.Content.ReadFromJsonAsync(JsonOptions); content.TryGetProperty(key, out var val).ShouldBeTrue(); val.GetString().ShouldBe("eff-value"); } [Fact] public async Task GetEffectiveConfig_NonExistentAgent_ReturnsEmptyDictionary() { var client = await GetAdminClientAsync(); var response = await client.GetAsync($"api/settings/agent/{Guid.NewGuid()}"); // The service returns global defaults (empty if none exist), not 404. response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var content = await response.Content.ReadFromJsonAsync(JsonOptions); content.ValueKind.ShouldBe(System.Text.Json.JsonValueKind.Object); } [Fact] public async Task SetAgentOverride_WithValidRequest_ReturnsOverride() { var admin = await GetAdminClientAsync(); var agentId = await CreateAgentAsync(); var key = $"override.set.{Guid.NewGuid()}"; await admin.PostAsJsonAsync("api/settings", new { key, value = "global-value", category = "Testing" }); var response = await admin.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", new { key, value = "override-value" }); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var content = await response.Content.ReadFromJsonAsync(JsonOptions); content.GetProperty("key").GetString().ShouldBe(key); content.GetProperty("value").GetString().ShouldBe("override-value"); content.GetProperty("agentId").GetGuid().ShouldBe(agentId); } [Fact] public async Task GetEffectiveConfig_WithOverride_ReturnsOverrideValue() { var admin = await GetAdminClientAsync(); var agentId = await CreateAgentAsync(); var key = $"eff.override.{Guid.NewGuid()}"; await admin.PostAsJsonAsync("api/settings", new { key, value = "global-value", category = "Testing" }); await admin.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", new { key, value = "override-value" }); var response = await admin.GetAsync($"api/settings/agent/{agentId}"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var content = await response.Content.ReadFromJsonAsync(JsonOptions); content.TryGetProperty(key, out var val).ShouldBeTrue(); val.GetString().ShouldBe("override-value"); } [Fact] public async Task ListAgentOverrides_WithOverrides_ReturnsOverrideList() { var admin = await GetAdminClientAsync(); var agentId = await CreateAgentAsync(); var key1 = $"override.list.1.{Guid.NewGuid()}"; var key2 = $"override.list.2.{Guid.NewGuid()}"; await admin.PostAsJsonAsync("api/settings", new { key = key1, value = "global1", category = "Testing" }); await admin.PostAsJsonAsync("api/settings", new { key = key2, value = "global2", category = "Testing" }); await admin.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", new { key = key1, value = "override1" }); await admin.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", new { key = key2, value = "override2" }); var response = await admin.GetAsync($"api/settings/agent/{agentId}/overrides"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var content = await response.Content.ReadFromJsonAsync(JsonOptions); var overrides = content.EnumerateArray().ToList(); overrides.Count.ShouldBe(2); overrides.Any(o => o.GetProperty("key").GetString() == key1).ShouldBeTrue(); overrides.Any(o => o.GetProperty("key").GetString() == key2).ShouldBeTrue(); } [Fact] public async Task RemoveAgentOverride_ExistingOverride_ReturnsNoContent() { var admin = await GetAdminClientAsync(); var agentId = await CreateAgentAsync(); var key = $"override.remove.{Guid.NewGuid()}"; await admin.PostAsJsonAsync("api/settings", new { key, value = "global", category = "Testing" }); await admin.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", new { key, value = "override" }); var deleteResponse = await admin.DeleteAsync($"api/settings/agent/{agentId}/overrides/{key}"); deleteResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.NoContent); var configResponse = await admin.GetAsync($"api/settings/agent/{agentId}"); var configContent = await configResponse.Content.ReadFromJsonAsync(JsonOptions); configContent.TryGetProperty(key, out var val).ShouldBeTrue(); val.GetString().ShouldBe("global"); } [Fact] public async Task RemoveAgentOverride_NonExistentOverride_ReturnsNotFound() { var admin = await GetAdminClientAsync(); var agentId = await CreateAgentAsync(); var response = await admin.DeleteAsync($"api/settings/agent/{agentId}/overrides/nonexistent.override"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound); } // ──────────────────────────── RELOAD ──────────────────────────── [Fact] public async Task ReloadAllAgents_WithAdmin_ReturnsAccepted() { var client = await GetAdminClientAsync(); var response = await client.PostAsync("api/settings/reload", null); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Accepted); } }