package ru.mtuci.messenger.service; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.dao.DataAccessException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import ru.mtuci.messenger.api.model.ErrorError; import ru.mtuci.messenger.exception.ApiException; import ru.mtuci.messenger.exception.RateLimitedException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.util.HexFormat; /** * Общий счётчик входа в Redis, поэтому две реплики API делят один лимит. * На worker и migrate Redis нет: там этот класс ничего не делает. */ @Component public class LoginLimiter { private final ObjectProvider redis; private final int perUser; private final int global; private final Duration window; public LoginLimiter(ObjectProvider redis, @Value("${app.login-limit.per-user}") int perUser, @Value("${app.login-limit.global}") int global, @Value("${app.login-limit.window}") Duration window) { this.redis = redis; this.perUser = perUser; this.global = global; this.window = window; } public void check(String username) { StringRedisTemplate template = redis.getIfAvailable(); if (template == null) { return; } try { long userRetry = hit(template, "login:user:" + digest(username), perUser); long globalRetry = hit(template, "login:global", global); long retry = Math.max(userRetry, globalRetry); if (retry > 0) { throw new RateLimitedException(retry); } } catch (RateLimitedException limited) { throw limited; } catch (DataAccessException exception) { throw new ApiException(HttpStatus.SERVICE_UNAVAILABLE, ErrorError.CodeEnum.UNAVAILABLE, "Сервис временно недоступен"); } } private long hit(StringRedisTemplate template, String key, int max) { template.opsForValue().setIfAbsent(key, "0", window); Long count = template.opsForValue().increment(key); if (count == null || count <= max) { return -1; } Long ttl = template.getExpire(key); if (ttl == null || ttl < 1) { return window.toSeconds(); } return ttl; } private static String digest(String username) { try { byte[] hash = MessageDigest.getInstance("SHA-256").digest(username.getBytes(StandardCharsets.UTF_8)); return HexFormat.of().formatHex(hash).substring(0, 16); } catch (NoSuchAlgorithmException exception) { throw new IllegalStateException(exception); } } }