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 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 19:21:29 +01:00
co-authored by Claude Sonnet 5.5
parent 3cba2facb3
commit c8e23826c3
11 changed files with 901 additions and 9 deletions
@@ -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<IPasswordResetService>();
private readonly IPasswordResetDispatcher _dispatcher = Substitute.For<IPasswordResetDispatcher>();
private readonly IIdentityMailService _mail = Substitute.For<IIdentityMailService>();
private AuthController Controller(bool mailEnabled = true)
{
_mail.IsEnabled.Returns(mailEnabled);
return new AuthController(
Substitute.For<IAuthService>(),
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<AllowAnonymousAttribute>().Should().NotBeNull();
info.GetCustomAttribute<EnableRateLimitingAttribute>()!.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<AcceptedResult>();
unknown.Should().BeOfType<AcceptedResult>();
((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<BadRequestObjectResult>();
_dispatcher.DidNotReceiveWithAnyArgs().Dispatch(default!);
}
[Fact]
public async Task OnASiteWithoutMail_BothEndpointsAre404()
{
var controller = Controller(mailEnabled: false);
controller.ForgotPassword(new ForgotPasswordRequest("a@example.org")).Should().BeOfType<NotFoundResult>();
(await controller.ResetPassword(new ResetPasswordRequest(Guid.NewGuid(), "t", "Password1!"), default)).Should().BeOfType<NotFoundResult>();
_dispatcher.DidNotReceiveWithAnyArgs().Dispatch(default!);
}
[Fact]
public async Task Reset_MapsTheOutcomes()
{
var id = Guid.NewGuid();
_service.ResetAsync(id, "ok", "Password1!", Arg.Any<CancellationToken>()).Returns(PasswordResetResult.Success);
_service.ResetAsync(id, "bad", "Password1!", Arg.Any<CancellationToken>()).Returns(PasswordResetResult.InvalidLink);
_service.ResetAsync(id, "weak", "Password1!", Arg.Any<CancellationToken>())
.Returns(new PasswordResetResult(PasswordResetStatus.PasswordRejected, ["too short"]));
var controller = Controller();
(await controller.ResetPassword(new ResetPasswordRequest(id, "ok", "Password1!"), default)).Should().BeOfType<OkObjectResult>();
(await controller.ResetPassword(new ResetPasswordRequest(id, "bad", "Password1!"), default)).Should().BeOfType<BadRequestObjectResult>()
.Which.Value!.ToString().Should().Contain("invalid_link");
(await controller.ResetPassword(new ResetPasswordRequest(id, "weak", "Password1!"), default)).Should().BeOfType<BadRequestObjectResult>()
.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<BadRequestObjectResult>().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<BadRequestObjectResult>();
(await controller.ResetPassword(new ResetPasswordRequest(Guid.NewGuid(), new string('x', 2049), "Password1!"), default)).Should().BeOfType<BadRequestObjectResult>();
(await controller.ResetPassword(new ResetPasswordRequest(Guid.NewGuid(), "tok", new string('x', 129)), default)).Should().BeOfType<BadRequestObjectResult>();
await _service.DidNotReceiveWithAnyArgs().ResetAsync(default, default!, default!, default);
}
}
@@ -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<SlpModularCms.Core.Identity.Services.IPasswordResetService>(), Substitute.For<SlpModularCms.Core.Identity.Services.IPasswordResetDispatcher>(), Substitute.For<SlpModularCms.Core.Email.IIdentityMailService>());
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<SlpModularCms.Core.Identity.Services.IPasswordResetService>(), Substitute.For<SlpModularCms.Core.Identity.Services.IPasswordResetDispatcher>(), Substitute.For<SlpModularCms.Core.Email.IIdentityMailService>());
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<SlpModularCms.Core.Identity.Services.IPasswordResetService>(), Substitute.For<SlpModularCms.Core.Identity.Services.IPasswordResetDispatcher>(), Substitute.For<SlpModularCms.Core.Email.IIdentityMailService>());
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<SlpModularCms.Core.Identity.Services.IPasswordResetService>(), Substitute.For<SlpModularCms.Core.Identity.Services.IPasswordResetDispatcher>(), Substitute.For<SlpModularCms.Core.Email.IIdentityMailService>());
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<string>(), Arg.Any<string>()).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<SlpModularCms.Core.Identity.Services.IPasswordResetService>(), Substitute.For<SlpModularCms.Core.Identity.Services.IPasswordResetDispatcher>(), Substitute.For<SlpModularCms.Core.Email.IIdentityMailService>());
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<string>(), Arg.Any<string>()).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<SlpModularCms.Core.Identity.Services.IPasswordResetService>(), Substitute.For<SlpModularCms.Core.Identity.Services.IPasswordResetDispatcher>(), Substitute.For<SlpModularCms.Core.Email.IIdentityMailService>());
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<SlpModularCms.Core.Identity.Services.IPasswordResetService>(), Substitute.For<SlpModularCms.Core.Identity.Services.IPasswordResetDispatcher>(), Substitute.For<SlpModularCms.Core.Email.IIdentityMailService>());
var httpContext = new DefaultHttpContext();
httpContext.User = new ClaimsPrincipal(
new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())], "TestAuth"));