backend: Rate limit login attempts per email and IP

This commit is contained in:
GonnaHetzMe committed 2026-12-04 23:45:00 +01:00
1 parent 5470818841
commit 52fb8af684
18 files changed
+106 -116

No files matched your search

@@ -42,8 +42,15 @@ public sealed class AuthController(AuthService auth) : ControllerBase
[HttpPost("login")]
[ProducesResponseType<AuthResponse>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
public Task<AuthResponse> Login(LoginRequest request, CancellationToken ct) => auth.LoginAsync(request, ct);
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
public async Task<ActionResult<AuthResponse>> Login(LoginRequest request, [FromServices] LoginRateLimiter limiter, CancellationToken ct)
{
if (!limiter.TryAcquire(HttpContext, request.Email))
return Problem(statusCode: StatusCodes.Status429TooManyRequests,
title: "Příliš mnoho pokusů o přihlášení. Zkuste to za chvíli.");
return await auth.LoginAsync(request, ct);
}
/// <summary>Výměna refresh tokenu za nový pár tokenů. Použitý refresh token se zneplatní.</summary>
/// <remarks>Opakované použití už vyměněného refresh tokenu zneplatní všechny tokeny uživatele.</remarks>
@@ -43,4 +43,10 @@ public static class RateLimitPolicies
{
public const string Auth = "auth";
public const string IssueWrites = "issue-writes";
public static string ClientIp(HttpContext context)
{
var address = context.Connection.RemoteIpAddress;
return (address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString() ?? "unknown";
}
}
@@ -0,0 +1,22 @@
using System.Threading.RateLimiting;
using Helpdesk.Domain.Users;
namespace Helpdesk.Api.Infrastructure;
public sealed class LoginRateLimiter : IDisposable
{
private readonly PartitionedRateLimiter<(string, string)> attempts =
PartitionedRateLimiter.Create<(string, string), (string, string)>(key =>
RateLimitPartition.GetFixedWindowLimiter(key,
_ => new FixedWindowRateLimiterOptions { PermitLimit = 5, Window = TimeSpan.FromMinutes(1) }));
public bool TryAcquire(HttpContext context, string? email)
{
var trimmed = email?.Trim();
var normalized = trimmed is { Length: > 0 and <= 254 } ? User.NormalizeEmail(trimmed) : string.Empty;
using var lease = attempts.AttemptAcquire((RateLimitPolicies.ClientIp(context), normalized));
return lease.IsAcquired;
}
public void Dispose() => attempts.Dispose();
}
+4 -8
View File
@@ -49,17 +49,13 @@ if (trustedProxies.Length > 0)
}
// Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10).
builder.Services.AddSingleton<LoginRateLimiter>();
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy(RateLimitPolicies.Auth, http =>
{
var address = http.Connection.RemoteIpAddress;
if (address is { IsIPv4MappedToIPv6: true })
address = address.MapToIPv4();
return RateLimitPartition.GetFixedWindowLimiter(address?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) });
});
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter(
RateLimitPolicies.ClientIp(http),
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }));
options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter(
http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown",
_ => new SlidingWindowRateLimiterOptions
@@ -39,7 +39,7 @@ public interface IAppDbContext
public interface IPasswordHasher
{
string Hash(string password);
bool Verify(string password, string passwordHash);
bool Verify(string password, string? passwordHash);
}
/// <summary>Vydaný JWT: serializovaný token a záznam pro tabulku <c>auth_token</c>.</summary>
@@ -17,7 +17,6 @@ public sealed class AuthService(
TokenRevocationService revocation,
IEmailSender emailSender,
IOptions<RegistrationOptions> registrationOptions,
TimeProvider clock,
IValidator<RegisterRequest> registerValidator,
IValidator<ConfirmEmailRequest> confirmEmailValidator,
IValidator<LoginRequest> loginValidator,
@@ -71,36 +70,21 @@ public sealed class AuthService(
await loginValidator.ValidateAndThrowAsync(request, ct);
var normalized = User.NormalizeEmail(request.Email);
var account = await db.Users.Where(u => u.EmailNormalized == normalized)
.Select(u => new { u.Id, u.EmailNormalized }).SingleOrDefaultAsync(ct);
var account = await db.Users.Where(u => u.EmailNormalized == normalized && u.IsActive && !u.IsDeleted && u.EmailConfirmed)
.Select(u => new { u.Id, u.EmailNormalized, u.PasswordHash }).SingleOrDefaultAsync(ct);
// Neexistující účet a špatné heslo vracejí stejnou chybu – nelze tak zjišťovat registrované e-maily.
const string invalidCredentials = "Neplatný e-mail nebo heslo.";
if (account is null)
var passwordHash = account?.EmailNormalized == normalized ? account.PasswordHash : null;
if (!passwordHasher.Verify(request.Password, passwordHash) || account is null)
throw new UnauthorizedException(invalidCredentials);
// Po ověření hesla ověříme pod zámkem, že se účet mezitím nezměnil.
await using var transaction = await db.BeginWriteAsync(ct);
var user = await db.LockUserAsync(account.Id, ct);
if (user is null || user.IsDeleted || user.EmailNormalized != account.EmailNormalized || user.PasswordHash.Length == 0)
if (user is not { IsActive: true, IsDeleted: false, EmailConfirmed: true } ||
user.EmailNormalized != normalized || user.PasswordHash != passwordHash)
throw new UnauthorizedException(invalidCredentials);
var now = clock.GetUtcNow().UtcDateTime;
if (user.IsLockedOut(now))
throw new UnauthorizedException("Účet je po opakovaných neúspěšných pokusech dočasně zamčen. Zkuste to později.");
if (!passwordHasher.Verify(request.Password, user.PasswordHash))
{
user.RegisterFailedLogin(now);
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
throw new UnauthorizedException(invalidCredentials);
}
if (!user.IsActive)
throw new ForbiddenException("Účet je deaktivován.");
if (!user.EmailConfirmed)
throw new ForbiddenException("E-mail ještě nebyl ověřen. Použijte odkaz z ověřovacího e-mailu.");
user.RegisterSuccessfulLogin();
var response = await IssueTokenPairAsync(user, ct);
await transaction.CommitAsync(ct);
return response;
+1 -29
View File
@@ -6,9 +6,6 @@ namespace Helpdesk.Domain.Users;
/// </summary>
public sealed class User : IHasCreatedAt
{
public const int MaxFailedLogins = 5;
public static readonly TimeSpan LockoutDuration = TimeSpan.FromMinutes(15);
private User() { } // EF Core
public int Id { get; private set; }
@@ -24,8 +21,6 @@ public sealed class User : IHasCreatedAt
public bool IsDeleted { get; private set; }
public bool EmailConfirmed { get; private set; }
public bool EmailNotificationsEnabled { get; private set; } = true;
public int FailedLoginCount { get; private set; }
public DateTime? LockoutUntil { get; private set; }
public int RowVersion { get; private set; }
public DateTime CreatedAt { get; set; }
@@ -43,25 +38,6 @@ public sealed class User : IHasCreatedAt
public static string NormalizeEmail(string email) => email.Trim().ToUpperInvariant();
public bool IsLockedOut(DateTime now) => LockoutUntil is { } until && until > now;
/// <summary>Neúspěšné přihlášení; po <see cref="MaxFailedLogins"/> pokusech se účet na 15 minut zamkne.</summary>
public void RegisterFailedLogin(DateTime now)
{
FailedLoginCount++;
if (FailedLoginCount >= MaxFailedLogins)
{
LockoutUntil = now + LockoutDuration;
FailedLoginCount = 0;
}
}
public void RegisterSuccessfulLogin()
{
FailedLoginCount = 0;
LockoutUntil = null;
}
public void ConfirmEmail() => EmailConfirmed = true;
public void SetEmailConfirmed(bool confirmed) => EmailConfirmed = confirmed;
@@ -72,11 +48,7 @@ public sealed class User : IHasCreatedAt
EmailNormalized = NormalizeEmail(email);
}
public void ChangePasswordHash(string passwordHash)
{
PasswordHash = passwordHash;
RegisterSuccessfulLogin();
}
public void ChangePasswordHash(string passwordHash) => PasswordHash = passwordHash;
public void UpdateProfile(string firstName, string lastName, string? phone, bool emailNotificationsEnabled)
{
@@ -45,8 +45,7 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
foreach (var entry in ChangeTracker.Entries<User>())
{
if (entry.State == EntityState.Modified && entry.Properties.Any(property =>
property.IsModified && property.Metadata.Name is not (
nameof(User.FailedLoginCount) or nameof(User.LockoutUntil) or nameof(User.RowVersion))))
property.IsModified && property.Metadata.Name != nameof(User.RowVersion)))
{
var version = entry.Property(user => user.RowVersion);
version.CurrentValue = checked(version.OriginalValue + 1);
@@ -1,3 +1,4 @@
using System.Security.Cryptography;
using Helpdesk.Application.Abstractions;
namespace Helpdesk.Infrastructure.Security;
@@ -6,8 +7,15 @@ namespace Helpdesk.Infrastructure.Security;
internal sealed class BCryptPasswordHasher : IPasswordHasher
{
private const int WorkFactor = 12;
private readonly string dummyHash = BCrypt.Net.BCrypt.HashPassword(
Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), WorkFactor);
public string Hash(string password) => BCrypt.Net.BCrypt.HashPassword(password, WorkFactor);
public bool Verify(string password, string passwordHash) => BCrypt.Net.BCrypt.Verify(password, passwordHash);
public bool Verify(string password, string? passwordHash)
{
var hasPassword = !string.IsNullOrEmpty(passwordHash);
var matches = BCrypt.Net.BCrypt.Verify(password, hasPassword ? passwordHash : dummyHash);
return hasPassword && matches;
}
}
@@ -55,7 +55,7 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, Password), Cancellation),
HttpStatusCode.Unauthorized);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, edit.Password!), Cancellation),
HttpStatusCode.Forbidden);
HttpStatusCode.Unauthorized);
await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(edit.Email), password: edit.Password!);
var edited = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
new LoginRequest(edit.Email, edit.Password!), Cancellation));
@@ -91,7 +91,7 @@ public sealed class AdministrationTests(BackendFixture fixture) : IClassFixture<
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(false), Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(member.GetAsync(profile, Cancellation), HttpStatusCode.Unauthorized);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, Password), Cancellation),
HttpStatusCode.Forbidden);
HttpStatusCode.Unauthorized);
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(true), Cancellation), HttpStatusCode.NoContent);
Assert.Equal(user.Id, (await LoginAsync(anonymous, user.Email)).User.Id);
}
@@ -4,6 +4,7 @@ using Helpdesk.Api.Controllers;
using Helpdesk.Application.Auth;
using Helpdesk.Domain.Auth;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.JsonWebTokens;
@@ -13,6 +14,32 @@ namespace Helpdesk.IntegrationTests;
public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Fact]
public async Task LoginFailuresAreGenericAndLoginLimitAppliesPerClientAndEmail()
{
using var setup = fixture.CreateClient();
var user = await fixture.RegisterAsync(setup);
var unrelated = await fixture.RegisterAsync(setup);
using var limitedClient = fixture.CreateClient();
using var otherClient = fixture.CreateClient();
const string login = "/api/v1/auth/login";
const string wrongPassword = "Wrong-integration-password";
var unknown = await ReadAsync<ProblemDetails>(limitedClient.PostAsJsonAsync(login,
new LoginRequest("[email protected]", wrongPassword), Cancellation), HttpStatusCode.Unauthorized);
for (var attempt = 0; attempt < 5; attempt++)
{
var failure = await ReadAsync<ProblemDetails>(limitedClient.PostAsJsonAsync(login,
new LoginRequest($" {user.Email.ToUpperInvariant()} ", wrongPassword), Cancellation), HttpStatusCode.Unauthorized);
Assert.Equal((unknown.Status, unknown.Title, unknown.Type), (failure.Status, failure.Title, failure.Type));
}
await ExpectAsync(limitedClient.PostAsJsonAsync(login, new LoginRequest(user.Email, Password), Cancellation),
HttpStatusCode.TooManyRequests);
Assert.Equal(unrelated.Id, (await LoginAsync(limitedClient, unrelated.Email)).User.Id);
Assert.Equal(user.Id, (await LoginAsync(otherClient, user.Email)).User.Id);
}
[Fact]
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSessionAndRemovesItsDevice()
{
@@ -54,6 +54,8 @@ public sealed class EmailConfirmationTests(BackendFixture fixture) : IClassFixtu
var original = scope.ServiceProvider.GetRequiredService<ITokenService>().Issue(pending, TokenType.EmailConfirm);
db.AuthTokens.Add(original.Record);
await db.SaveChangesAsync(Cancellation);
await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, oldPassword), Cancellation),
HttpStatusCode.Unauthorized);
await ExpectAsync(anonymous.PostAsJsonAsync(Register, new RegisterRequest(address, "Jiné", "Jméno"), Cancellation),
HttpStatusCode.Created);
@@ -1,4 +1,6 @@
using System.Net;
using System.Text.Json;
using Helpdesk.Application.Auth;
using Microsoft.AspNetCore.TestHost;
using static Helpdesk.IntegrationTests.BackendFixture;
@@ -16,16 +18,16 @@ public sealed class ProxyRateLimitTests(BackendFixture fixture) : IClassFixture<
await using var api = fixture.CreateApiBehindProxies(externalProxy, web);
for (var attempt = 0; attempt < 20; attempt++)
Assert.Equal(401, await LoginAsync(api.Server, web, firstClient));
Assert.Equal(401, await LoginAsync(api.Server, web, firstClient, $"absent-{attempt}@example.test"));
Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient));
Assert.Equal(401, await LoginAsync(api.Server, web, secondClient));
Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient));
Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient, "[email protected]"));
Assert.Equal(401, await LoginAsync(api.Server, web, secondClient, "[email protected]"));
Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient, "[email protected]"));
}
private static async Task<int> LoginAsync(TestServer server, string peer, string client)
private static async Task<int> LoginAsync(TestServer server, string peer, string client, string email)
{
using var body = new MemoryStream("""{"email":"absent@example.test","password":"test-password"}"""u8.ToArray());
using var body = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(new LoginRequest(email, "test-password")));
var response = await server.SendAsync(context =>
{
context.Connection.RemoteIpAddress = IPAddress.Parse(peer);
@@ -37,46 +37,11 @@ public class EnumCodeTests
public void Neznamy_kod_neprojde() => Assert.False(EnumCode.TryParse<UserRole>("SUPERUSER", out _));
}
public class UserLockoutTests
public class UserTests
{
private static readonly DateTime Now = new(2026, 10, 29, 10, 0, 0, DateTimeKind.Utc);
private static User NewUser() => User.Create("[email protected]", "hash", "Jan", "Novák", UserRole.Student);
[Fact]
public void Ctyri_neuspesne_pokusy_ucet_nezamknou()
{
var user = NewUser();
for (var i = 0; i < User.MaxFailedLogins - 1; i++)
user.RegisterFailedLogin(Now);
Assert.False(user.IsLockedOut(Now));
}
[Fact]
public void Paty_neuspesny_pokus_zamkne_ucet_na_15_minut()
{
var user = NewUser();
for (var i = 0; i < User.MaxFailedLogins; i++)
user.RegisterFailedLogin(Now);
Assert.True(user.IsLockedOut(Now.AddMinutes(14)));
Assert.False(user.IsLockedOut(Now.AddMinutes(15)));
}
[Fact]
public void Uspesne_prihlaseni_vynuluje_pocitadlo()
{
var user = NewUser();
user.RegisterFailedLogin(Now);
user.RegisterSuccessfulLogin();
Assert.Equal(0, user.FailedLoginCount);
}
[Fact]
public void Email_se_normalizuje_pro_jednoznacne_vyhledani() =>
Assert.Equal("[email protected]", NewUser().EmailNormalized);
Assert.Equal("[email protected]", User.Create("[email protected]", "hash", "Jan", "Novák", UserRole.Student).EmailNormalized);
}
public class RegistrationRoleTests
@@ -0,0 +1,3 @@
ALTER TABLE app_user
DROP COLUMN IF EXISTS failed_login_count,
DROP COLUMN IF EXISTS lockout_until;
+2 -4
View File
@@ -512,7 +512,7 @@ Větvení: `main` (stabilní), `develop`, feature větve `feature/<nazev>`, merg
| Oblast | Řešení |
|---|---|
| Hesla | Hash BCrypt (knihovna BCrypt.Net-Next, work factor 12; sůl je součástí hashe). Min. délka hesla 8 znaků. |
| Přihlášení | Ochrana proti hádání hesla: po 5 neúspěšných pokusech zámek účtu na 15 minut (`failed_login_count`, `lockout_until`), rate limiting na `/api/v1/auth/*`. |
| Přihlášení | Neúspěšné ověření vrací jednotnou odpověď, BCrypt se provádí i pro neznámý účet. Každá instance API omezuje přihlášení na 5 pokusů za minutu pro dvojici klientská IP a normalizovaný e-mail. Pro `/api/v1/auth/*` platí také limit 20 požadavků za minutu na klientskou IP. |
| Tokeny | Všechny tokeny jsou podepsané JWT podle RFC 7519 s unikátním `jti` a typem v hlavičce. V databázi není žádný token ani jeho hash (kap. 10.1). |
| Šifrování citlivých údajů | Telefonní číslo uživatele šifrováno AES-256-GCM (EF Core value converter), klíč mimo DB – v proměnné prostředí / Docker secret. Přenos výhradně HTTPS (TLS 1.2+), HSTS. |
| Přílohy | Kontrola typu (přípona + signatura souboru) a velikosti, ukládání pod náhodným GUID mimo webový kořen, stahování jen přes API s kontrolou oprávnění k závadě. Web nabízí PDF ke stažení. API zapisuje varování do logu, pokud na svazku s přílohami zbývá méně než 10 % volného místa. |
@@ -780,8 +780,6 @@ erDiagram
bool is_active
bool email_confirmed
bool email_notifications_enabled
int failed_login_count
datetime lockout_until
datetime created_at
}
auth_token {
@@ -951,7 +949,7 @@ V první verzi byla tabulka uživatelů „chobotnice“: vedlo na ni 17 cizích
- Hlavní tabulky (`issue`, `proposal`, `attachment`, …) obsahují **jen `created_at`**. Je neměnný a potřebný pro řazení a filtrování podle období přes index.
- Všechny ostatní časy životního cyklu (přiřazení, převzetí, uzavření, rozhodnutí vedení, úpravy) jsou v **tabulkách událostí** `issue_event` a `proposal_event`. Jedna řádka = jeden okamžik (`occurred_at`), kdo ho způsobil (`actor_id`) a co se stalo (`event_type`, `from_status` → `to_status`, `note`). Zrušeny byly sloupce `updated_at`, `assigned_at`, `closed_at`, `decided_at`, `rejection_reason`, `decision_note`.
- Odvozené časy poskytuje pohled `v_issue_lifecycle` (`first_assigned_at`, `closed_at`, `last_activity_at`). Z něj čerpají statistiky.
- Zůstávají jen **funkční časy**, které popisují aktuální stav záznamu a řídí chování systému: `notification.read_at`, `notification_delivery.next_attempt_at` / `sent_at`, `auth_token.issued_at` / `expires_at` / `revoked_at` (odpovídají claimům tokenu), `app_user.lockout_until`.
- **Funkční časy** popisují aktuální stav záznamu a řídí chování systému: `notification.read_at`, `notification_delivery.next_attempt_at` / `sent_at`, `auth_token.issued_at` / `expires_at` / `revoked_at` (odpovídají claimům tokenu).
- *Proč ne jedna společná tabulka datumů pro všechny entity:* musela by odkazovat na různé tabulky bez cizího klíče (polymorfní vazba), každý seznam by potřeboval další JOIN a řazení podle data by nevyužilo index. Tabulky událostí pro každou hlavní entitu tyto nevýhody nemají, zachovávají referenční integritu a navíc slouží jako audit.
- `created_at` vyplňuje v EF Core automaticky interceptor `SaveChanges` u entit s rozhraním `IHasCreatedAt`. Výchozí hodnota v DB je `UTC_TIMESTAMP(6)`.
@@ -44,7 +44,6 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized
or HttpStatusCode.Forbidden or HttpStatusCode.TooManyRequests)
{
// 401 špatné heslo / zamčený účet, 403 neověřený e-mail nebo deaktivovaný účet – API vrací český text.
ModelState.AddApiErrors(ex, typeof(LoginViewModel));
model.Password = "";
return View(model);