using System.Net; using FluentAssertions; using FsCheck; using FsCheck.Fluent; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NSubstitute; using SlpModularCms.Core.Data; using SlpModularCms.Core.Email; using SlpModularCms.Core.Hosting; using SlpModularCms.Core.Identity.Authorization; using SlpModularCms.Core.Identity.Entities; using SlpModularCms.Core.Identity.Models; using SlpModularCms.Core.Identity.Services; using Xunit.Abstractions; namespace SlpModularCms.Core.Tests.Identity; internal sealed class FakeTime(DateTimeOffset start) : TimeProvider { private DateTimeOffset _now = start; public override DateTimeOffset GetUtcNow() => _now; public void Advance(TimeSpan by) => _now += by; } /// /// The reset flow end to end with real Identity, real data-protection tokens and the real bearer check. /// The rule under test (Bryan): REQUESTING a reset touches nothing; only a COMPLETED reset ends sessions. /// public class PasswordResetFlowTests : IAsyncLifetime { private static readonly JwtSettings Jwt = new() { Secret = "a-test-secret-that-is-long-enough-for-hmac-sha256-0123456789", Issuer = "test-issuer", Audience = "test-audience", ExpiryMinutes = 30 }; private readonly string _dbName = Guid.NewGuid().ToString(); private readonly FakeTime _time = new(DateTimeOffset.UtcNow); private readonly IIdentityMailService _mail = Substitute.For(); private readonly List<(Guid UserId, string Token)> _sentTokens = []; private readonly TimeSpan _tokenLifespan = TimeSpan.FromMinutes(60); private bool _mailEnabled = true; private IHost _host = null!; private HttpClient _client = null!; private Guid _ownerId; public async Task InitializeAsync() { _mail.IsEnabled.Returns(_ => _mailEnabled); _mail.SendPasswordResetAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(ci => { _sentTokens.Add((ci.Arg().Id, ci.Arg())); return Task.FromResult(MailSendResult.Ok); }); _host = await new HostBuilder().ConfigureWebHost(web => { web.UseTestServer(); web.ConfigureServices(services => { services.AddLogging(); services.AddRouting(); services.AddDataProtection(); services.AddDbContext(o => o.UseInMemoryDatabase(_dbName)); services.AddIdentityCore() .AddRoles() .AddEntityFrameworkStores() .AddDefaultTokenProviders(); services.Configure(o => o.TokenLifespan = _tokenLifespan); services.Configure(o => { o.Secret = Jwt.Secret; o.Issuer = Jwt.Issuer; o.Audience = Jwt.Audience; o.ExpiryMinutes = Jwt.ExpiryMinutes; }); services.AddScoped(); services.AddSingleton(_mail); services.AddSingleton(_time); services.AddSingleton(sp => new ResetCooldown(sp.GetRequiredService(), TimeSpan.FromMinutes(5))); services.AddScoped(); services.AddAuthentication("Bearer").AddJwtBearer(o => o.UseCmsTokenValidation(JwtTokenValidation.Create(Jwt))); services.AddAuthorization(); }); web.Configure(app => { app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(e => e.MapGet("/data", () => Results.Ok("secret")).RequireAuthorization()); }); }).StartAsync(); _client = _host.GetTestClient(); using var scope = _host.Services.CreateScope(); var users = scope.ServiceProvider.GetRequiredService>(); var owner = new ApplicationUser { UserName = "owner@test.nl", Email = "owner@test.nl", IsActive = true, DisplayName = "Owner" }; (await users.CreateAsync(owner, "Password1!")).Succeeded.Should().BeTrue(); _ownerId = owner.Id; (await users.CreateAsync(new ApplicationUser { UserName = "off@test.nl", Email = "off@test.nl", IsActive = false }, "Password1!")).Succeeded.Should().BeTrue(); } public async Task DisposeAsync() { _client.Dispose(); await _host.StopAsync(); _host.Dispose(); } private async Task Scoped(Func> action) { using var scope = _host.Services.CreateScope(); return await action(scope.ServiceProvider); } private Task RequestAsync(string email) => Scoped(async sp => { await sp.GetRequiredService().RequestAsync(email); return 0; }); private Task ResetAsync(Guid userId, string token, string password) => Scoped(sp => sp.GetRequiredService().ResetAsync(userId, token, password)); private async Task GetAsync(string accessToken) { using var request = new HttpRequestMessage(HttpMethod.Get, "/data"); request.Headers.Authorization = new("Bearer", accessToken); return (await _client.SendAsync(request)).StatusCode; } private Task LoginAsync(string password = "Password1!") => Scoped(sp => sp.GetRequiredService().AuthenticateAsync("owner@test.nl", password)); private async Task<(string Hash, string Stamp, int ActiveRefreshTokens)> SnapshotAsync() { using var scope = _host.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.AsNoTracking().SingleAsync(u => u.Id == _ownerId); var active = await db.RefreshTokens.CountAsync(t => t.UserId == _ownerId && !t.IsRevoked); return (user.PasswordHash!, user.SecurityStamp!, active); } // ---- the rule: a REQUEST changes nothing [Fact] public async Task ARequest_LeavesPasswordStampAndEverySessionUntouched() { var login = await LoginAsync(); var before = await SnapshotAsync(); await RequestAsync("owner@test.nl"); _sentTokens.Should().ContainSingle(); (await SnapshotAsync()).Should().Be(before); (await GetAsync(login.AccessToken)).Should().Be(HttpStatusCode.OK); // access token still works var refreshed = await Scoped(sp => sp.GetRequiredService().RefreshTokenAsync(login.RefreshToken)); (await GetAsync(refreshed.AccessToken)).Should().Be(HttpStatusCode.OK); // refresh token still works (await LoginAsync()).AccessToken.Should().NotBeNullOrEmpty(); // old password still works } // ---- a COMPLETED reset ends sessions [Fact] public async Task ACompletedReset_SetsTheNewPassword_AndEndsEverySession() { var login = await LoginAsync(); await RequestAsync("owner@test.nl"); var (userId, token) = _sentTokens.Single(); var result = await ResetAsync(userId, token, "Brand-New-Pass9!"); result.Status.Should().Be(PasswordResetStatus.Succeeded); (await GetAsync(login.AccessToken)).Should().Be(HttpStatusCode.Unauthorized); // earlier access token ends (stamp) var refresh = () => Scoped(sp => sp.GetRequiredService().RefreshTokenAsync(login.RefreshToken)); await refresh.Should().ThrowAsync(); // refresh token revoked (await SnapshotAsync()).ActiveRefreshTokens.Should().Be(0); var oldPassword = () => LoginAsync("Password1!"); await oldPassword.Should().ThrowAsync(); (await GetAsync((await LoginAsync("Brand-New-Pass9!")).AccessToken)).Should().Be(HttpStatusCode.OK); } [Fact] public async Task TheResetLink_WorksOnce() { await RequestAsync("owner@test.nl"); var (userId, token) = _sentTokens.Single(); (await ResetAsync(userId, token, "Brand-New-Pass9!")).Status.Should().Be(PasswordResetStatus.Succeeded); (await ResetAsync(userId, token, "Another-Pass8!")).Status.Should().Be(PasswordResetStatus.InvalidLink); (await LoginAsync("Brand-New-Pass9!")).AccessToken.Should().NotBeNullOrEmpty(); } [Fact] public async Task AnExpiredLink_IsRefused_AsInvalid() { // The provider reads the (singleton) option when it checks a token, so shortening it here applies. _host.Services.GetRequiredService>().Value.TokenLifespan = TimeSpan.FromMilliseconds(1); await RequestAsync("owner@test.nl"); var (userId, token) = _sentTokens.Single(); await Task.Delay(100); (await ResetAsync(userId, token, "Brand-New-Pass9!")).Status.Should().Be(PasswordResetStatus.InvalidLink); (await SnapshotAsync()).Hash.Should().NotBeNullOrEmpty(); (await LoginAsync()).AccessToken.Should().NotBeNullOrEmpty(); // password unchanged } [Fact] public async Task ATokenOfAnotherUser_OrAGarbageToken_IsRefused() { using (var scope = _host.Services.CreateScope()) { var users = scope.ServiceProvider.GetRequiredService>(); (await users.CreateAsync(new ApplicationUser { UserName = "b@test.nl", Email = "b@test.nl", IsActive = true }, "Password1!")).Succeeded.Should().BeTrue(); } await RequestAsync("b@test.nl"); var (otherId, otherToken) = _sentTokens.Single(); (await ResetAsync(_ownerId, otherToken, "Brand-New-Pass9!")).Status.Should().Be(PasswordResetStatus.InvalidLink); (await ResetAsync(_ownerId, "garbage", "Brand-New-Pass9!")).Status.Should().Be(PasswordResetStatus.InvalidLink); (await ResetAsync(Guid.NewGuid(), otherToken, "Brand-New-Pass9!")).Status.Should().Be(PasswordResetStatus.InvalidLink); otherId.Should().NotBe(_ownerId); } [Fact] public async Task AWeakPassword_IsReported_WithoutUsingUpTheLink() { await RequestAsync("owner@test.nl"); var (userId, token) = _sentTokens.Single(); var weak = await ResetAsync(userId, token, "short"); weak.Status.Should().Be(PasswordResetStatus.PasswordRejected); weak.Problems.Should().NotBeEmpty(); (await ResetAsync(userId, token, "Brand-New-Pass9!")).Status.Should().Be(PasswordResetStatus.Succeeded); } // ---- nothing is revealed, nothing is sent when it should not be [Theory] [InlineData("nobody@test.nl")] // unknown [InlineData("off@test.nl")] // deactivated [InlineData("")] // blank public async Task UnknownDeactivatedOrBlankAddresses_SendNothing_AndDoNotThrow(string email) { await RequestAsync(email); _sentTokens.Should().BeEmpty(); } [Fact] public async Task OnASiteWithoutMail_NothingHappens() { _mailEnabled = false; await RequestAsync("owner@test.nl"); _sentTokens.Should().BeEmpty(); } [Fact] public async Task ADeactivatedAccount_CannotCompleteAReset() { await RequestAsync("owner@test.nl"); var (userId, token) = _sentTokens.Single(); using (var scope = _host.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); (await db.Users.SingleAsync(u => u.Id == userId)).IsActive = false; await db.SaveChangesAsync(); } (await ResetAsync(userId, token, "Brand-New-Pass9!")).Status.Should().Be(PasswordResetStatus.InvalidLink); } // ---- cooldown [Fact] public async Task OneMailPerAddressPerWindow_ExtraRequestsAreIgnored_ThenItWorksAgain() { await RequestAsync("owner@test.nl"); await RequestAsync("OWNER@test.nl"); // same address, other case _time.Advance(TimeSpan.FromMinutes(4)); await RequestAsync("owner@test.nl"); _sentTokens.Should().HaveCount(1); _time.Advance(TimeSpan.FromMinutes(2)); // 6 minutes after the first await RequestAsync("owner@test.nl"); _sentTokens.Should().HaveCount(2); } [Fact] public async Task TheCooldownAppliesToUnknownAddressesToo_SoTheOutcomeDoesNotDependOnTheAccount() { await RequestAsync("nobody@test.nl"); await RequestAsync("nobody@test.nl"); _sentTokens.Should().BeEmpty(); } } public class ResetCooldownTests(ITestOutputHelper output) { [Fact] public void FirstRequestPasses_ASecondWithinTheWindowDoesNot_AfterTheWindowItDoes() { var time = new FakeTime(DateTimeOffset.UtcNow); var cooldown = new ResetCooldown(time, TimeSpan.FromMinutes(5)); cooldown.TryEnter("a@b.nl").Should().BeTrue(); cooldown.TryEnter("a@b.nl").Should().BeFalse(); cooldown.TryEnter("c@d.nl").Should().BeTrue(); // another address is independent time.Advance(TimeSpan.FromMinutes(5)); cooldown.TryEnter("a@b.nl").Should().BeTrue(); } [Fact] public void Memory_IsBounded_ExpiredEntriesArePurged_AndWhenFullNewAddressesAreRefused() { var time = new FakeTime(DateTimeOffset.UtcNow); var cooldown = new ResetCooldown(time, TimeSpan.FromMinutes(5), capacity: 3); cooldown.TryEnter("1@x.nl").Should().BeTrue(); cooldown.TryEnter("2@x.nl").Should().BeTrue(); cooldown.TryEnter("3@x.nl").Should().BeTrue(); cooldown.TryEnter("4@x.nl").Should().BeFalse(); // full: refused, never grows past the cap cooldown.Count.Should().Be(3); time.Advance(TimeSpan.FromMinutes(6)); // everything expired cooldown.TryEnter("4@x.nl").Should().BeTrue(); cooldown.Count.Should().BeLessThanOrEqualTo(3); } // PBT-03: for any sequence of requests over time, two accepted requests for one address are never closer than the window. [Fact] public void Property_TwoAcceptedRequestsForOneAddress_AreNeverCloserThanTheWindow() { var steps = Gen.Choose(0, 400).Select(s => TimeSpan.FromSeconds(s)); var request = Gen.Elements("a@x.nl", "b@x.nl", "c@x.nl").Zip(steps); Prop.ForAll(request.ArrayOf().ToArbitrary(), seq => { var time = new FakeTime(DateTimeOffset.UtcNow); var window = TimeSpan.FromMinutes(5); var cooldown = new ResetCooldown(time, window); var lastAccepted = new Dictionary(); foreach (var (address, delta) in seq) { time.Advance(delta); if (!cooldown.TryEnter(address)) continue; if (lastAccepted.TryGetValue(address, out var previous) && time.GetUtcNow() - previous < window) return false; lastAccepted[address] = time.GetUtcNow(); } return true; }).Check(Config.QuickThrowOnFailure.WithMaxTest(1500)); output.WriteLine("Property held for 1500 generated request sequences."); } [Fact] public void Settings_AreValidatedWithinTheirRanges() { PasswordResetSettings.IsValid(new PasswordResetSettings()).Should().BeTrue(); PasswordResetSettings.IsValid(new PasswordResetSettings { TokenLifetimeMinutes = 4 }).Should().BeFalse(); PasswordResetSettings.IsValid(new PasswordResetSettings { TokenLifetimeMinutes = 1441 }).Should().BeFalse(); PasswordResetSettings.IsValid(new PasswordResetSettings { CooldownMinutes = 0 }).Should().BeFalse(); PasswordResetSettings.IsValid(new PasswordResetSettings { CooldownMinutes = 61 }).Should().BeFalse(); } }