From 52fb8af68454371604bf9db70f5a9778dbedfd1d Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Fri, 4 Dec 2026 23:45:00 +0100 Subject: [PATCH] backend: Rate limit login attempts per email and IP --- .../Controllers/AuthController.cs | 11 +++++- .../Infrastructure/AuthenticationSetup.cs | 6 +++ .../Infrastructure/LoginRateLimiter.cs | 22 +++++++++++ backend/src/Helpdesk.Api/Program.cs | 12 ++---- .../Abstractions/Abstractions.cs | 2 +- .../Helpdesk.Application/Auth/AuthService.cs | 30 ++++---------- backend/src/Helpdesk.Domain/Users/User.cs | 30 +------------- .../Persistence/HelpdeskDbContext.cs | 3 +- .../Security/BCryptPasswordHasher.cs | 10 ++++- .../AdminAccountLifecycleTests.cs | 2 +- .../AdministrationTests.cs | 2 +- .../Helpdesk.IntegrationTests/AuthTests.cs | 27 +++++++++++++ .../EmailConfirmationTests.cs | 2 + .../ProxyRateLimitTests.cs | 14 ++++--- .../tests/Helpdesk.UnitTests/DomainTests.cs | 39 +------------------ ...7__remove_unused_login_lockout_columns.sql | 3 ++ docs/navrh-aplikace.md | 6 +-- .../Controllers/AccountController.cs | 1 - 18 files changed, 106 insertions(+), 116 deletions(-) create mode 100644 backend/src/Helpdesk.Api/Infrastructure/LoginRateLimiter.cs create mode 100644 db/migrations/V007__remove_unused_login_lockout_columns.sql diff --git a/backend/src/Helpdesk.Api/Controllers/AuthController.cs b/backend/src/Helpdesk.Api/Controllers/AuthController.cs index efb574f..c70a3f7 100644 --- a/backend/src/Helpdesk.Api/Controllers/AuthController.cs +++ b/backend/src/Helpdesk.Api/Controllers/AuthController.cs @@ -42,8 +42,15 @@ public sealed class AuthController(AuthService auth) : ControllerBase [HttpPost("login")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status403Forbidden)] - public Task Login(LoginRequest request, CancellationToken ct) => auth.LoginAsync(request, ct); + [ProducesResponseType(StatusCodes.Status429TooManyRequests)] + public async Task> 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); + } /// Výměna refresh tokenu za nový pár tokenů. Použitý refresh token se zneplatní. /// Opakované použití už vyměněného refresh tokenu zneplatní všechny tokeny uživatele. diff --git a/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs b/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs index 102af77..6bbde59 100644 --- a/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs +++ b/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs @@ -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"; + } } diff --git a/backend/src/Helpdesk.Api/Infrastructure/LoginRateLimiter.cs b/backend/src/Helpdesk.Api/Infrastructure/LoginRateLimiter.cs new file mode 100644 index 0000000..464bbc4 --- /dev/null +++ b/backend/src/Helpdesk.Api/Infrastructure/LoginRateLimiter.cs @@ -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(); +} diff --git a/backend/src/Helpdesk.Api/Program.cs b/backend/src/Helpdesk.Api/Program.cs index 96ebe63..e037835 100644 --- a/backend/src/Helpdesk.Api/Program.cs +++ b/backend/src/Helpdesk.Api/Program.cs @@ -49,17 +49,13 @@ if (trustedProxies.Length > 0) } // Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10). +builder.Services.AddSingleton(); 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 diff --git a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs index 41a2e85..3fffff8 100644 --- a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs +++ b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs @@ -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); } /// Vydaný JWT: serializovaný token a záznam pro tabulku auth_token. diff --git a/backend/src/Helpdesk.Application/Auth/AuthService.cs b/backend/src/Helpdesk.Application/Auth/AuthService.cs index 21115fa..436f759 100644 --- a/backend/src/Helpdesk.Application/Auth/AuthService.cs +++ b/backend/src/Helpdesk.Application/Auth/AuthService.cs @@ -17,7 +17,6 @@ public sealed class AuthService( TokenRevocationService revocation, IEmailSender emailSender, IOptions registrationOptions, - TimeProvider clock, IValidator registerValidator, IValidator confirmEmailValidator, IValidator 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; diff --git a/backend/src/Helpdesk.Domain/Users/User.cs b/backend/src/Helpdesk.Domain/Users/User.cs index b8b6105..d51d51b 100644 --- a/backend/src/Helpdesk.Domain/Users/User.cs +++ b/backend/src/Helpdesk.Domain/Users/User.cs @@ -6,9 +6,6 @@ namespace Helpdesk.Domain.Users; /// 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; - - /// Neúspěšné přihlášení; po pokusech se účet na 15 minut zamkne. - 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) { diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs index f98a74d..ede5122 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs @@ -45,8 +45,7 @@ public sealed class HelpdeskDbContext(DbContextOptions option foreach (var entry in ChangeTracker.Entries()) { 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); diff --git a/backend/src/Helpdesk.Infrastructure/Security/BCryptPasswordHasher.cs b/backend/src/Helpdesk.Infrastructure/Security/BCryptPasswordHasher.cs index 9011bc5..a831a43 100644 --- a/backend/src/Helpdesk.Infrastructure/Security/BCryptPasswordHasher.cs +++ b/backend/src/Helpdesk.Infrastructure/Security/BCryptPasswordHasher.cs @@ -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; + } } diff --git a/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs b/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs index c2a3533..06fd561 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs @@ -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(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, edit.Password!), Cancellation)); diff --git a/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs b/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs index e47d05d..bcd7f36 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs @@ -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); } diff --git a/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs index 409c7b2..7ea15d3 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs @@ -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 { + [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(limitedClient.PostAsJsonAsync(login, + new LoginRequest("unknown@example.test", wrongPassword), Cancellation), HttpStatusCode.Unauthorized); + + for (var attempt = 0; attempt < 5; attempt++) + { + var failure = await ReadAsync(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() { diff --git a/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs b/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs index e339e20..c77d3b9 100644 --- a/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs @@ -54,6 +54,8 @@ public sealed class EmailConfirmationTests(BackendFixture fixture) : IClassFixtu var original = scope.ServiceProvider.GetRequiredService().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); diff --git a/backend/tests/Helpdesk.IntegrationTests/ProxyRateLimitTests.cs b/backend/tests/Helpdesk.IntegrationTests/ProxyRateLimitTests.cs index 84d5292..9303395 100644 --- a/backend/tests/Helpdesk.IntegrationTests/ProxyRateLimitTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/ProxyRateLimitTests.cs @@ -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, "absent@example.test")); + Assert.Equal(401, await LoginAsync(api.Server, web, secondClient, "absent@example.test")); + Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient, "absent@example.test")); } - private static async Task LoginAsync(TestServer server, string peer, string client) + private static async Task 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); diff --git a/backend/tests/Helpdesk.UnitTests/DomainTests.cs b/backend/tests/Helpdesk.UnitTests/DomainTests.cs index 48f8789..30a9fbc 100644 --- a/backend/tests/Helpdesk.UnitTests/DomainTests.cs +++ b/backend/tests/Helpdesk.UnitTests/DomainTests.cs @@ -37,46 +37,11 @@ public class EnumCodeTests public void Neznamy_kod_neprojde() => Assert.False(EnumCode.TryParse("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("jan@student.univerzita.cz", "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("JAN@STUDENT.UNIVERZITA.CZ", NewUser().EmailNormalized); + Assert.Equal("JAN@STUDENT.UNIVERZITA.CZ", User.Create("jan@student.univerzita.cz", "hash", "Jan", "Novák", UserRole.Student).EmailNormalized); } public class RegistrationRoleTests diff --git a/db/migrations/V007__remove_unused_login_lockout_columns.sql b/db/migrations/V007__remove_unused_login_lockout_columns.sql new file mode 100644 index 0000000..c3d4057 --- /dev/null +++ b/db/migrations/V007__remove_unused_login_lockout_columns.sql @@ -0,0 +1,3 @@ +ALTER TABLE app_user + DROP COLUMN IF EXISTS failed_login_count, + DROP COLUMN IF EXISTS lockout_until; diff --git a/docs/navrh-aplikace.md b/docs/navrh-aplikace.md index a15f417..278457d 100644 --- a/docs/navrh-aplikace.md +++ b/docs/navrh-aplikace.md @@ -512,7 +512,7 @@ Větvení: `main` (stabilní), `develop`, feature větve `feature/`, 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)`. diff --git a/web/Helpdesk.Web/Controllers/AccountController.cs b/web/Helpdesk.Web/Controllers/AccountController.cs index 97cbd8f..087a351 100644 --- a/web/Helpdesk.Web/Controllers/AccountController.cs +++ b/web/Helpdesk.Web/Controllers/AccountController.cs @@ -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);