- 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>
84 lines
3.5 KiB
Java
84 lines
3.5 KiB
Java
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;
|
||
}
|
||
}
|
||
}
|