From f7650d9fd622b463a60033d4b27aec32467704f1 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Sun, 15 Feb 2026 08:25:12 -0700 Subject: [PATCH] feat: add login rate limiting to prevent brute-force attacks (#2761) --- .../service/AuthenticationService.java | 8 ++++ .../service/LoginRateLimitService.java | 45 +++++++++++++++++++ .../java/org/booklore/exception/ApiError.java | 3 +- .../org/booklore/model/enums/AuditAction.java | 3 +- .../components/login/login.component.ts | 2 + booklore-ui/src/i18n/en/auth.json | 3 +- booklore-ui/src/i18n/es/auth.json | 3 +- 7 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 booklore-api/src/main/java/org/booklore/config/security/service/LoginRateLimitService.java diff --git a/booklore-api/src/main/java/org/booklore/config/security/service/AuthenticationService.java b/booklore-api/src/main/java/org/booklore/config/security/service/AuthenticationService.java index cbb391e8a..06cf2db3a 100644 --- a/booklore-api/src/main/java/org/booklore/config/security/service/AuthenticationService.java +++ b/booklore-api/src/main/java/org/booklore/config/security/service/AuthenticationService.java @@ -28,6 +28,7 @@ import java.util.Map; import java.util.Optional; import org.booklore.model.enums.AuditAction; import org.booklore.service.audit.AuditService; +import org.booklore.util.RequestUtils; @Slf4j @AllArgsConstructor @@ -42,6 +43,7 @@ public class AuthenticationService { private final JwtUtils jwtUtils; private final DefaultSettingInitializer defaultSettingInitializer; private final AuditService auditService; + private final LoginRateLimitService loginRateLimitService; public BookLoreUser getAuthenticatedUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); @@ -90,16 +92,22 @@ public class AuthenticationService { } public ResponseEntity> loginUser(UserLoginRequest loginRequest) { + String ip = RequestUtils.getCurrentRequest().getRemoteAddr(); + loginRateLimitService.checkRateLimit(ip); + BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> { auditService.log(AuditAction.LOGIN_FAILED, "Login failed for unknown user: " + loginRequest.getUsername()); + loginRateLimitService.recordFailedAttempt(ip); return ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()); }); if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) { auditService.log(AuditAction.LOGIN_FAILED, "Login failed for user: " + loginRequest.getUsername()); + loginRateLimitService.recordFailedAttempt(ip); throw ApiError.INVALID_CREDENTIALS.createException(); } + loginRateLimitService.resetAttempts(ip); return loginUser(user); } diff --git a/booklore-api/src/main/java/org/booklore/config/security/service/LoginRateLimitService.java b/booklore-api/src/main/java/org/booklore/config/security/service/LoginRateLimitService.java new file mode 100644 index 000000000..3ef0d7de3 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/config/security/service/LoginRateLimitService.java @@ -0,0 +1,45 @@ +package org.booklore.config.security.service; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import lombok.extern.slf4j.Slf4j; +import org.booklore.exception.ApiError; +import org.booklore.model.enums.AuditAction; +import org.booklore.service.audit.AuditService; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +@Service +public class LoginRateLimitService { + + private static final int MAX_ATTEMPTS = 5; + + private final Cache attemptCache; + private final AuditService auditService; + + public LoginRateLimitService(AuditService auditService) { + this.auditService = auditService; + this.attemptCache = Caffeine.newBuilder() + .expireAfterWrite(Duration.ofMinutes(15)) + .build(); + } + + public void checkRateLimit(String ip) { + AtomicInteger attempts = attemptCache.getIfPresent(ip); + if (attempts != null && attempts.get() >= MAX_ATTEMPTS) { + auditService.log(AuditAction.LOGIN_RATE_LIMITED, "Login rate limited for IP: " + ip); + throw ApiError.RATE_LIMITED.createException(); + } + } + + public void recordFailedAttempt(String ip) { + attemptCache.get(ip, k -> new AtomicInteger(0)).incrementAndGet(); + } + + public void resetAttempts(String ip) { + attemptCache.invalidate(ip); + } +} diff --git a/booklore-api/src/main/java/org/booklore/exception/ApiError.java b/booklore-api/src/main/java/org/booklore/exception/ApiError.java index 823f0ffa6..d8e896b4e 100644 --- a/booklore-api/src/main/java/org/booklore/exception/ApiError.java +++ b/booklore-api/src/main/java/org/booklore/exception/ApiError.java @@ -62,7 +62,8 @@ public enum ApiError { DEMO_USER_PASSWORD_CHANGE_NOT_ALLOWED(HttpStatus.FORBIDDEN, "Demo user password change not allowed."), PERMISSION_DENIED(HttpStatus.FORBIDDEN, "Permission denied: %s"), LIBRARY_PATH_NOT_ACCESSIBLE(HttpStatus.SERVICE_UNAVAILABLE, "Library scan aborted: path not accessible or empty: %s"), - FORMAT_NOT_ALLOWED(HttpStatus.BAD_REQUEST, "File format '%s' is not allowed in library '%s'"); + FORMAT_NOT_ALLOWED(HttpStatus.BAD_REQUEST, "File format '%s' is not allowed in library '%s'"), + RATE_LIMITED(HttpStatus.TOO_MANY_REQUESTS, "Too many failed login attempts. Please try again later."); private final HttpStatus status; private final String message; diff --git a/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java b/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java index 3b04635e0..53a1a76c3 100644 --- a/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java +++ b/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java @@ -31,5 +31,6 @@ public enum AuditAction { OPDS_USER_CREATED, OPDS_USER_DELETED, OPDS_USER_UPDATED, - NAMING_PATTERN_CHANGED + NAMING_PATTERN_CHANGED, + LOGIN_RATE_LIMITED } diff --git a/booklore-ui/src/app/shared/components/login/login.component.ts b/booklore-ui/src/app/shared/components/login/login.component.ts index 2abdea706..b1f2c2087 100644 --- a/booklore-ui/src/app/shared/components/login/login.component.ts +++ b/booklore-ui/src/app/shared/components/login/login.component.ts @@ -89,6 +89,8 @@ export class LoginComponent implements OnInit, OnDestroy { error: (error) => { if (error.status === 0) { this.errorMessage = this.translocoService.translate('auth.login.connectionError'); + } else if (error.status === 429) { + this.errorMessage = this.translocoService.translate('auth.login.rateLimited'); } else { this.errorMessage = error?.error?.message || this.translocoService.translate('auth.login.unexpectedError'); } diff --git a/booklore-ui/src/i18n/en/auth.json b/booklore-ui/src/i18n/en/auth.json index 5668b70e9..ce99edd8f 100644 --- a/booklore-ui/src/i18n/en/auth.json +++ b/booklore-ui/src/i18n/en/auth.json @@ -23,6 +23,7 @@ "useLocalLogin": "Use Local Login", "oidcAutoDisabled": "{{provider}} authentication has been automatically disabled after {{count}} consecutive failures (including timeouts). You can retry or continue with local login.", "oidcManuallyDisabled": "{{provider}} authentication has been manually disabled. You can re-enable it or continue with local login.", - "oidcErrors": "{{provider}} authentication encountered {{count}} error(s), possibly due to timeouts or server issues." + "oidcErrors": "{{provider}} authentication encountered {{count}} error(s), possibly due to timeouts or server issues.", + "rateLimited": "Too many failed login attempts. Please try again later." } } diff --git a/booklore-ui/src/i18n/es/auth.json b/booklore-ui/src/i18n/es/auth.json index 7d83012f3..0ab74992e 100644 --- a/booklore-ui/src/i18n/es/auth.json +++ b/booklore-ui/src/i18n/es/auth.json @@ -23,6 +23,7 @@ "useLocalLogin": "Usar inicio local", "oidcAutoDisabled": "La autenticación de {{provider}} se desactivó automáticamente tras {{count}} fallos consecutivos (incluidos tiempos de espera). Puedes reintentar o continuar con el inicio de sesión local.", "oidcManuallyDisabled": "La autenticación de {{provider}} se desactivó manualmente. Puedes reactivarla o continuar con el inicio de sesión local.", - "oidcErrors": "La autenticación de {{provider}} encontró {{count}} error(es), posiblemente por tiempos de espera o problemas del servidor." + "oidcErrors": "La autenticación de {{provider}} encontró {{count}} error(es), posiblemente por tiempos de espera o problemas del servidor.", + "rateLimited": "Demasiados intentos de inicio de sesión fallidos. Inténtalo de nuevo más tarde." } }