diff --git a/src/Jiaowu.Api/Controllers/AccountSecurityController.cs b/src/Jiaowu.Api/Controllers/AccountSecurityController.cs index 10d07c8..f3daa1e 100644 --- a/src/Jiaowu.Api/Controllers/AccountSecurityController.cs +++ b/src/Jiaowu.Api/Controllers/AccountSecurityController.cs @@ -2,9 +2,11 @@ using System.ComponentModel.DataAnnotations; using System.Security.Claims; using Jiaowu.Api.Domain.Identity; using Jiaowu.Api.Infrastructure.Branding; +using Jiaowu.Api.Infrastructure.Auth; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; namespace Jiaowu.Api.Controllers; @@ -23,13 +25,16 @@ public sealed class AccountSecurityController( } [HttpPost("totp/setup")] + [EnableRateLimiting("sensitive-auth")] public async Task> SetupTotp(PasswordConfirmationRequest request) { var user = await CurrentUserAsync(); if (user is null) return Unauthorized(); - if (!await userManager.CheckPasswordAsync(user, request.CurrentPassword)) + if (!await SensitiveOperationVerification.PasswordAsync(userManager, user, request.CurrentPassword)) return Unauthorized(PasswordProblem()); + if (user.TwoFactorEnabled) return Conflict("双重验证已启用,请先关闭后再重新设置。"); + await userManager.ResetAuthenticatorKeyAsync(user); var key = await userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrWhiteSpace(key)) return Problem("无法创建验证器密钥。"); @@ -41,12 +46,13 @@ public sealed class AccountSecurityController( } [HttpPost("totp/enable")] + [EnableRateLimiting("sensitive-auth")] public async Task> EnableTotp(TotpEnableRequest request) { var user = await CurrentUserAsync(); if (user is null) return Unauthorized(); - if (!await userManager.VerifyTwoFactorTokenAsync(user, - TokenOptions.DefaultAuthenticatorProvider, request.Code.Replace(" ", string.Empty))) + if (user.TwoFactorEnabled) return Conflict("双重验证已启用。"); + if (!await SensitiveOperationVerification.TotpAsync(userManager, user, request.Code.Replace(" ", string.Empty))) { ModelState.AddModelError("code", "验证码不正确或已过期。"); return ValidationProblem(ModelState); @@ -58,11 +64,12 @@ public sealed class AccountSecurityController( } [HttpPost("totp/disable")] + [EnableRateLimiting("sensitive-auth")] public async Task DisableTotp(PasswordConfirmationRequest request) { var user = await CurrentUserAsync(); if (user is null) return Unauthorized(); - if (!await userManager.CheckPasswordAsync(user, request.CurrentPassword)) + if (!await SensitiveOperationVerification.PasswordAsync(userManager, user, request.CurrentPassword)) return Unauthorized(PasswordProblem()); await userManager.SetTwoFactorEnabledAsync(user, false); await userManager.ResetAuthenticatorKeyAsync(user); diff --git a/src/Jiaowu.Api/Controllers/PasskeyController.cs b/src/Jiaowu.Api/Controllers/PasskeyController.cs index a7498f9..7184c5a 100644 --- a/src/Jiaowu.Api/Controllers/PasskeyController.cs +++ b/src/Jiaowu.Api/Controllers/PasskeyController.cs @@ -61,6 +61,7 @@ public sealed class PasskeyController( [Authorize] [HttpPost("registration/options")] + [EnableRateLimiting("sensitive-auth")] public async Task RegistrationOptions( PasskeyRegistrationOptionsRequest request, CancellationToken cancellationToken) @@ -68,7 +69,7 @@ public sealed class PasskeyController( if (!_options.Enabled) return PasskeysDisabled(); var user = await CurrentUserAsync(); if (user is null) return Unauthorized(); - if (!await userManager.CheckPasswordAsync(user, request.CurrentPassword)) + if (!await SensitiveOperationVerification.PasswordAsync(userManager, user, request.CurrentPassword)) return Unauthorized(PasswordProblem()); var credentials = await db.PasskeyCredentials.AsNoTracking() .Where(x => x.UserId == user.Id).ToListAsync(cancellationToken); @@ -278,6 +279,7 @@ public sealed class PasskeyController( [Authorize] [HttpDelete("{id:guid}")] + [EnableRateLimiting("sensitive-auth")] public async Task Delete( Guid id, PasswordConfirmationRequest request, @@ -285,7 +287,7 @@ public sealed class PasskeyController( { var user = await CurrentUserAsync(); if (user is null) return Unauthorized(); - if (!await userManager.CheckPasswordAsync(user, request.CurrentPassword)) + if (!await SensitiveOperationVerification.PasswordAsync(userManager, user, request.CurrentPassword)) return Unauthorized(PasswordProblem()); var credential = await db.PasskeyCredentials.SingleOrDefaultAsync( x => x.Id == id && x.UserId == user.Id, cancellationToken); diff --git a/src/Jiaowu.Api/Infrastructure/Auth/SensitiveOperationVerification.cs b/src/Jiaowu.Api/Infrastructure/Auth/SensitiveOperationVerification.cs new file mode 100644 index 0000000..093c89e --- /dev/null +++ b/src/Jiaowu.Api/Infrastructure/Auth/SensitiveOperationVerification.cs @@ -0,0 +1,31 @@ +using Jiaowu.Api.Domain.Identity; +using Microsoft.AspNetCore.Identity; + +namespace Jiaowu.Api.Infrastructure.Auth; + +internal static class SensitiveOperationVerification +{ + public static async Task PasswordAsync(UserManager manager, ApplicationUser user, string password) + { + if (!user.IsEnabled || await manager.IsLockedOutAsync(user)) return false; + if (!await manager.CheckPasswordAsync(user, password)) + { + await manager.AccessFailedAsync(user); + return false; + } + await manager.ResetAccessFailedCountAsync(user); + return true; + } + + public static async Task TotpAsync(UserManager manager, ApplicationUser user, string code) + { + if (!user.IsEnabled || await manager.IsLockedOutAsync(user)) return false; + if (!await manager.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, code)) + { + await manager.AccessFailedAsync(user); + return false; + } + await manager.ResetAccessFailedCountAsync(user); + return true; + } +} diff --git a/src/Jiaowu.Api/Program.cs b/src/Jiaowu.Api/Program.cs index dae8dfa..7abb13f 100644 --- a/src/Jiaowu.Api/Program.cs +++ b/src/Jiaowu.Api/Program.cs @@ -749,6 +749,16 @@ builder.Services.AddRateLimiter(options => QueueLimit = 0, AutoReplenishment = true })); + options.AddPolicy("sensitive-auth", context => + RateLimitPartition.GetFixedWindowLimiter( + context.Connection.RemoteIpAddress?.ToString() ?? "unknown", + _ => new FixedWindowRateLimiterOptions + { + PermitLimit = 10, + Window = TimeSpan.FromMinutes(5), + QueueLimit = 0, + AutoReplenishment = true + })); options.AddPolicy("captcha-challenge", context => RateLimitPartition.GetFixedWindowLimiter( context.Connection.RemoteIpAddress?.ToString() ?? "unknown", diff --git a/tests/Jiaowu.Api.Tests/AccountSecurityTests.cs b/tests/Jiaowu.Api.Tests/AccountSecurityTests.cs new file mode 100644 index 0000000..bd99a7b --- /dev/null +++ b/tests/Jiaowu.Api.Tests/AccountSecurityTests.cs @@ -0,0 +1,91 @@ +using System.Security.Claims; +using Jiaowu.Api.Controllers; +using Jiaowu.Api.Domain.Identity; +using Jiaowu.Api.Infrastructure.Branding; +using Jiaowu.Api.Infrastructure.Persistence; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Jiaowu.Api.Tests; + +public sealed class AccountSecurityTests +{ + [Fact] + public async Task PasswordFailuresLockAccountAndPreventEvenCorrectPassword() + { + await using var f = await Fixture.CreateAsync(); + for (var i = 0; i < 5; i++) + Assert.IsType((await f.Controller.SetupTotp(new("wrong"))).Result); + Assert.True(await f.Users.IsLockedOutAsync(f.User)); + Assert.IsType((await f.Controller.SetupTotp(new("LocalUser@123"))).Result); + Assert.Null(await f.Users.GetAuthenticatorKeyAsync(f.User)); + } + + [Fact] + public async Task InvalidTotpAttemptsLockAccount() + { + await using var f = await Fixture.CreateAsync(); + await f.Users.ResetAuthenticatorKeyAsync(f.User); + for (var i = 0; i < 5; i++) + Assert.IsAssignableFrom((await f.Controller.EnableTotp(new("not-a-code"))).Result); + Assert.True(await f.Users.IsLockedOutAsync(f.User)); + Assert.IsAssignableFrom((await f.Controller.EnableTotp(new("123456"))).Result); + Assert.False(f.User.TwoFactorEnabled); + } + + [Fact] + public async Task EnabledTotpCannotBeResetOrReenabled() + { + await using var f = await Fixture.CreateAsync(); + await f.Users.ResetAuthenticatorKeyAsync(f.User); + var key = await f.Users.GetAuthenticatorKeyAsync(f.User); + await f.Users.SetTwoFactorEnabledAsync(f.User, true); + Assert.IsType((await f.Controller.SetupTotp(new("LocalUser@123"))).Result); + Assert.IsType((await f.Controller.EnableTotp(new("123456"))).Result); + Assert.Equal(key, await f.Users.GetAuthenticatorKeyAsync(f.User)); + } + + private sealed class Fixture(SqliteConnection connection, ServiceProvider provider, ApplicationUser user, UserManager users, AccountSecurityController controller) : IAsyncDisposable + { + public ApplicationUser User { get; } = user; + public UserManager Users { get; } = users; + public AccountSecurityController Controller { get; } = controller; + + public static async Task CreateAsync() + { + var connection = new SqliteConnection("Data Source=:memory:"); + await connection.OpenAsync(); + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(options => options.UseSqlite(connection)); + services.AddIdentityCore(options => + { + options.Lockout.MaxFailedAccessAttempts = 5; + options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15); + }) + .AddRoles() + .AddTokenProvider>(TokenOptions.DefaultAuthenticatorProvider) + .AddEntityFrameworkStores(); + var provider = services.BuildServiceProvider(); + await provider.GetRequiredService().Database.EnsureCreatedAsync(); + var users = provider.GetRequiredService>(); + var user = new ApplicationUser { UserName = "user", DisplayName = "User", IsEnabled = true, LockoutEnabled = true }; + Assert.True((await users.CreateAsync(user, "LocalUser@123")).Succeeded); + var controller = new AccountSecurityController(users, new BrandingOptions()) + { + ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())], "test")) } } + }; + return new Fixture(connection, provider, user, users, controller); + } + + public async ValueTask DisposeAsync() + { + await provider.DisposeAsync(); + await connection.DisposeAsync(); + } + } +}