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:
@@ -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<IdentityMailService>.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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<string>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var service = Substitute.For<IPasswordResetService>();
|
||||
var release = new ManualResetEventSlim(false);
|
||||
service.RequestAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(ci =>
|
||||
{
|
||||
release.Wait(TimeSpan.FromSeconds(5)); // a slow mail: the caller must not wait for it
|
||||
handled.TrySetResult(ci.Arg<string>());
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
var services = new ServiceCollection();
|
||||
services.AddScoped(_ => service);
|
||||
using var sp = services.BuildServiceProvider();
|
||||
var dispatcher = new BackgroundPasswordResetDispatcher(sp.GetRequiredService<IServiceScopeFactory>(), NullLogger<BackgroundPasswordResetDispatcher>.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<IPasswordResetService>();
|
||||
service.RequestAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).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<IServiceScopeFactory>(), NullLogger<BackgroundPasswordResetDispatcher>.Instance);
|
||||
|
||||
var act = () => dispatcher.Dispatch("a@example.org");
|
||||
|
||||
act.Should().NotThrow();
|
||||
await called.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<IIdentityMailService>();
|
||||
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<ApplicationUser>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ci =>
|
||||
{
|
||||
_sentTokens.Add((ci.Arg<ApplicationUser>().Id, ci.Arg<string>()));
|
||||
return Task.FromResult(MailSendResult.Ok);
|
||||
});
|
||||
|
||||
_host = await new HostBuilder().ConfigureWebHost(web =>
|
||||
{
|
||||
web.UseTestServer();
|
||||
web.ConfigureServices(services =>
|
||||
{
|
||||
services.AddLogging();
|
||||
services.AddRouting();
|
||||
services.AddDataProtection();
|
||||
services.AddDbContext<ApplicationDbContext>(o => o.UseInMemoryDatabase(_dbName));
|
||||
services.AddIdentityCore<ApplicationUser>()
|
||||
.AddRoles<ApplicationRole>()
|
||||
.AddEntityFrameworkStores<ApplicationDbContext>()
|
||||
.AddDefaultTokenProviders();
|
||||
services.Configure<DataProtectionTokenProviderOptions>(o => o.TokenLifespan = _tokenLifespan);
|
||||
services.Configure<JwtSettings>(o =>
|
||||
{
|
||||
o.Secret = Jwt.Secret; o.Issuer = Jwt.Issuer; o.Audience = Jwt.Audience; o.ExpiryMinutes = Jwt.ExpiryMinutes;
|
||||
});
|
||||
services.AddScoped<IAuthService, AuthService>();
|
||||
services.AddSingleton(_mail);
|
||||
services.AddSingleton<TimeProvider>(_time);
|
||||
services.AddSingleton(sp => new ResetCooldown(sp.GetRequiredService<TimeProvider>(), TimeSpan.FromMinutes(5)));
|
||||
services.AddScoped<IPasswordResetService, PasswordResetService>();
|
||||
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<UserManager<ApplicationUser>>();
|
||||
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<T> Scoped<T>(Func<IServiceProvider, Task<T>> action)
|
||||
{
|
||||
using var scope = _host.Services.CreateScope();
|
||||
return await action(scope.ServiceProvider);
|
||||
}
|
||||
|
||||
private Task RequestAsync(string email) =>
|
||||
Scoped(async sp => { await sp.GetRequiredService<IPasswordResetService>().RequestAsync(email); return 0; });
|
||||
|
||||
private Task<PasswordResetResult> ResetAsync(Guid userId, string token, string password) =>
|
||||
Scoped(sp => sp.GetRequiredService<IPasswordResetService>().ResetAsync(userId, token, password));
|
||||
|
||||
private async Task<HttpStatusCode> 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<TokenResponse> LoginAsync(string password = "Password1!") =>
|
||||
Scoped(sp => sp.GetRequiredService<IAuthService>().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<ApplicationDbContext>();
|
||||
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<IAuthService>().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<IAuthService>().RefreshTokenAsync(login.RefreshToken));
|
||||
await refresh.Should().ThrowAsync<SlpModularCms.Core.Exceptions.UnauthorizedException>(); // refresh token revoked
|
||||
(await SnapshotAsync()).ActiveRefreshTokens.Should().Be(0);
|
||||
var oldPassword = () => LoginAsync("Password1!");
|
||||
await oldPassword.Should().ThrowAsync<SlpModularCms.Core.Exceptions.UnauthorizedException>();
|
||||
(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<IOptions<DataProtectionTokenProviderOptions>>().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<UserManager<ApplicationUser>>();
|
||||
(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<ApplicationDbContext>();
|
||||
(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<string, DateTimeOffset>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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<string, string?>
|
||||
{
|
||||
["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<IOptions<DataProtectionTokenProviderOptions>>().Value.TokenLifespan.Should().Be(TimeSpan.FromMinutes(30));
|
||||
sp.GetRequiredService<IOptions<IdentityOptions>>().Value.Tokens.ProviderMap.Should().ContainKey("Default");
|
||||
using var scope = sp.CreateScope();
|
||||
scope.ServiceProvider.GetRequiredService<IPasswordResetService>().Should().NotBeNull();
|
||||
sp.GetRequiredService<ResetCooldown>().Should().NotBeNull();
|
||||
sp.GetRequiredService<IPasswordResetDispatcher>().Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutConfiguration_TheLinkLastsAnHour_AndTheCooldownIsFiveMinutes()
|
||||
{
|
||||
using var sp = Build(null);
|
||||
|
||||
sp.GetRequiredService<IOptions<DataProtectionTokenProviderOptions>>().Value.TokenLifespan.Should().Be(TimeSpan.FromMinutes(60));
|
||||
sp.GetRequiredService<IOptions<PasswordResetSettings>>().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<IOptions<PasswordResetSettings>>().Value;
|
||||
|
||||
act.Should().Throw<OptionsValidationException>().WithMessage("*TokenLifetimeMinutes*");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user