using System.Net.Http.Headers; using System.Net.Http.Json; using Heimdall.IntegrationTests.Factories; using Shouldly; namespace Heimdall.IntegrationTests.Controllers; public class AuthControllerTests : PostgresTestBase { private HttpClient? _client; private HttpClient Client => _client ?? throw new InvalidOperationException("Client not initialized"); private static readonly SemaphoreSlim _seedLock = new(1, 1); private static bool _seeded; public AuthControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } /// /// Clear static cache and create HTTP client AFTER DB reset. /// Creating Factory.CreateClient() before InitializeAsync would start the /// server (with role seeding) but then ResetDatabaseAsync() truncates the /// seeded roles — causing "Role ADMIN does not exist" on first request. /// public override async Task InitializeAsync() { await base.InitializeAsync(); _seeded = false; _client = Factory.CreateClient(); } /// /// Seeds the public registration setting so non-first-user registrations work. /// Registers the first admin user and creates the AppSetting via the API. /// Runs once per test class (factory is shared). /// private async Task EnsurePublicRegistrationAsync() { if (_seeded) return; await _seedLock.WaitAsync(); try { if (_seeded) return; // First registration is auto-admin (no prior users in the DB) var adminEmail = $"admin-{Guid.NewGuid()}@heimdall.test"; var regResponse = await Client.PostAsJsonAsync("api/auth/register", new { email = adminEmail, password = "TestPassword123!", displayName = "Admin" }); regResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); // Extract access token from the registration response var authResult = await regResponse.Content.ReadFromJsonAsync(); authResult.ShouldNotBeNull(); // Use admin token to create the public registration setting var request = new HttpRequestMessage(HttpMethod.Post, "api/settings") { Content = JsonContent.Create(new { key = "auth.public-registration.enabled", value = "true", valueType = "boolean", category = "Auth", description = "Enable public registration" }) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); var settingResponse = await Client.SendAsync(request); _seeded = true; } finally { _seedLock.Release(); } } [Fact] public async Task Register_ValidRequest_ReturnsOk() { await EnsurePublicRegistrationAsync(); var response = await Client.PostAsJsonAsync("api/auth/register", new { email = $"test-{Guid.NewGuid()}@heimdall.test", password = "TestPassword123!", displayName = "Test User" }); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); } [Fact] public async Task Register_DuplicateEmail_ReturnsConflict() { await EnsurePublicRegistrationAsync(); var email = $"dup-{Guid.NewGuid()}@heimdall.test"; var first = await Client.PostAsJsonAsync("api/auth/register", new { email, password = "TestPassword123!", displayName = "User 1" }); first.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); var second = await Client.PostAsJsonAsync("api/auth/register", new { email, password = "TestPassword123!", displayName = "User 2" }); second.StatusCode.ShouldBe(System.Net.HttpStatusCode.Conflict); } [Fact] public async Task Login_ValidCredentials_ReturnsOk() { await EnsurePublicRegistrationAsync(); var email = $"login-{Guid.NewGuid()}@heimdall.test"; await Client.PostAsJsonAsync("api/auth/register", new { email, password = "TestPassword123!", displayName = "Login User" }); var response = await Client.PostAsJsonAsync("api/auth/login", new { email, password = "TestPassword123!" }); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); } [Fact] public async Task Login_InvalidPassword_ReturnsUnauthorized() { await EnsurePublicRegistrationAsync(); var email = $"badpwd-{Guid.NewGuid()}@heimdall.test"; await Client.PostAsJsonAsync("api/auth/register", new { email, password = "TestPassword123!", displayName = "Bad Pwd User" }); var response = await Client.PostAsJsonAsync("api/auth/login", new { email, password = "WrongPassword!" }); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); } /// DTO matching the API auth response for extracting the access token. private sealed record AuthTestResponse( string AccessToken, string RefreshToken, DateTime ExpiresAt, bool Requires2fa, UserInfo? User); private sealed record UserInfo(Guid Id, string Email, string DisplayName, IList? Roles); }