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

View File

@@ -8,5 +8,6 @@ public enum ErrorCode {
UNAUTHORIZED,
FORBIDDEN,
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
// публичные эндпоинты
.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/ads-media/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/posts/**").permitAll()
@@ -68,7 +70,6 @@ public class SecurityConfig {
// реклама
.requestMatchers(HttpMethod.GET, "/api/ads/next").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.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.UserRegisterDto;
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.LoginAlreadyExistsException;
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.nio.charset.StandardCharsets;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@@ -26,13 +31,17 @@ import org.springframework.util.StringUtils;
public class AuthService {
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 final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
private final RefreshTokenService refreshTokenService;
private final RedisRateLimiter rateLimiter;
private final RateLimitProperties rateLimitProperties;
public UserRegisterDto registerUser(RegisterRequest request) {
validateRegistration(request);
@@ -55,12 +64,26 @@ public class AuthService {
}
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())) {
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("Неверный логин или пароль");
}
rateLimiter.reset(LOGIN_FAILURES_RULE, login, loginLimit.getWindow());
String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
String refreshToken = refreshTokenService.issue(user.getLogin());
@@ -102,8 +125,8 @@ public class AuthService {
// BCrypt учитывает только первые 72 байта пароля
if (password == null || password.length() < MIN_PASSWORD_LENGTH
|| password.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) {
throw new InvalidCredentialsException("Пароль должен быть от " + MIN_PASSWORD_LENGTH + " до "
+ MAX_PASSWORD_BYTES + " символов");
throw new InvalidCredentialsException("Пароль должен быть не короче " + MIN_PASSWORD_LENGTH
+ " символов и не длиннее " + MAX_PASSWORD_BYTES + " байт");
}
}