Files
mtusi2026lab7/app/ratelimit.py
T
dawudukandCursor fb566d874c Перевести пароли на Argon2id и читать секреты через AppRole.
Лимит входа общий для реплик, размер тела ограничен, исходящие клиенты проверяют TLS, если задан CA.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-26 19:40:28 +03:00

37 lines
1.3 KiB
Python

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