using System.Buffers.Binary; using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Security.Cryptography; 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); var verifiedSession = (await response.Content.ReadFromJsonAsync())!; verifiedSession.AccessToken.ShouldNotBeNullOrEmpty(); var cookieResponse = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = verifiedSession.AccessToken }); cookieResponse.StatusCode.ShouldBe(HttpStatusCode.OK); await AssertCookieSessionAsync(cookieResponse); var replay = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code }); replay.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } [Fact] public async Task Authenticator_2fa_success_emits_token_accepted_by_cookie_signin() { string code; using (var scope = _factory.Services.CreateScope()) { var users = scope.ServiceProvider.GetRequiredService>(); var user = (await users.FindByIdAsync(_userId.ToString()))!; (await users.ResetAuthenticatorKeyAsync(user)).Succeeded.ShouldBeTrue(); (await users.SetTwoFactorEnabledAsync(user, true)).Succeeded.ShouldBeTrue(); var key = await users.GetAuthenticatorKeyAsync(user); code = GenerateTotp(key!); (await users.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, code)).ShouldBeTrue(); } var challenge = await LoginAsync(); challenge.Requires2fa.ShouldBeTrue(); var verification = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code }); verification.StatusCode.ShouldBe(HttpStatusCode.OK, await verification.Content.ReadAsStringAsync()); var session = (await verification.Content.ReadFromJsonAsync())!; session.AccessToken.ShouldNotBeNullOrEmpty(); var cookieResponse = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = session.AccessToken }); cookieResponse.StatusCode.ShouldBe(HttpStatusCode.OK); await AssertCookieSessionAsync(cookieResponse); } [Fact] public async Task Cookie_signin_rejects_malformed_tokens_without_returning_validation_details() { var response = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = "not-a-jwt" }); response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); var body = await response.Content.ReadAsStringAsync(); body.ShouldNotContain("not-a-jwt"); body.ShouldNotContain("IDX"); } private async Task AssertCookieSessionAsync(HttpResponseMessage cookieResponse) { var cookie = cookieResponse.Headers.GetValues("Set-Cookie") .Single(value => value.StartsWith(".Heimdall.Auth=", StringComparison.Ordinal)).Split(';')[0]; var authenticatedRequest = new HttpRequestMessage(HttpMethod.Get, "/api/users/me"); authenticatedRequest.Headers.Add("Cookie", cookie); (await _client.SendAsync(authenticatedRequest)).StatusCode.ShouldBe(HttpStatusCode.OK); } #pragma warning disable CA5350 private static string GenerateTotp(string base32Key) { const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; var key = new List(); var buffer = 0; var bits = 0; foreach (var character in base32Key.TrimEnd('=')) { buffer = (buffer << 5) | alphabet.IndexOf(character); bits += 5; if (bits < 8) continue; bits -= 8; key.Add((byte)(buffer >> bits)); } Span message = stackalloc byte[8]; BinaryPrimitives.WriteInt64BigEndian(message, DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30); var hash = HMACSHA1.HashData(key.ToArray(), message); var offset = hash[^1] & 0x0f; var binary = ((hash[offset] & 0x7f) << 24) | (hash[offset + 1] << 16) | (hash[offset + 2] << 8) | hash[offset + 3]; return (binary % 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture); } #pragma warning restore CA5350 [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]; var validCookieRequest = new HttpRequestMessage(HttpMethod.Get, "/api/users/me"); validCookieRequest.Headers.Add("Cookie", cookie); (await _client.SendAsync(validCookieRequest)).StatusCode.ShouldBe(HttpStatusCode.OK); 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); } }