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

@@ -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