From c8e23826c35efbad50685e607de06ca73345be09 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Sun, 8 Nov 2026 19:21:29 +0100 Subject: [PATCH] U3 password-reset (backend): wachtwoord vergeten en opnieuw instellen POST auth/forgot-password antwoordt altijd hetzelfde (202) en handelt de mail na het antwoord af; POST auth/reset-password zet een nieuw wachtwoord met de link uit de mail. Alleen een voltooide reset trekt alle refresh tokens in (en beeindigt eerdere access tokens via de security stamp); het aanvragen raakt niets. Link eenmalig en tijdsbeperkt (standaard 60 minuten), cooldown van 5 minuten per adres in het geheugen, beide endpoints onder de login-limiter. Co-Authored-By: Claude Sonnet 5.5 --- .../Email/IdentityMailServiceTests.cs | 17 + .../Identity/PasswordResetDispatcherTests.cs | 58 +++ .../Identity/PasswordResetFlowTests.cs | 373 ++++++++++++++++++ .../PasswordResetRegistrationTests.cs | 65 +++ .../Email/IdentityMailService.cs | 11 + .../Hosting/ServiceCollectionExtensions.cs | 21 +- .../Identity/Models/IdentityRequests.cs | 2 + .../Identity/Services/PasswordReset.cs | 179 +++++++++ .../AuthControllerPasswordResetTests.cs | 115 ++++++ .../Controllers/AuthControllerTests.cs | 14 +- .../Controllers/AuthController.cs | 55 ++- 11 files changed, 901 insertions(+), 9 deletions(-) create mode 100644 src/SlpModularCms.Core.Tests/Identity/PasswordResetDispatcherTests.cs create mode 100644 src/SlpModularCms.Core.Tests/Identity/PasswordResetFlowTests.cs create mode 100644 src/SlpModularCms.Core.Tests/Identity/PasswordResetRegistrationTests.cs create mode 100644 src/SlpModularCms.Core/Identity/Services/PasswordReset.cs create mode 100644 src/SlpModularCms.Modules.Identity.Tests/Controllers/AuthControllerPasswordResetTests.cs diff --git a/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs b/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs index 8881441..872f737 100644 --- a/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs +++ b/src/SlpModularCms.Core.Tests/Email/IdentityMailServiceTests.cs @@ -38,6 +38,7 @@ public class IdentityMailServiceTests Options.Create(new EmailOptions { LogoUrl = logo, BrandColor = "#5f6a58", Smtp = { Host = smtpHost } }), Options.Create(new AppMailOptions { DefaultLanguage = defaultLanguage, PublicBaseUrl = "https://test.andreaslop.nl/" }), Options.Create(new InvitationSettings { ExpiryHours = hours }), + Options.Create(new SlpModularCms.Core.Identity.Services.PasswordResetSettings()), NullLogger.Instance); [Fact] @@ -163,4 +164,20 @@ public class IdentityMailServiceTests [InlineData("https://t.nl", "login", "https://t.nl/admin/login")] public void BuildLink_PutsTheAdminBasePathBetweenSiteAndPath(string baseUrl, string path, string expected) => IdentityMailService.BuildLink(baseUrl, path).Should().Be(expected); + + [Fact] + public async Task PasswordReset_LinksToTheResetPage_WithTheUserIdNotTheAddress_AndTheLifetime() + { + var user = new ApplicationUser { Id = Guid.Parse("11111111-2222-3333-4444-555555555555"), Email = "jan@example.org", DisplayName = "Jan", PreferredLanguage = "en" }; + + await Service().SendPasswordResetAsync(user, "to/ken+1="); + + var mail = _sender.Sent.Single(); + mail.Subject.Should().StartWith("Reset your password"); + mail.HtmlBody.Should().Contain("https://test.andreaslop.nl/admin/reset-password?uid=11111111-2222-3333-4444-555555555555&token=to%2Fken%2B1%3D"); + mail.TextBody.Should().Contain("https://test.andreaslop.nl/admin/reset-password?uid=11111111-2222-3333-4444-555555555555&token=to%2Fken%2B1%3D") + .And.Contain("1 hour").And.Contain("unchanged"); + // Nothing in the link identifies the account by its address. + mail.TextBody!.Split("https://", 2)[1].Split('\n', 2)[0].Should().NotContain("jan@example.org").And.NotContain("%40"); + } } diff --git a/src/SlpModularCms.Core.Tests/Identity/PasswordResetDispatcherTests.cs b/src/SlpModularCms.Core.Tests/Identity/PasswordResetDispatcherTests.cs new file mode 100644 index 0000000..9085839 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Identity/PasswordResetDispatcherTests.cs @@ -0,0 +1,58 @@ +using FluentAssertions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using SlpModularCms.Core.Identity.Services; + +namespace SlpModularCms.Core.Tests.Identity; + +public class PasswordResetDispatcherTests +{ + [Fact] + public async Task Dispatch_ReturnsAtOnce_AndTheRequestIsHandledInTheBackgroundInAScope() + { + var handled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var service = Substitute.For(); + var release = new ManualResetEventSlim(false); + service.RequestAsync(Arg.Any(), Arg.Any()).Returns(ci => + { + release.Wait(TimeSpan.FromSeconds(5)); // a slow mail: the caller must not wait for it + handled.TrySetResult(ci.Arg()); + return Task.CompletedTask; + }); + var services = new ServiceCollection(); + services.AddScoped(_ => service); + using var sp = services.BuildServiceProvider(); + var dispatcher = new BackgroundPasswordResetDispatcher(sp.GetRequiredService(), NullLogger.Instance); + + var started = DateTime.UtcNow; + dispatcher.Dispatch("a@example.org"); + (DateTime.UtcNow - started).Should().BeLessThan(TimeSpan.FromSeconds(1)); + handled.Task.IsCompleted.Should().BeFalse(); + + release.Set(); + (await handled.Task.WaitAsync(TimeSpan.FromSeconds(5))).Should().Be("a@example.org"); + } + + [Fact] + public async Task AFailingRequest_NeverSurfaces() + { + var called = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var service = Substitute.For(); + service.RequestAsync(Arg.Any(), Arg.Any()).Returns(ci => + { + called.TrySetResult(); + return Task.FromException(new InvalidOperationException("boom")); + }); + var services = new ServiceCollection(); + services.AddScoped(_ => service); + using var sp = services.BuildServiceProvider(); + var dispatcher = new BackgroundPasswordResetDispatcher(sp.GetRequiredService(), NullLogger.Instance); + + var act = () => dispatcher.Dispatch("a@example.org"); + + act.Should().NotThrow(); + await called.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } +} diff --git a/src/SlpModularCms.Core.Tests/Identity/PasswordResetFlowTests.cs b/src/SlpModularCms.Core.Tests/Identity/PasswordResetFlowTests.cs new file mode 100644 index 0000000..7e714fb --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Identity/PasswordResetFlowTests.cs @@ -0,0 +1,373 @@ +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(); + } +} diff --git a/src/SlpModularCms.Core.Tests/Identity/PasswordResetRegistrationTests.cs b/src/SlpModularCms.Core.Tests/Identity/PasswordResetRegistrationTests.cs new file mode 100644 index 0000000..68fa5c9 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Identity/PasswordResetRegistrationTests.cs @@ -0,0 +1,65 @@ +using FluentAssertions; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Identity.Services; + +namespace SlpModularCms.Core.Tests.Identity; + +public class PasswordResetRegistrationTests +{ + private static ServiceProvider Build(string? minutes) + { + var values = new Dictionary + { + ["JwtSettings:Secret"] = "a-test-secret-that-is-long-enough-for-hmac-sha256-0123456789", + ["JwtSettings:Issuer"] = "i", + ["JwtSettings:Audience"] = "a", + ["ConnectionStrings:DefaultConnection"] = "Server=localhost;Database=x;User=x;Password=x" + }; + if (minutes is not null) values["Identity:PasswordReset:TokenLifetimeMinutes"] = minutes; + var config = new ConfigurationBuilder().AddInMemoryCollection(values).Build(); + + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDataProtection(); + services.AddCoreInfrastructure(config); + return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + } + + [Fact] + public void TokenProvidersAndTheConfiguredLifetime_AreWiredUp() + { + using var sp = Build("30"); + + sp.GetRequiredService>().Value.TokenLifespan.Should().Be(TimeSpan.FromMinutes(30)); + sp.GetRequiredService>().Value.Tokens.ProviderMap.Should().ContainKey("Default"); + using var scope = sp.CreateScope(); + scope.ServiceProvider.GetRequiredService().Should().NotBeNull(); + sp.GetRequiredService().Should().NotBeNull(); + sp.GetRequiredService().Should().NotBeNull(); + } + + [Fact] + public void WithoutConfiguration_TheLinkLastsAnHour_AndTheCooldownIsFiveMinutes() + { + using var sp = Build(null); + + sp.GetRequiredService>().Value.TokenLifespan.Should().Be(TimeSpan.FromMinutes(60)); + sp.GetRequiredService>().Value.CooldownMinutes.Should().Be(5); + } + + [Theory] + [InlineData("4")] + [InlineData("1441")] + public void AnOutOfRangeLifetime_FailsStartup(string minutes) + { + using var sp = Build(minutes); + + var act = () => sp.GetRequiredService>().Value; + + act.Should().Throw().WithMessage("*TokenLifetimeMinutes*"); + } +} diff --git a/src/SlpModularCms.Core/Email/IdentityMailService.cs b/src/SlpModularCms.Core/Email/IdentityMailService.cs index cac782d..a49c853 100644 --- a/src/SlpModularCms.Core/Email/IdentityMailService.cs +++ b/src/SlpModularCms.Core/Email/IdentityMailService.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SlpModularCms.Core.Identity.Entities; using SlpModularCms.Core.Identity.Models; +using SlpModularCms.Core.Identity.Services; using SlpModularCms.Core.SiteSettings; namespace SlpModularCms.Core.Email; @@ -16,6 +17,7 @@ public interface IIdentityMailService bool IsEnabled { get; } Task SendInvitationAsync(string email, string token, string? language, bool isNewLink, CancellationToken ct = default); + Task SendPasswordResetAsync(ApplicationUser user, string token, CancellationToken ct = default); Task SendAccountDeactivatedAsync(ApplicationUser user, CancellationToken ct = default); Task SendAccountReactivatedAsync(ApplicationUser user, CancellationToken ct = default); Task SendRoleChangedAsync(ApplicationUser user, string newRole, CancellationToken ct = default); @@ -29,6 +31,7 @@ public sealed class IdentityMailService( IOptions email, IOptions app, IOptions invitation, + IOptions resetSettings, ILogger logger) : IIdentityMailService { public bool IsEnabled => !string.IsNullOrWhiteSpace(email.Value.Smtp.Host); @@ -44,6 +47,14 @@ public sealed class IdentityMailService( detail: null, ct); + /// The link carries the user id and the token (no e-mail address in a URL). + public Task SendPasswordResetAsync(ApplicationUser user, string token, CancellationToken ct = default) => + SendAsync( + MailKind.PasswordReset, user.Email, user.PreferredLanguage, user.DisplayName, + actionPath: "/reset-password?uid=" + user.Id + "&token=" + Uri.EscapeDataString(token), + validForMinutes: resetSettings.Value.TokenLifetimeMinutes, + detail: null, ct); + public Task SendAccountDeactivatedAsync(ApplicationUser user, CancellationToken ct = default) => SendAsync(MailKind.AccountDeactivated, user.Email, user.PreferredLanguage, user.DisplayName, null, null, null, ct); diff --git a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs index 57ef7d6..e824822 100644 --- a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs @@ -9,6 +9,8 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using SlpModularCms.Core.Availability; @@ -52,7 +54,9 @@ public static class ServiceCollectionExtensions }) .AddRoles() .AddRoleManager>() - .AddEntityFrameworkStores(); + .AddEntityFrameworkStores() + // Needed for the password-reset token (stateless, single use through the security stamp). + .AddDefaultTokenProviders(); // 3. Auth & Identity Services var jwtSettings = configuration.GetSection("JwtSettings").Get() @@ -67,6 +71,21 @@ public static class ServiceCollectionExtensions $"{InvitationSettings.SectionName}:ExpiryHours must be between 1 and {InvitationSettings.MaxExpiryHours}.") .ValidateOnStart(); + services.AddOptions() + .Bind(configuration.GetSection(PasswordResetSettings.SectionName)) + .Validate( + PasswordResetSettings.IsValid, + $"{PasswordResetSettings.SectionName}: TokenLifetimeMinutes must be 5..1440 and CooldownMinutes 1..60.") + .ValidateOnStart(); + // The reset link lifetime is the data-protection token lifetime. + services.AddOptions() + .Configure>((o, reset) => o.TokenLifespan = TimeSpan.FromMinutes(reset.Value.TokenLifetimeMinutes)); + services.TryAddSingleton(TimeProvider.System); + services.TryAddSingleton(sp => + new ResetCooldown(sp.GetRequiredService(), TimeSpan.FromMinutes(sp.GetRequiredService>().Value.CooldownMinutes))); + services.AddScoped(); + services.AddSingleton(); + services.AddCmsEmail(configuration); services.AddScoped(); diff --git a/src/SlpModularCms.Core/Identity/Models/IdentityRequests.cs b/src/SlpModularCms.Core/Identity/Models/IdentityRequests.cs index 80760e7..d5c7cfa 100644 --- a/src/SlpModularCms.Core/Identity/Models/IdentityRequests.cs +++ b/src/SlpModularCms.Core/Identity/Models/IdentityRequests.cs @@ -7,6 +7,8 @@ namespace SlpModularCms.Core.Identity.Models; [ExcludeFromCodeCoverage] public record InviteUserRequest(string Email, string Role, string? Language = null); [ExcludeFromCodeCoverage] public record CompleteSetupRequest(string Token, string Password, string? Name = null); [ExcludeFromCodeCoverage] public record ChangeRoleRequest(string NewRole); +[ExcludeFromCodeCoverage] public record ForgotPasswordRequest(string Email); +[ExcludeFromCodeCoverage] public record ResetPasswordRequest(Guid UserId, string Token, string NewPassword); [ExcludeFromCodeCoverage] public record UpdateProfileRequest(string Name, string Email, string? Language = null); [ExcludeFromCodeCoverage] public record ChangePasswordRequest(string CurrentPassword, string NewPassword); [ExcludeFromCodeCoverage] public record SetUserActiveRequest(bool IsActive); diff --git a/src/SlpModularCms.Core/Identity/Services/PasswordReset.cs b/src/SlpModularCms.Core/Identity/Services/PasswordReset.cs new file mode 100644 index 0000000..4b36414 --- /dev/null +++ b/src/SlpModularCms.Core/Identity/Services/PasswordReset.cs @@ -0,0 +1,179 @@ +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using SlpModularCms.Core.Data; +using SlpModularCms.Core.Email; +using SlpModularCms.Core.Identity.Entities; + +namespace SlpModularCms.Core.Identity.Services; + +/// Settings for "forgot password" (section Identity:PasswordReset). +[ExcludeFromCodeCoverage] +public sealed class PasswordResetSettings +{ + public const string SectionName = "Identity:PasswordReset"; + public const int DefaultTokenLifetimeMinutes = 60; + public const int DefaultCooldownMinutes = 5; + + /// How long a reset link works (5 to 1440 minutes). The link is single-use besides. + public int TokenLifetimeMinutes { get; set; } = DefaultTokenLifetimeMinutes; + + /// At most one reset mail per address per this many minutes (1 to 60); extra requests are ignored silently. + public int CooldownMinutes { get; set; } = DefaultCooldownMinutes; + + public static bool IsValid(PasswordResetSettings s) => + s.TokenLifetimeMinutes is >= 5 and <= 1440 && s.CooldownMinutes is >= 1 and <= 60; +} + +/// +/// One reset mail per address per window, in memory. Anonymous requests could otherwise be used to flood +/// somebody's inbox; the per-client rate limiter does not help against many client addresses. Memory is +/// bounded: expired entries are purged and, if the table is still full, new addresses are refused (the +/// caller treats that like the cooldown: silently, with the same response). +/// +public sealed class ResetCooldown(TimeProvider time, TimeSpan window, int capacity = 10_000) +{ + private readonly ConcurrentDictionary _last = new(); + + /// True when a mail may be sent for this address now (and it is recorded); false during the cooldown. + public bool TryEnter(string normalizedAddress) + { + var now = time.GetUtcNow(); + + if (_last.Count >= capacity) Purge(now); + if (_last.Count >= capacity && !_last.ContainsKey(normalizedAddress)) return false; + + var allowed = false; + _last.AddOrUpdate( + normalizedAddress, + _ => { allowed = true; return now; }, + (_, previous) => + { + if (now - previous >= window) { allowed = true; return now; } + return previous; + }); + return allowed; + } + + public int Count => _last.Count; + + private void Purge(DateTimeOffset now) + { + foreach (var (key, at) in _last) + { + if (now - at >= window) _last.TryRemove(key, out _); + } + } +} + +public enum PasswordResetStatus { Succeeded, InvalidLink, PasswordRejected } + +public sealed record PasswordResetResult(PasswordResetStatus Status, IReadOnlyList Problems) +{ + public static PasswordResetResult Success { get; } = new(PasswordResetStatus.Succeeded, []); + public static PasswordResetResult InvalidLink { get; } = new(PasswordResetStatus.InvalidLink, []); +} + +public interface IPasswordResetService +{ + /// + /// Sends a reset mail when the address belongs to an active account, mail is on and the cooldown allows + /// it. Changes nothing else: not the password, the security stamp, nor any session. Never throws and + /// reveals nothing about the address. + /// + Task RequestAsync(string email, CancellationToken ct = default); + + /// + /// Sets a new password with a valid token. Only a completed reset ends the account's sessions + /// (its refresh tokens are revoked here, its earlier access tokens end through the changed security + /// stamp). A bad, expired or already used token is one generic . + /// + Task ResetAsync(Guid userId, string token, string newPassword, CancellationToken ct = default); +} + +public sealed class PasswordResetService( + UserManager users, + ApplicationDbContext db, + IIdentityMailService mail, + ResetCooldown cooldown, + ILogger logger) : IPasswordResetService +{ + public async Task RequestAsync(string email, CancellationToken ct = default) + { + try + { + if (!mail.IsEnabled || string.IsNullOrWhiteSpace(email)) return; + + var address = email.Trim(); + // Unknown addresses enter the cooldown too, so the outcome does not depend on the account existing. + if (!cooldown.TryEnter(address.ToLowerInvariant())) + { + logger.LogInformation("password_reset_request_ignored reason=cooldown"); + return; + } + + var user = await users.FindByEmailAsync(address); + if (user is null || !user.IsActive) return; + + var token = await users.GeneratePasswordResetTokenAsync(user); + await mail.SendPasswordResetAsync(user, token, ct); + } + catch (Exception ex) + { + logger.LogWarning("password_reset_request_failed exception={ExceptionType}", ex.GetType().Name); + } + } + + public async Task ResetAsync(Guid userId, string token, string newPassword, CancellationToken ct = default) + { + var user = await users.FindByIdAsync(userId.ToString()); + if (user is null || !user.IsActive) return PasswordResetResult.InvalidLink; + + var result = await users.ResetPasswordAsync(user, token, newPassword); + if (!result.Succeeded) + { + // The token is checked before the password, so a policy complaint only reaches a holder of a valid link. + if (result.Errors.Any(e => e.Code == nameof(IdentityErrorDescriber.InvalidToken))) + return PasswordResetResult.InvalidLink; + return new PasswordResetResult(PasswordResetStatus.PasswordRejected, result.Errors.Select(e => e.Description).ToList()); + } + + // Completed reset: end every session of this account. Not done on a mere request. + var tokens = await db.RefreshTokens.Where(t => t.UserId == user.Id && !t.IsRevoked).ToListAsync(ct); + foreach (var t in tokens) t.IsRevoked = true; + await db.SaveChangesAsync(ct); + + logger.LogInformation("password_reset_completed"); + return PasswordResetResult.Success; + } +} + +/// +/// Starts a reset request without making the caller wait for it. The anonymous endpoint answers first, so +/// its response time does not tell whether the address exists (a mail takes longer than nothing). +/// +public interface IPasswordResetDispatcher +{ + void Dispatch(string email); +} + +public sealed class BackgroundPasswordResetDispatcher(IServiceScopeFactory scopes, ILogger logger) + : IPasswordResetDispatcher +{ + public void Dispatch(string email) => + _ = Task.Run(async () => + { + try + { + using var scope = scopes.CreateScope(); + await scope.ServiceProvider.GetRequiredService().RequestAsync(email); + } + catch (Exception ex) + { + logger.LogWarning("password_reset_dispatch_failed exception={ExceptionType}", ex.GetType().Name); + } + }); +} diff --git a/src/SlpModularCms.Modules.Identity.Tests/Controllers/AuthControllerPasswordResetTests.cs b/src/SlpModularCms.Modules.Identity.Tests/Controllers/AuthControllerPasswordResetTests.cs new file mode 100644 index 0000000..4bdf3bb --- /dev/null +++ b/src/SlpModularCms.Modules.Identity.Tests/Controllers/AuthControllerPasswordResetTests.cs @@ -0,0 +1,115 @@ +using System.Reflection; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Options; +using NSubstitute; +using SlpModularCms.Core.Email; +using SlpModularCms.Core.Identity.Models; +using SlpModularCms.Core.Identity.Services; +using SlpModularCms.Modules.Identity.Controllers; + +namespace SlpModularCms.Modules.Identity.Tests.Controllers; + +public class AuthControllerPasswordResetTests +{ + private readonly IPasswordResetService _service = Substitute.For(); + private readonly IPasswordResetDispatcher _dispatcher = Substitute.For(); + private readonly IIdentityMailService _mail = Substitute.For(); + + private AuthController Controller(bool mailEnabled = true) + { + _mail.IsEnabled.Returns(mailEnabled); + return new AuthController( + Substitute.For(), + Options.Create(new JwtSettings { Secret = "x", Issuer = "i", Audience = "a" }), + _service, _dispatcher, _mail); + } + + [Theory] + [InlineData(nameof(AuthController.ForgotPassword))] + [InlineData(nameof(AuthController.ResetPassword))] + public void BothEndpoints_AreAnonymous_AndUnderTheLoginRateLimiter(string method) + { + var info = typeof(AuthController).GetMethod(method)!; + + info.GetCustomAttribute().Should().NotBeNull(); + info.GetCustomAttribute()!.PolicyName.Should().Be("login"); + } + + [Fact] + public void Forgot_AnswersTheSame_ForAnyWellFormedAddress_AndHandsItToTheBackground() + { + var controller = Controller(); + + var known = controller.ForgotPassword(new ForgotPasswordRequest("known@example.org")); + var unknown = controller.ForgotPassword(new ForgotPasswordRequest("nobody@example.org")); + + known.Should().BeOfType(); + unknown.Should().BeOfType(); + ((AcceptedResult)known).Value.Should().BeEquivalentTo(((AcceptedResult)unknown).Value); + _dispatcher.Received(1).Dispatch("known@example.org"); + _dispatcher.Received(1).Dispatch("nobody@example.org"); + } + + [Theory] + [InlineData("")] + [InlineData("not-an-address")] + [InlineData("a@example.org\r\nBcc: x@y.nl")] + public void Forgot_RejectsAMalformedAddress_WithoutDispatching(string email) + { + Controller().ForgotPassword(new ForgotPasswordRequest(email)).Should().BeOfType(); + + _dispatcher.DidNotReceiveWithAnyArgs().Dispatch(default!); + } + + [Fact] + public async Task OnASiteWithoutMail_BothEndpointsAre404() + { + var controller = Controller(mailEnabled: false); + + controller.ForgotPassword(new ForgotPasswordRequest("a@example.org")).Should().BeOfType(); + (await controller.ResetPassword(new ResetPasswordRequest(Guid.NewGuid(), "t", "Password1!"), default)).Should().BeOfType(); + _dispatcher.DidNotReceiveWithAnyArgs().Dispatch(default!); + } + + [Fact] + public async Task Reset_MapsTheOutcomes() + { + var id = Guid.NewGuid(); + _service.ResetAsync(id, "ok", "Password1!", Arg.Any()).Returns(PasswordResetResult.Success); + _service.ResetAsync(id, "bad", "Password1!", Arg.Any()).Returns(PasswordResetResult.InvalidLink); + _service.ResetAsync(id, "weak", "Password1!", Arg.Any()) + .Returns(new PasswordResetResult(PasswordResetStatus.PasswordRejected, ["too short"])); + var controller = Controller(); + + (await controller.ResetPassword(new ResetPasswordRequest(id, "ok", "Password1!"), default)).Should().BeOfType(); + (await controller.ResetPassword(new ResetPasswordRequest(id, "bad", "Password1!"), default)).Should().BeOfType() + .Which.Value!.ToString().Should().Contain("invalid_link"); + (await controller.ResetPassword(new ResetPasswordRequest(id, "weak", "Password1!"), default)).Should().BeOfType() + .Which.Value!.ToString().Should().Contain("password_rejected"); + } + + [Theory] + [InlineData("", "Password1!")] + [InlineData("tok", "")] + public async Task Reset_RejectsMissingValues_AsAnInvalidLink(string token, string password) + { + var result = await Controller().ResetPassword(new ResetPasswordRequest(Guid.NewGuid(), token, password), default); + + result.Should().BeOfType().Which.Value!.ToString().Should().Contain("invalid_link"); + await _service.DidNotReceiveWithAnyArgs().ResetAsync(default, default!, default!, default); + } + + [Fact] + public async Task Reset_RejectsAnEmptyUserId_AndOversizedValues() + { + var controller = Controller(); + + (await controller.ResetPassword(new ResetPasswordRequest(Guid.Empty, "tok", "Password1!"), default)).Should().BeOfType(); + (await controller.ResetPassword(new ResetPasswordRequest(Guid.NewGuid(), new string('x', 2049), "Password1!"), default)).Should().BeOfType(); + (await controller.ResetPassword(new ResetPasswordRequest(Guid.NewGuid(), "tok", new string('x', 129)), default)).Should().BeOfType(); + await _service.DidNotReceiveWithAnyArgs().ResetAsync(default, default!, default!, default); + } +} diff --git a/src/SlpModularCms.Modules.Identity.Tests/Controllers/AuthControllerTests.cs b/src/SlpModularCms.Modules.Identity.Tests/Controllers/AuthControllerTests.cs index 2181e68..8b9c978 100644 --- a/src/SlpModularCms.Modules.Identity.Tests/Controllers/AuthControllerTests.cs +++ b/src/SlpModularCms.Modules.Identity.Tests/Controllers/AuthControllerTests.cs @@ -27,7 +27,7 @@ public class AuthControllerTests private AuthController CreateController(string? refreshTokenCookie = null, bool isAuthenticated = false, string? userId = null) { var options = Options.Create(_jwtSettings); - var controller = new AuthController(_authService, options); + var controller = new AuthController(_authService, options, Substitute.For(), Substitute.For(), Substitute.For()); var httpContext = new DefaultHttpContext(); @@ -99,7 +99,7 @@ public class AuthControllerTests // Manually set cookie via IHeaderDictionary since DefaultHttpContext reads cookies from header var options = Options.Create(_jwtSettings); - var controller = new AuthController(_authService, options); + var controller = new AuthController(_authService, options, Substitute.For(), Substitute.For(), Substitute.For()); var httpContext = new DefaultHttpContext(); httpContext.Request.Headers.Append("Cookie", "refreshToken=some-token"); controller.ControllerContext = new ControllerContext { HttpContext = httpContext }; @@ -114,7 +114,7 @@ public class AuthControllerTests public async Task Revoke_ReturnsNoContent_WhenCookiePresent() { var options = Options.Create(_jwtSettings); - var controller = new AuthController(_authService, options); + var controller = new AuthController(_authService, options, Substitute.For(), Substitute.For(), Substitute.For()); var httpContext = new DefaultHttpContext(); httpContext.Request.Headers.Append("Cookie", "refreshToken=some-token"); controller.ControllerContext = new ControllerContext { HttpContext = httpContext }; @@ -150,7 +150,7 @@ public class AuthControllerTests public async Task ChangePassword_ReturnsUnauthorized_WhenUserIdClaimIsNotAGuid() { var options = Options.Create(_jwtSettings); - var controller = new AuthController(_authService, options); + var controller = new AuthController(_authService, options, Substitute.For(), Substitute.For(), Substitute.For()); var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal( new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "not-a-guid")], "TestAuth")); @@ -169,7 +169,7 @@ public class AuthControllerTests _authService.AuthenticateAsync(Arg.Any(), Arg.Any()).Returns(response); var settings = new JwtSettings { Secret = _jwtSettings.Secret, Issuer = _jwtSettings.Issuer, Audience = _jwtSettings.Audience, CookieSameSite = "None" }; - var controller = new AuthController(_authService, Options.Create(settings)); + var controller = new AuthController(_authService, Options.Create(settings), Substitute.For(), Substitute.For(), Substitute.For()); controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; var result = await controller.Login(new LoginRequest("test@test.com", "Password1!")); @@ -185,7 +185,7 @@ public class AuthControllerTests _authService.AuthenticateAsync(Arg.Any(), Arg.Any()).Returns(response); var settings = new JwtSettings { Secret = _jwtSettings.Secret, Issuer = _jwtSettings.Issuer, Audience = _jwtSettings.Audience, CookieSameSite = "Invalid" }; - var controller = new AuthController(_authService, Options.Create(settings)); + var controller = new AuthController(_authService, Options.Create(settings), Substitute.For(), Substitute.For(), Substitute.For()); controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; var result = await controller.Login(new LoginRequest("test@test.com", "Password1!")); @@ -198,7 +198,7 @@ public class AuthControllerTests { var userId = Guid.NewGuid(); var options = Options.Create(_jwtSettings); - var controller = new AuthController(_authService, options); + var controller = new AuthController(_authService, options, Substitute.For(), Substitute.For(), Substitute.For()); var httpContext = new DefaultHttpContext(); httpContext.User = new ClaimsPrincipal( new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())], "TestAuth")); diff --git a/src/SlpModularCms.Modules.Identity/Controllers/AuthController.cs b/src/SlpModularCms.Modules.Identity/Controllers/AuthController.cs index b38af92..9d9b8f5 100644 --- a/src/SlpModularCms.Modules.Identity/Controllers/AuthController.cs +++ b/src/SlpModularCms.Modules.Identity/Controllers/AuthController.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using Microsoft.Extensions.Options; +using SlpModularCms.Core.Email; using SlpModularCms.Core.Identity.Models; using SlpModularCms.Core.Identity.Services; @@ -15,11 +16,22 @@ public class AuthController : ControllerBase { private readonly IAuthService _authService; private readonly JwtSettings _jwtSettings; + private readonly IPasswordResetService _passwordReset; + private readonly IPasswordResetDispatcher _dispatcher; + private readonly IIdentityMailService _mail; - public AuthController(IAuthService authService, IOptions jwtSettings) + public AuthController( + IAuthService authService, + IOptions jwtSettings, + IPasswordResetService passwordReset, + IPasswordResetDispatcher dispatcher, + IIdentityMailService mail) { _authService = authService; _jwtSettings = jwtSettings.Value; + _passwordReset = passwordReset; + _dispatcher = dispatcher; + _mail = mail; } [HttpPost("login")] @@ -76,6 +88,47 @@ public class AuthController : ControllerBase return Ok(); } + /// + /// Anonymous. Always answers 202 with the same body for a well-formed address, whether the account + /// exists or not; the mail (if any) is handled after the response. 404 on a site without mail. + /// + [HttpPost("forgot-password")] + [AllowAnonymous] + [EnableRateLimiting("login")] + public IActionResult ForgotPassword([FromBody] ForgotPasswordRequest request) + { + if (!_mail.IsEnabled) return NotFound(); + + var email = request?.Email?.Trim(); + if (!EmailAddressRules.IsValidAddress(email)) + return BadRequest(new { code = "invalid_email", detail = "Enter a valid e-mail address." }); + + _dispatcher.Dispatch(email!); + return Accepted(new { message = "If this address belongs to an account, an e-mail with a link has been sent." }); + } + + /// Anonymous. Sets a new password with the link from the mail; only a completed reset ends sessions. + [HttpPost("reset-password")] + [AllowAnonymous] + [EnableRateLimiting("login")] + public async Task ResetPassword([FromBody] ResetPasswordRequest request, CancellationToken ct) + { + if (!_mail.IsEnabled) return NotFound(); + + if (request is null || request.UserId == Guid.Empty + || string.IsNullOrWhiteSpace(request.Token) || request.Token.Length > 2048 + || string.IsNullOrEmpty(request.NewPassword) || request.NewPassword.Length > 128) + return BadRequest(new { code = "invalid_link", detail = "This link is invalid or has expired." }); + + var result = await _passwordReset.ResetAsync(request.UserId, request.Token, request.NewPassword, ct); + return result.Status switch + { + PasswordResetStatus.Succeeded => Ok(new { message = "Password set. You can sign in now." }), + PasswordResetStatus.PasswordRejected => BadRequest(new { code = "password_rejected", detail = "The password does not meet the requirements.", problems = result.Problems }), + _ => BadRequest(new { code = "invalid_link", detail = "This link is invalid or has expired." }) + }; + } + private void SetTokenCookie(string refreshToken) { Response.Cookies.Append("refreshToken", refreshToken, GetCookieOptions());