using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using Heimdall.Application.Auth.Services; using Heimdall.Application.DTOs; using Heimdall.Application.Users.Commands.AssignRoles; using Heimdall.Application.Users.Commands.LockUser; using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Data; using Heimdall.IntegrationTests.Factories; using MediatR; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Heimdall.Infrastructure.Identity; namespace Heimdall.IntegrationTests.Controllers; [Collection("Postgres")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "xUnit invokes IAsyncLifetime.DisposeAsync to dispose the client and application factory.")] public sealed class AuthSessionSecurityTests(PostgreSqlContainerFixture postgres) : IAsyncLifetime { private HeimdallWebApplicationFactory _factory = null!; private HttpClient _client = null!; private readonly string _email = $"auth-{Guid.NewGuid():N}@example.test"; private Guid _userId; private const string Password = "Correct-password-123!"; public async Task InitializeAsync() { _factory = new HeimdallWebApplicationFactory(postgres.ConnectionString); _client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, HandleCookies = false }); using var scope = _factory.Services.CreateScope(); var users = scope.ServiceProvider.GetRequiredService>(); var user = new IdentityAppUser { Id = Guid.NewGuid(), Email = _email, UserName = _email, EmailConfirmed = true }; (await users.CreateAsync(user, Password)).Succeeded.ShouldBeTrue(); (await users.AddToRoleAsync(user, "Viewer")).Succeeded.ShouldBeTrue(); _userId = user.Id; } public async Task DisposeAsync() { _client.Dispose(); await _factory.DisposeAsync(); } private async Task LoginAsync() { var response = await _client.PostAsJsonAsync("/api/auth/login", new { email = _email, password = Password }); response.StatusCode.ShouldBe(HttpStatusCode.OK); response.Headers.Contains("Set-Cookie").ShouldBeFalse(); return (await response.Content.ReadFromJsonAsync())!; } [Fact] public async Task Http_2fa_requires_password_challenge_and_rejects_replay() { var code = "ABCDE"; using (var scope = _factory.Services.CreateScope()) { var users = scope.ServiceProvider.GetRequiredService>(); var user = (await users.FindByIdAsync(_userId.ToString()))!; await users.ResetAuthenticatorKeyAsync(user); await users.SetTwoFactorEnabledAsync(user, true); var db = scope.ServiceProvider.GetRequiredService(); db.UserRecoveryCodes.Add(new UserRecoveryCode(_userId, RecoveryCodeService.Hash(code))); await db.SaveChangesAsync(); } var bypass = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { email = _email, code }); bypass.IsSuccessStatusCode.ShouldBeFalse(); var challenge = await LoginAsync(); challenge.Requires2fa.ShouldBeTrue(); challenge.AccessToken.ShouldBeEmpty(); var response = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code }); response.StatusCode.ShouldBe(HttpStatusCode.OK); (await response.Content.ReadFromJsonAsync())!.AccessToken.ShouldNotBeNullOrEmpty(); var replay = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code }); replay.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } [Theory] [InlineData("lock")] [InlineData("roles")] [InlineData("password")] [InlineData("email")] public async Task Existing_jwt_cookie_and_refresh_are_revoked_by_account_change(string change) { var auth = await LoginAsync(); var signin = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = auth.AccessToken }); signin.StatusCode.ShouldBe(HttpStatusCode.OK); var cookie = signin.Headers.GetValues("Set-Cookie").Single(x => x.StartsWith(".Heimdall.Auth=", StringComparison.Ordinal)).Split(';')[0]; using (var scope = _factory.Services.CreateScope()) { var sender = scope.ServiceProvider.GetRequiredService(); if (change == "lock") (await sender.Send(new LockUserCommand(_userId))).IsSuccess.ShouldBeTrue(); else if (change == "roles") (await sender.Send(new AssignRolesCommand(_userId, ["Supervisor"]))).IsSuccess.ShouldBeTrue(); else { var users = scope.ServiceProvider.GetRequiredService>(); var user = (await users.FindByIdAsync(_userId.ToString()))!; if (change == "email") { var update = await users.SetEmailAsync(user, $"changed-{_email}"); update.Succeeded.ShouldBeTrue(); await users.UpdateSecurityStampAsync(user); } else { var token = await users.GeneratePasswordResetTokenAsync(user); var reset = await users.ResetPasswordAsync(user, token, "Changed-password-123!"); reset.Succeeded.ShouldBeTrue(); await users.UpdateSecurityStampAsync(user); } } } var refresh = await _client.PostAsJsonAsync("/api/auth/refresh", new { refreshToken = auth.RefreshToken }); refresh.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); var bearer = new HttpRequestMessage(HttpMethod.Get, "/api/users/me"); bearer.Headers.Authorization = new AuthenticationHeaderValue("Bearer", auth.AccessToken); (await _client.SendAsync(bearer)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); var withCookie = new HttpRequestMessage(HttpMethod.Get, "/api/users/me"); withCookie.Headers.Add("Cookie", cookie); (await _client.SendAsync(withCookie)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); (await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = auth.AccessToken })).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } }