forked from mtusi2026/mtusi2026lab7
Перевести пароли на Argon2id и читать секреты через AppRole.
Лимит входа общий для реплик, размер тела ограничен, исходящие клиенты проверяют TLS, если задан CA. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import hashlib
|
||||
|
||||
from app import config, rediscli
|
||||
from app.errors import AppError
|
||||
|
||||
|
||||
def _slot(prefix: str, value: str) -> str:
|
||||
digest = hashlib.sha256(value.encode("utf-8")).hexdigest()
|
||||
return prefix + digest
|
||||
|
||||
|
||||
async def reserve_login(username: str, ip: str) -> int | None:
|
||||
"""Count a login attempt on the shared Redis. Returns Retry-After seconds when limited.
|
||||
|
||||
Both replicas use the same keys, so the limit is not per process.
|
||||
The attempt is counted before Argon2 so a flood cannot spend the memory budget.
|
||||
"""
|
||||
user_key = _slot("login:u:", username[:128])
|
||||
ip_key = _slot("login:ip:", ip[:64])
|
||||
window = config.LOGIN_RATE_WINDOW_SECONDS
|
||||
try:
|
||||
redis = rediscli.require()
|
||||
async with redis.pipeline(transaction=True) as pipe:
|
||||
pipe.incr(user_key)
|
||||
pipe.expire(user_key, window, nx=True)
|
||||
pipe.incr(ip_key)
|
||||
pipe.expire(ip_key, window, nx=True)
|
||||
user_count, _, ip_count, _ = await pipe.execute()
|
||||
if user_count > config.LOGIN_RATE_LIMIT or ip_count > config.LOGIN_IP_RATE_LIMIT:
|
||||
ttl = int(await redis.ttl(user_key))
|
||||
return max(ttl, 1)
|
||||
except AppError:
|
||||
raise
|
||||
except Exception:
|
||||
raise AppError(503, "service unavailable") from None
|
||||
return None
|
||||
Reference in New Issue
Block a user