Add Redis rate limiting, login lockout, password policy and health probes

- RateLimitFilter: fixed-window counters in Redis (Lua INCR+PEXPIRE) per
  client IP for login, registration, refresh, check-login, post creation,
  uploads, chat start and public ad endpoints; 429 with Retry-After; fails
  open when Redis is down. Rules live in rate-limit.* in application.yaml.
- Login is blocked for an account after 10 failed attempts in 15 minutes,
  independent of the client IP.
- Registration requires a password of at least 8 characters.
- server.forward-headers-strategy=native so the client IP survives a reverse
  proxy; graceful shutdown.
- /actuator/health with liveness/readiness probes is public (no details).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-20 01:31:12 +03:00
parent a696a21a1f
commit 48351398b5
11 changed files with 542 additions and 9 deletions

View File

@@ -3,6 +3,7 @@ package com.krylov.refound;
import com.krylov.refound.ai.config.AiProperties; import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.config.AiRetryProperties; import com.krylov.refound.ai.config.AiRetryProperties;
import com.krylov.refound.config.MinioProperties; import com.krylov.refound.config.MinioProperties;
import com.krylov.refound.ratelimit.RateLimitProperties;
import com.krylov.refound.search.SearchProperties; import com.krylov.refound.search.SearchProperties;
import io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration; import io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
@@ -17,7 +18,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class } exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }
)@EnableScheduling )@EnableScheduling
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class, @EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class,
SearchProperties.class}) SearchProperties.class, RateLimitProperties.class})
@EnableRetry @EnableRetry
public class ReFoundApplication { public class ReFoundApplication {

View File

@@ -8,5 +8,6 @@ public enum ErrorCode {
UNAUTHORIZED, UNAUTHORIZED,
FORBIDDEN, FORBIDDEN,
CONTENT_BLOCKED, CONTENT_BLOCKED,
INVALID_STATUS_TRANSITION INVALID_STATUS_TRANSITION,
TOO_MANY_REQUESTS
} }

View File

@@ -0,0 +1,105 @@
package com.krylov.refound.ratelimit;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.krylov.refound.enums.ErrorCode;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.PathContainer;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;
/**
* Ограничение частоты запросов по IP для уязвимых маршрутов: вход и регистрация
* (перебор паролей, спам аккаунтами), публичный трекинг рекламы (накрутка),
* загрузка файлов и создание объявлений. Правила — {@code rate-limit.rules}.
*
* <p>IP берётся из {@code request.getRemoteAddr()}; за обратным прокси он
* восстанавливается из X-Forwarded-For (server.forward-headers-strategy=native).
* При превышении — 429 с заголовком Retry-After в формате ErrorResponse.
*/
@Slf4j
@Component
public class RateLimitFilter extends OncePerRequestFilter {
private final RedisRateLimiter rateLimiter;
private final RateLimitProperties properties;
private final ObjectMapper objectMapper;
private final List<CompiledRule> rules;
record CompiledRule(RateLimitProperties.Rule rule, List<PathPattern> patterns) {
boolean matches(HttpServletRequest request, PathContainer path) {
String method = rule.getMethod();
if (method != null && !method.isBlank() && !method.equalsIgnoreCase(request.getMethod())) {
return false;
}
return patterns.stream().anyMatch(pattern -> pattern.matches(path));
}
}
public RateLimitFilter(RedisRateLimiter rateLimiter, RateLimitProperties properties, ObjectMapper objectMapper) {
this.rateLimiter = rateLimiter;
this.properties = properties;
this.objectMapper = objectMapper;
PathPatternParser parser = new PathPatternParser();
this.rules = properties.getRules().stream()
.map(rule -> new CompiledRule(rule, rule.getPaths().stream().map(parser::parse).toList()))
.toList();
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return !properties.isEnabled() || rules.isEmpty();
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
PathContainer path = PathContainer.parsePath(request.getRequestURI().substring(request.getContextPath().length()));
String clientIp = request.getRemoteAddr();
for (CompiledRule compiled : rules) {
if (!compiled.matches(request, path)) {
continue;
}
RateLimitProperties.Rule rule = compiled.rule();
RedisRateLimiter.Decision decision = rateLimiter.hit(rule.getName(), clientIp, rule.getLimit(), rule.getWindow());
if (!decision.allowed()) {
log.warn("Rate limit '{}' превышен: ip={}, {} {}", rule.getName(), clientIp, request.getMethod(),
request.getRequestURI());
writeTooManyRequests(request, response, decision.retryAfterSeconds());
return;
}
}
filterChain.doFilter(request, response);
}
private void writeTooManyRequests(HttpServletRequest request, HttpServletResponse response, long retryAfter)
throws IOException {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("status", HttpStatus.TOO_MANY_REQUESTS.value());
body.put("error", ErrorCode.TOO_MANY_REQUESTS.name());
body.put("message", "Слишком много запросов, повторите позже");
body.put("path", request.getRequestURI());
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.setHeader(HttpHeaders.RETRY_AFTER, Long.toString(retryAfter));
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
objectMapper.writeValue(response.getWriter(), body);
}
}

View File

@@ -0,0 +1,49 @@
package com.krylov.refound.ratelimit;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Лимиты запросов ({@code rate-limit.*} в application.yaml). Счётчики лежат в
* Redis, поэтому лимит общий для всех экземпляров приложения.
*/
@Getter
@Setter
@ConfigurationProperties(prefix = "rate-limit")
public class RateLimitProperties {
/** Выключатель всех лимитов (например, для нагрузочных тестов). */
private boolean enabled = true;
/** Правила по маршрутам; ключ лимита — IP клиента. */
private List<Rule> rules = new ArrayList<>();
/** Защита конкретного аккаунта от перебора пароля с разных IP. */
private Login login = new Login();
@Getter
@Setter
public static class Rule {
/** Имя правила — часть ключа в Redis. */
private String name;
/** HTTP-метод; пусто — любой. */
private String method;
/** Шаблоны путей в стиле Spring MVC ({@code /api/v1/auth/login}, {@code /api/ads/**}). */
private List<String> paths = new ArrayList<>();
/** Сколько запросов разрешено за окно. */
private int limit;
private Duration window = Duration.ofMinutes(1);
}
@Getter
@Setter
public static class Login {
/** Сколько неудачных входов в один аккаунт допускается за окно. */
private int maxFailures = 10;
private Duration window = Duration.ofMinutes(15);
}
}

View File

@@ -0,0 +1,83 @@
package com.krylov.refound.ratelimit;
import java.time.Duration;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
/**
* Счётчик с фиксированным окном в Redis: ключ {@code rl:<правило>:<субъект>:<номер окна>},
* INCR и EXPIRE выполняются одним Lua-скриптом (атомарно, без «вечных» ключей).
*
* <p>Лимиты — защитный слой, а не бизнес-логика: при недоступном Redis запрос
* пропускается (fail-open), чтобы сбой кэша не положил весь API.
*/
@Slf4j
@Component
public class RedisRateLimiter {
private static final RedisScript<Long> INCREMENT = new DefaultRedisScript<>("""
local count = redis.call('INCR', KEYS[1])
if count == 1 then
redis.call('PEXPIRE', KEYS[1], ARGV[1])
end
return count
""", Long.class);
private final StringRedisTemplate redisTemplate;
public RedisRateLimiter(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
/** Результат проверки: разрешён ли запрос и через сколько секунд откроется окно. */
public record Decision(boolean allowed, long count, long retryAfterSeconds) {
static Decision allow() {
return new Decision(true, 0, 0);
}
}
/** Учитывает запрос и решает, укладывается ли он в лимит. */
public Decision hit(String rule, String subject, int limit, Duration window) {
long windowMillis = window.toMillis();
long now = System.currentTimeMillis();
long windowIndex = now / windowMillis;
String key = "rl:" + rule + ":" + subject + ":" + windowIndex;
try {
Long count = redisTemplate.execute(INCREMENT, List.of(key), Long.toString(windowMillis));
if (count == null) {
return Decision.allow();
}
long retryAfter = Math.max(1, ((windowIndex + 1) * windowMillis - now + 999) / 1000);
return new Decision(count <= limit, count, retryAfter);
} catch (RuntimeException e) {
log.warn("Rate limit '{}' не проверен, Redis недоступен: {}", rule, e.getMessage());
return Decision.allow();
}
}
/** Сбрасывает текущее окно (например, после успешного входа). */
public void reset(String rule, String subject, Duration window) {
long windowIndex = System.currentTimeMillis() / window.toMillis();
try {
redisTemplate.delete("rl:" + rule + ":" + subject + ":" + windowIndex);
} catch (RuntimeException e) {
log.debug("Rate limit '{}' не сброшен: {}", rule, e.getMessage());
}
}
/** Текущее значение счётчика без увеличения (0, если ключа нет или Redis недоступен). */
public long current(String rule, String subject, Duration window) {
long windowIndex = System.currentTimeMillis() / window.toMillis();
try {
String value = redisTemplate.opsForValue().get("rl:" + rule + ":" + subject + ":" + windowIndex);
return value == null ? 0 : Long.parseLong(value);
} catch (RuntimeException e) {
return 0;
}
}
}

View File

@@ -49,6 +49,8 @@ public class SecurityConfig {
.authorizeHttpRequests(auth -> auth .authorizeHttpRequests(auth -> auth
// публичные эндпоинты // публичные эндпоинты
.requestMatchers("/api/v1/auth/**").permitAll() .requestMatchers("/api/v1/auth/**").permitAll()
// health-пробы балансировщика/оркестратора (без деталей состояния)
.requestMatchers(HttpMethod.GET, "/actuator/health", "/actuator/health/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/files/**").permitAll() .requestMatchers(HttpMethod.GET, "/api/v1/files/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/ads-media/**").permitAll() .requestMatchers(HttpMethod.GET, "/api/v1/ads-media/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/posts/**").permitAll() .requestMatchers(HttpMethod.GET, "/api/v1/posts/**").permitAll()
@@ -68,7 +70,6 @@ public class SecurityConfig {
// реклама // реклама
.requestMatchers(HttpMethod.GET, "/api/ads/next").permitAll() .requestMatchers(HttpMethod.GET, "/api/ads/next").permitAll()
.requestMatchers(HttpMethod.POST, "/api/ads/impression").permitAll() .requestMatchers(HttpMethod.POST, "/api/ads/impression").permitAll()
.requestMatchers(HttpMethod.POST, "/api/ads/impression/beacon").permitAll()
.requestMatchers(HttpMethod.POST, "/api/ads/click").permitAll() .requestMatchers(HttpMethod.POST, "/api/ads/click").permitAll()
.requestMatchers(HttpMethod.GET, "/api/fullscreen-ad").permitAll() .requestMatchers(HttpMethod.GET, "/api/fullscreen-ad").permitAll()

View File

@@ -8,13 +8,18 @@ import com.krylov.refound.dto.RegisterRequest;
import com.krylov.refound.dto.user.UserDto; import com.krylov.refound.dto.user.UserDto;
import com.krylov.refound.dto.user.UserRegisterDto; import com.krylov.refound.dto.user.UserRegisterDto;
import com.krylov.refound.entity.User; import com.krylov.refound.entity.User;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.exception.InvalidCredentialsException; import com.krylov.refound.exception.InvalidCredentialsException;
import com.krylov.refound.exception.LoginAlreadyExistsException; import com.krylov.refound.exception.LoginAlreadyExistsException;
import com.krylov.refound.ratelimit.RateLimitProperties;
import com.krylov.refound.ratelimit.RedisRateLimiter;
import com.krylov.refound.repository.UserRepository; import com.krylov.refound.repository.UserRepository;
import com.krylov.refound.security.JwtService; import com.krylov.refound.security.JwtService;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -26,13 +31,17 @@ import org.springframework.util.StringUtils;
public class AuthService { public class AuthService {
private static final int MAX_LOGIN_LENGTH = 255; private static final int MAX_LOGIN_LENGTH = 255;
private static final int MIN_PASSWORD_LENGTH = 1; /** Минимум по рекомендациям NIST SP 800-63B для паролей, выбранных пользователем. */
private static final int MIN_PASSWORD_LENGTH = 8;
private static final String LOGIN_FAILURES_RULE = "login-failures";
private static final int MAX_PASSWORD_BYTES = 72; private static final int MAX_PASSWORD_BYTES = 72;
private final UserRepository userRepository; private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
private final JwtService jwtService; private final JwtService jwtService;
private final RefreshTokenService refreshTokenService; private final RefreshTokenService refreshTokenService;
private final RedisRateLimiter rateLimiter;
private final RateLimitProperties rateLimitProperties;
public UserRegisterDto registerUser(RegisterRequest request) { public UserRegisterDto registerUser(RegisterRequest request) {
validateRegistration(request); validateRegistration(request);
@@ -55,12 +64,26 @@ public class AuthService {
} }
public UserRegisterDto loginUser(AuthRequest request) { public UserRegisterDto loginUser(AuthRequest request) {
User user = request.getLogin() == null ? null : userRepository.findByLogin(request.getLogin()).orElse(null); String login = request.getLogin();
// Перебор пароля одного аккаунта с разных IP: лимит по IP (RateLimitFilter) тут не спасает
RateLimitProperties.Login loginLimit = rateLimitProperties.getLogin();
if (login != null && rateLimitProperties.isEnabled()
&& rateLimiter.current(LOGIN_FAILURES_RULE, login, loginLimit.getWindow()) >= loginLimit.getMaxFailures()) {
log.warn("login blocked: too many failed attempts for {}", login);
throw new ApiException(ErrorCode.TOO_MANY_REQUESTS,
"Слишком много неудачных попыток входа, повторите позже", HttpStatus.TOO_MANY_REQUESTS);
}
User user = login == null ? null : userRepository.findByLogin(login).orElse(null);
if (user == null || request.getPassword() == null || !passwordEncoder.matches(request.getPassword(), user.getPassword())) { if (user == null || request.getPassword() == null || !passwordEncoder.matches(request.getPassword(), user.getPassword())) {
log.warn("login failed: login or password incorrect for {}", request.getLogin()); log.warn("login failed: login or password incorrect for {}", login);
if (login != null) {
rateLimiter.hit(LOGIN_FAILURES_RULE, login, loginLimit.getMaxFailures(), loginLimit.getWindow());
}
throw new InvalidCredentialsException("Неверный логин или пароль"); throw new InvalidCredentialsException("Неверный логин или пароль");
} }
rateLimiter.reset(LOGIN_FAILURES_RULE, login, loginLimit.getWindow());
String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name()); String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
String refreshToken = refreshTokenService.issue(user.getLogin()); String refreshToken = refreshTokenService.issue(user.getLogin());
@@ -102,8 +125,8 @@ public class AuthService {
// BCrypt учитывает только первые 72 байта пароля // BCrypt учитывает только первые 72 байта пароля
if (password == null || password.length() < MIN_PASSWORD_LENGTH if (password == null || password.length() < MIN_PASSWORD_LENGTH
|| password.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) { || password.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) {
throw new InvalidCredentialsException("Пароль должен быть от " + MIN_PASSWORD_LENGTH + " до " throw new InvalidCredentialsException("Пароль должен быть не короче " + MIN_PASSWORD_LENGTH
+ MAX_PASSWORD_BYTES + " символов"); + " символов и не длиннее " + MAX_PASSWORD_BYTES + " байт");
} }
} }

View File

@@ -1,7 +1,16 @@
ffmpeg: ffmpeg:
binary-path: ${FFMPEG_PATH:C:\ffmpeg\ffmpeg-9.0.2-essentials_build\bin\ffmpeg.exe} binary-path: ${FFMPEG_PATH:C:\ffmpeg\ffmpeg-9.0.2-essentials_build\bin\ffmpeg.exe}
server:
# За обратным прокси (nginx, балансировщик) IP клиента и схема берутся из
# X-Forwarded-*: без этого лимиты считали бы все запросы с адреса прокси.
# Tomcat доверяет заголовкам только от внутренних адресов (10/8, 172.16/12, 192.168/16, 127/8).
forward-headers-strategy: ${FORWARD_HEADERS_STRATEGY:native}
shutdown: graceful
spring: spring:
lifecycle:
timeout-per-shutdown-phase: 20s
servlet: servlet:
multipart: multipart:
max-file-size: 10MB max-file-size: 10MB
@@ -96,4 +105,74 @@ jwt:
app: app:
cors: cors:
allowed-origins: ${CORS_ALLOWED_ORIGINS:http://localhost:5173,http://localhost:3000,http://192.168.1.76:3000} allowed-origins: ${CORS_ALLOWED_ORIGINS:http://localhost:5173,http://localhost:3000,http://192.168.1.76:3000}
websocket:
# Рассылка STOMP-сообщений во все экземпляры через Redis pub/sub (ClusterMessaging)
cluster-broadcast: ${WS_CLUSTER_BROADCAST:true}
# Health-пробы для оркестратора/балансировщика: /actuator/health/liveness и /readiness
# открыты без токена (SecurityConfig), подробности состояния наружу не отдаются
management:
endpoints:
web:
exposure:
include: health
endpoint:
health:
probes:
enabled: true
show-details: never
# Лимиты запросов по IP (RateLimitFilter), счётчики в Redis — общие для всех экземпляров
rate-limit:
enabled: ${RATE_LIMIT_ENABLED:true}
login:
max-failures: 10 # неудачных входов в один аккаунт
window: PT15M
rules:
- name: auth-login
method: POST
paths: [/api/v1/auth/login]
limit: 20
window: PT1M
- name: auth-register
method: POST
paths: [/api/v1/auth/register]
limit: 10
window: PT1H
- name: auth-refresh
method: POST
paths: [/api/v1/auth/refresh]
limit: 60
window: PT1M
- name: auth-check-login
method: GET
paths: [/api/v1/auth/check-login]
limit: 60
window: PT1M
- name: post-create
method: POST
paths: [/api/v1/posts]
limit: 20
window: PT1H
- name: file-upload
method: POST
paths: [/api/v1/files]
limit: 60
window: PT1H
- name: chat-start
method: POST
paths: [/api/v1/chats/with/**]
limit: 30
window: PT1M
- name: ads-next
method: GET
paths: [/api/ads/next, /api/fullscreen-ad]
limit: 120
window: PT1M
- name: ads-tracking
method: POST
paths: [/api/ads/impression, /api/ads/click]
limit: 120
window: PT1M

View File

@@ -0,0 +1,99 @@
package com.krylov.refound.ratelimit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import jakarta.servlet.FilterChain;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
class RateLimitFilterTest {
private RedisRateLimiter limiter;
private RateLimitFilter filter;
@BeforeEach
void setUp() {
limiter = mock(RedisRateLimiter.class);
RateLimitProperties properties = new RateLimitProperties();
RateLimitProperties.Rule rule = new RateLimitProperties.Rule();
rule.setName("auth-login");
rule.setMethod("POST");
rule.setPaths(List.of("/api/v1/auth/login"));
rule.setLimit(5);
rule.setWindow(Duration.ofMinutes(1));
properties.setRules(List.of(rule));
filter = new RateLimitFilter(limiter, properties, new ObjectMapper().registerModule(new JavaTimeModule()));
}
@Test
void requestOverLimitGets429WithRetryAfter() throws Exception {
when(limiter.hit(eq("auth-login"), eq("10.0.0.1"), eq(5), any()))
.thenReturn(new RedisRateLimiter.Decision(false, 6, 42));
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request("POST", "/api/v1/auth/login"), response, chain);
assertThat(response.getStatus()).isEqualTo(429);
assertThat(response.getHeader("Retry-After")).isEqualTo("42");
assertThat(response.getContentAsString()).contains("TOO_MANY_REQUESTS");
verify(chain, never()).doFilter(any(), any());
}
@Test
void requestWithinLimitPasses() throws Exception {
when(limiter.hit(anyString(), anyString(), anyInt(), any()))
.thenReturn(new RedisRateLimiter.Decision(true, 1, 60));
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request("POST", "/api/v1/auth/login"), new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(), any());
}
@Test
void otherRoutesAndMethodsAreNotCounted() throws Exception {
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request("GET", "/api/v1/auth/login"), new MockHttpServletResponse(), chain);
filter.doFilter(request("POST", "/api/v1/posts"), new MockHttpServletResponse(), chain);
verify(limiter, never()).hit(anyString(), anyString(), anyInt(), any());
}
@Test
@SuppressWarnings("unchecked")
void limiterFailsOpenWhenRedisIsDown() {
StringRedisTemplate redis = mock(StringRedisTemplate.class);
when(redis.execute(any(RedisScript.class), anyList(), any(Object[].class)))
.thenThrow(new RedisConnectionFailureException("down"));
RedisRateLimiter.Decision decision = new RedisRateLimiter(redis).hit("auth-login", "ip", 1, Duration.ofMinutes(1));
assertThat(decision.allowed()).isTrue();
}
private static MockHttpServletRequest request(String method, String uri) {
MockHttpServletRequest request = new MockHttpServletRequest(method, uri);
request.setRemoteAddr("10.0.0.1");
return request;
}
}

View File

@@ -0,0 +1,84 @@
package com.krylov.refound.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.krylov.refound.dto.AuthRequest;
import com.krylov.refound.dto.RegisterRequest;
import com.krylov.refound.entity.User;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.exception.InvalidCredentialsException;
import com.krylov.refound.ratelimit.RateLimitProperties;
import com.krylov.refound.ratelimit.RedisRateLimiter;
import com.krylov.refound.repository.UserRepository;
import com.krylov.refound.security.JwtService;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
class AuthServiceTest {
private UserRepository userRepository;
private RedisRateLimiter rateLimiter;
private PasswordEncoder passwordEncoder;
private AuthService service;
@BeforeEach
void setUp() {
userRepository = mock(UserRepository.class);
rateLimiter = mock(RedisRateLimiter.class);
passwordEncoder = new BCryptPasswordEncoder(4);
service = new AuthService(userRepository, passwordEncoder, mock(JwtService.class),
mock(RefreshTokenService.class), rateLimiter, new RateLimitProperties());
}
@Test
void accountIsLockedAfterTooManyFailures() {
when(rateLimiter.current(eq("login-failures"), eq("alice"), any())).thenReturn(10L);
assertThatThrownBy(() -> service.loginUser(auth("alice", "whatever")))
.isInstanceOfSatisfying(ApiException.class,
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS));
verify(userRepository, never()).findByLogin(anyString());
}
@Test
void failedLoginIsCounted() {
User alice = new User();
alice.setLogin("alice");
alice.setPassword(passwordEncoder.encode("correct-password"));
when(userRepository.findByLogin("alice")).thenReturn(Optional.of(alice));
assertThatThrownBy(() -> service.loginUser(auth("alice", "wrong-password")))
.isInstanceOf(InvalidCredentialsException.class);
verify(rateLimiter).hit(eq("login-failures"), eq("alice"), anyInt(), any());
}
@Test
void shortPasswordIsRejectedOnRegistration() {
RegisterRequest request = new RegisterRequest();
request.setLogin("alice");
request.setPassword("1234567");
assertThatThrownBy(() -> service.registerUser(request)).isInstanceOf(InvalidCredentialsException.class);
verify(userRepository, never()).save(any());
}
private static AuthRequest auth(String login, String password) {
AuthRequest request = new AuthRequest();
request.setLogin(login);
request.setPassword(password);
return request;
}
}

View File

@@ -15,3 +15,11 @@ minio:
endpoint: http://127.0.0.1:1 endpoint: http://127.0.0.1:1
access-key: test-only-access-key access-key: test-only-access-key
secret-key: test-only-secret-key secret-key: test-only-secret-key
app:
websocket:
# Без подписки на канал Redis: в тестах Redis нет
cluster-broadcast: false
rate-limit:
enabled: false