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; private static string _adminEmail = ""; 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(); } /// /// Creates the first admin through the one-time setup endpoint. /// Runs once per test class (factory is shared). /// private async Task EnsureAdminCreatedAsync() { 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"; _adminEmail = adminEmail; var regResponse = await Client.PostAsJsonAsync("api/auth/bootstrap-admin", 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(); _seeded = true; } finally { _seedLock.Release(); } } [Fact] public async Task AnonymousRegistrationRoute_IsRemoved() { await EnsureAdminCreatedAsync(); 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.NotFound); } [Fact] public async Task BootstrapAdmin_AfterSetup_ReturnsConflict() { await EnsureAdminCreatedAsync(); var email = $"dup-{Guid.NewGuid()}@heimdall.test"; var second = await Client.PostAsJsonAsync("api/auth/bootstrap-admin", new { email, password = "TestPassword123!", displayName = "User 2" }); second.StatusCode.ShouldBe(System.Net.HttpStatusCode.Conflict); } [Fact] public async Task ConcurrentBootstrapRequests_CreateExactlyOneAdministrator() { var requests = Enumerable.Range(0, 3).Select(index => Client.PostAsJsonAsync("api/auth/bootstrap-admin", new { email = $"concurrent-{index}-{Guid.NewGuid():N}@heimdall.test", password = "ConcurrentTest!Password123", displayName = $"Admin {index}" })); var responses = await Task.WhenAll(requests); responses.Count(response => response.StatusCode == System.Net.HttpStatusCode.OK).ShouldBe(1); responses.Count(response => response.StatusCode == System.Net.HttpStatusCode.Conflict).ShouldBe(2); } [Fact] public async Task Login_ValidCredentials_ReturnsOk() { await EnsureAdminCreatedAsync(); var email = _adminEmail; 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 EnsureAdminCreatedAsync(); var email = _adminEmail; 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); }