using System.Buffers.Binary; using System.Security.Cryptography; using Heimdall.Application.Auth.Commands.Login; using Heimdall.Application.Auth.Commands.Complete2faSetup; using Heimdall.Application.Auth.Commands.Verify2fa; using Heimdall.Application.Auth.Commands.RefreshToken; using Heimdall.Application.Auth.Services; using Heimdall.Application.Common.Persistence; using Heimdall.Application.Services; using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Data.Interceptors; using Heimdall.Infrastructure.Security; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; using Shouldly; using Heimdall.Infrastructure.Identity; namespace Heimdall.Infrastructure.Tests; public sealed class PasswordChallengeIdentityTests : IAsyncLifetime { private readonly string _path = Path.Combine(Path.GetTempPath(), $"heimdall-auth-{Guid.NewGuid()}.db"); private ServiceProvider _services = null!; private readonly string _email = "identity@example.test"; private const string Password = "Correct-password-123!"; public async Task InitializeAsync() { var services = new ServiceCollection(); services.AddLogging(); services.AddDbContext(o => o.UseSqlite($"Data Source={_path}")); services.AddSingleton(new AuditInterceptor()); services.AddIdentity(o => { o.Lockout.MaxFailedAccessAttempts = 5; }) .AddEntityFrameworkStores().AddDefaultTokenProviders(); services.AddScoped(); var accessor = Substitute.For(); accessor.HttpContext.Returns(new DefaultHttpContext()); services.AddSingleton(accessor); services.AddSingleton(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { ["Jwt:Key"] = new string('a', 64), ["Jwt:RefreshKey"] = new string('b', 64) }).Build()); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(_ => { var permissions = Substitute.For(); permissions.GetPermissionsForRolesAsync(Arg.Any>(), Arg.Any()) .Returns(Task.FromResult>([])); return permissions; }); _services = services.BuildServiceProvider(); using var scope = _services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await db.Database.EnsureCreatedAsync(); 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.ResetAuthenticatorKeyAsync(user); await users.SetTwoFactorEnabledAsync(user, true); } public async Task DisposeAsync() { await _services.DisposeAsync(); SqliteConnection.ClearAllPools(); File.Delete(_path); } private static LoginHandler Login(IServiceProvider s) { s.GetRequiredService().HttpContext!.RequestServices = s; return new( s.GetRequiredService(), s.GetRequiredService(), s.GetRequiredService(), s.GetRequiredService(), Substitute.For(), s.GetRequiredService(), NullLogger.Instance, s.GetRequiredService()); } private static IdentityAccount ToAccount(IdentityAppUser user) => new() { Id = user.Id, UserName = user.UserName, Email = user.Email, DisplayName = user.DisplayName, EmailConfirmed = user.EmailConfirmed, SecurityStamp = user.SecurityStamp, LockoutEnabled = user.LockoutEnabled, LockoutEnd = user.LockoutEnd, AccessFailedCount = user.AccessFailedCount, TwoFactorEnabled = user.TwoFactorEnabled, Language = user.Language, Theme = user.Theme, CreatedAt = user.CreatedAt }; private static Verify2faHandler Verify(IServiceProvider s) => new( s.GetRequiredService(), s.GetRequiredService(), s.GetRequiredService(), s.GetRequiredService(), NullLogger.Instance); [Fact] public async Task Authenticator_setup_requires_valid_totp_before_enabling_or_issuing_recovery_codes() { using var scope = _services.CreateScope(); var services = scope.ServiceProvider; var users = services.GetRequiredService>(); var db = services.GetRequiredService(); var user = (await users.FindByEmailAsync(_email))!; await users.SetTwoFactorEnabledAsync(user, false); await users.ResetAuthenticatorKeyAsync(user); var handler = new Complete2faSetupHandler(services.GetRequiredService(), db, NullLogger.Instance); var invalid = await handler.Handle(new(user.Id, "000000"), default); invalid.IsSuccess.ShouldBeFalse(); (await users.GetTwoFactorEnabledAsync(user)).ShouldBeFalse(); (await db.UserRecoveryCodes.CountAsync(x => x.UserId == user.Id)).ShouldBe(0); var key = (await users.GetAuthenticatorKeyAsync(user))!; var code = GenerateTotp(key); (await users.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, code)).ShouldBeTrue(); var completed = await handler.Handle(new(user.Id, code), default); completed.IsSuccess.ShouldBeTrue(completed.Error); completed.Data!.RecoveryCodes.Count.ShouldBe(10); (await users.GetTwoFactorEnabledAsync(user)).ShouldBeTrue(); var stored = await db.UserRecoveryCodes.Where(x => x.UserId == user.Id).ToListAsync(); stored.Count.ShouldBe(10); stored.ShouldAllBe(x => x.CodeHash.Length == 64 && !completed.Data.RecoveryCodes.Contains(x.CodeHash)); } // RFC 6238 authenticator codes used by ASP.NET Core Identity use HMAC-SHA1. #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 ch in base32Key.TrimEnd('=')) { buffer = (buffer << 5) | alphabet.IndexOf(ch); bits += 5; if (bits >= 8) { bits -= 8; key.Add((byte)(buffer >> bits)); } } var counter = DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30; Span message = stackalloc byte[8]; BinaryPrimitives.WriteInt64BigEndian(message, counter); 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 private async Task ChallengeAsync() { using var scope = _services.CreateScope(); var result = await Login(scope.ServiceProvider).Handle(new(_email, Password), default); result.IsSuccess.ShouldBeTrue(); result.Data!.Requires2fa.ShouldBeTrue(); result.Data.AccessToken.ShouldBeEmpty(); result.Data.ChallengeId.ShouldNotBeNull(); return result.Data.ChallengeId!; } private async Task RecoveryAsync() { using var scope = _services.CreateScope(); var s = scope.ServiceProvider; var user = await s.GetRequiredService>().FindByEmailAsync(_email); var code = Guid.NewGuid().ToString("N"); var db = s.GetRequiredService(); db.UserRecoveryCodes.Add(new UserRecoveryCode(user!.Id, RecoveryCodeService.Hash(code))); await db.SaveChangesAsync(); return code; } [Fact] public async Task Real_authenticator_totp_completes_password_challenge_once() { var challenge = await ChallengeAsync(); string key; using (var scope = _services.CreateScope()) { var users = scope.ServiceProvider.GetRequiredService>(); key = (await users.GetAuthenticatorKeyAsync((await users.FindByEmailAsync(_email))!))!; } var bits = string.Concat(key.TrimEnd('=').Select(c => Convert.ToString("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".IndexOf(c, StringComparison.Ordinal), 2).PadLeft(5, '0'))); var secret = Enumerable.Range(0, bits.Length / 8).Select(i => Convert.ToByte(bits.Substring(i * 8, 8), 2)).ToArray(); var counter = BitConverter.GetBytes(DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30); if (BitConverter.IsLittleEndian) Array.Reverse(counter); #pragma warning disable CA5350 // RFC 6238 / Identity authenticator protocol requires HMAC-SHA1. var hash = System.Security.Cryptography.HMACSHA1.HashData(secret, counter); #pragma warning restore CA5350 var offset = hash[^1] & 15; var number = ((hash[offset] & 127) << 24) | (hash[offset + 1] << 16) | (hash[offset + 2] << 8) | hash[offset + 3]; var code = (number % 1000000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture); using (var scope = _services.CreateScope()) (await Verify(scope.ServiceProvider).Handle(new(challenge, code), default)).IsSuccess.ShouldBeTrue(); using (var scope = _services.CreateScope()) (await Verify(scope.ServiceProvider).Handle(new(challenge, code), default)).StatusCode.ShouldBe(401); } [Theory] [InlineData("locked")] [InlineData("email")] [InlineData("stamp")] public async Task Refresh_revalidates_account(string mode) { var challenge = await ChallengeAsync(); var code = await RecoveryAsync(); string refresh; using (var scope = _services.CreateScope()) refresh = (await Verify(scope.ServiceProvider).Handle(new(challenge, code), default)).Data!.RefreshToken; using (var scope = _services.CreateScope()) { var s = scope.ServiceProvider; var users = s.GetRequiredService>(); var user = (await users.FindByEmailAsync(_email))!; if (mode == "locked") await users.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddMinutes(5)); if (mode == "stamp") await users.UpdateSecurityStampAsync(user); if (mode == "email") { user.EmailConfirmed = false; await users.UpdateAsync(user); await s.GetRequiredService().SetSettingValueAsync("email.confirmation.required", "true", "Auth", null, default); } } using var verify = _services.CreateScope(); var sp = verify.ServiceProvider; var handler = new RefreshTokenHandler(sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), NullLogger.Instance); (await handler.Handle(new(refresh), default)).StatusCode.ShouldBe(401); } [Fact] public async Task Refresh_preserves_absolute_session_deadline_and_rotates() { using var scope = _services.CreateScope(); var sp = scope.ServiceProvider; var user = (await sp.GetRequiredService>().FindByEmailAsync(_email))!; var started = DateTime.UtcNow.AddDays(-6); var jwt = sp.GetRequiredService(); var token = jwt.GenerateRefreshToken(ToAccount(user), started).token; var handler = new RefreshTokenHandler(jwt, sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), NullLogger.Instance); var result = await handler.Handle(new(token), default); result.IsSuccess.ShouldBeTrue(); var parsed = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().ReadJwtToken(result.Data!.RefreshToken); Math.Abs((parsed.ValidTo - started.AddDays(7)).TotalSeconds).ShouldBeLessThan(2); (await handler.Handle(new(token), default)).StatusCode.ShouldBe(401); } [Fact] public async Task Password_check_does_not_emit_cookie_and_requires_real_password() { using var scope = _services.CreateScope(); var s = scope.ServiceProvider; (await Login(s).Handle(new(_email, "wrong"), default)).StatusCode.ShouldBe(401); (await Login(s).Handle(new(_email, Password), default)).Data!.Requires2fa.ShouldBeTrue(); s.GetRequiredService().HttpContext!.Response.Headers.ContainsKey("Set-Cookie").ShouldBeFalse(); } [Fact] public async Task Login_without_2fa_issues_tokens_with_real_identity() { using var scope = _services.CreateScope(); var s = scope.ServiceProvider; var users = s.GetRequiredService>(); await users.SetTwoFactorEnabledAsync((await users.FindByEmailAsync(_email))!, false); var result = await Login(s).Handle(new(_email, Password), default); result.IsSuccess.ShouldBeTrue(); result.Data!.Requires2fa.ShouldBeFalse(); result.Data.AccessToken.ShouldNotBeNullOrEmpty(); } [Fact] public async Task Recovery_and_challenge_are_single_use_across_scopes() { var challenge = await ChallengeAsync(); var code = await RecoveryAsync(); using (var scope = _services.CreateScope()) (await Verify(scope.ServiceProvider).Handle(new(challenge, code), default)).IsSuccess.ShouldBeTrue(); using (var scope = _services.CreateScope()) (await Verify(scope.ServiceProvider).Handle(new(challenge, code), default)).StatusCode.ShouldBe(401); var another = await ChallengeAsync(); using (var scope = _services.CreateScope()) (await Verify(scope.ServiceProvider).Handle(new(another, code), default)).StatusCode.ShouldBe(401); } [Theory] [InlineData("expired")] [InlineData("locked")] [InlineData("disabled")] [InlineData("email")] [InlineData("password")] public async Task Challenge_rechecks_account_and_expiration(string mode) { var challenge = await ChallengeAsync(); var code = await RecoveryAsync(); using (var scope = _services.CreateScope()) { var s = scope.ServiceProvider; var users = s.GetRequiredService>(); var user = (await users.FindByEmailAsync(_email))!; var db = s.GetRequiredService(); if (mode == "expired") await db.Set().ExecuteUpdateAsync(x => x.SetProperty(c => c.ExpiresAt, DateTime.UtcNow.AddSeconds(-1))); if (mode == "locked") await users.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddMinutes(10)); if (mode == "disabled") await users.SetTwoFactorEnabledAsync(user, false); if (mode == "password") await users.ChangePasswordAsync(user, Password, "New-password-123!"); if (mode == "email") { user.EmailConfirmed = false; await users.UpdateAsync(user); db.AppSettings.Add(new AppSetting("email.confirmation.required", "true")); await db.SaveChangesAsync(); } } using var verify = _services.CreateScope(); (await Verify(verify.ServiceProvider).Handle(new(challenge, code), default)).StatusCode.ShouldBe(401); } [Fact] public async Task Five_invalid_attempts_exhaust_challenge_and_lock_identity() { var challenge = await ChallengeAsync(); for (var i = 0; i < 5; i++) { using var scope = _services.CreateScope(); (await Verify(scope.ServiceProvider).Handle(new(challenge, "invalid"), default)).StatusCode.ShouldBe(401); } using var last = _services.CreateScope(); var users = last.ServiceProvider.GetRequiredService>(); (await users.IsLockedOutAsync((await users.FindByEmailAsync(_email))!)).ShouldBeTrue(); (await Verify(last.ServiceProvider).Handle(new(challenge, await RecoveryAsync()), default)).StatusCode.ShouldBe(401); } [Fact] public async Task Concurrent_recovery_redemption_allows_only_one_session() { var challenges = new[] { await ChallengeAsync(), await ChallengeAsync() }; var code = await RecoveryAsync(); var results = await Task.WhenAll(challenges.Select(challenge => Task.Run(async () => { using var scope = _services.CreateScope(); return await Verify(scope.ServiceProvider).Handle(new(challenge, code), default); }))); results.Count(x => x.IsSuccess).ShouldBe(1); } }