forked from mtusi2026/mtusi2026lab7
Grade 4
This commit is contained in:
+39
-1
@@ -3,6 +3,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from threading import BoundedSemaphore
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
@@ -11,7 +12,28 @@ from redis import Redis
|
||||
|
||||
from .errors import APIError
|
||||
|
||||
password_hasher = PasswordHasher()
|
||||
hash_slots = BoundedSemaphore(2)
|
||||
|
||||
|
||||
class BoundedHasher(PasswordHasher):
|
||||
def hash(self, password, **kwargs):
|
||||
if not hash_slots.acquire(blocking=False):
|
||||
raise APIError(429, 'rate_limited', 'Повторите попытку позже')
|
||||
try:
|
||||
return super().hash(password, **kwargs)
|
||||
finally:
|
||||
hash_slots.release()
|
||||
|
||||
def verify(self, encoded, password):
|
||||
if not hash_slots.acquire(blocking=False):
|
||||
raise APIError(429, 'rate_limited', 'Повторите попытку позже')
|
||||
try:
|
||||
return super().verify(encoded, password)
|
||||
finally:
|
||||
hash_slots.release()
|
||||
|
||||
|
||||
password_hasher = BoundedHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
dummy_hash = password_hasher.hash(secrets.token_urlsafe(32))
|
||||
|
||||
|
||||
@@ -32,6 +54,7 @@ class Sessions:
|
||||
os.getenv('REDIS_URL', 'redis://redis:6379/0'), decode_responses=True,
|
||||
socket_connect_timeout=1, socket_timeout=1, max_connections=20,
|
||||
retry_on_timeout=False,
|
||||
ssl_ca_certs='/run/identity/ca.crt', ssl_check_hostname=True,
|
||||
)
|
||||
self.ttl = int(os.getenv('SESSION_TTL_SECONDS', '3600'))
|
||||
if self.ttl < 1:
|
||||
@@ -66,3 +89,18 @@ class Sessions:
|
||||
|
||||
|
||||
sessions = Sessions()
|
||||
|
||||
|
||||
def password_budget(subject):
|
||||
"""Atomic, shared fixed windows before any expensive hash (including registration)."""
|
||||
digest = hashlib.sha256(subject.encode()).hexdigest()
|
||||
allowed = sessions.client.eval('''
|
||||
local global = redis.call('INCR', KEYS[1])
|
||||
if global == 1 then redis.call('EXPIRE', KEYS[1], 1) end
|
||||
local account = redis.call('INCR', KEYS[2])
|
||||
if account == 1 then redis.call('EXPIRE', KEYS[2], 10) end
|
||||
if global > 32 or account > 8 then return 0 end
|
||||
return 1
|
||||
''', 2, 'login:global', 'login:' + digest)
|
||||
if not allowed:
|
||||
raise APIError(429, 'rate_limited', 'Повторите попытку позже')
|
||||
|
||||
Reference in New Issue
Block a user