fix(admin): limit password attempts
This commit is contained in:
1 parent
d3920c8156
commit
b78f211292
4 files changed
+43
-3
No files matched your search
+27
@@ -27,10 +27,14 @@ _IDENTITY_DIR: IdentityDirectory | None = None
|
||||
_APPLICATION_STORE: ApplicationStore | None = None
|
||||
_ADMIN_SESSIONS: set[str] = set()
|
||||
_ISSUED_WEB_UPLOAD_URLS: set[str] = set()
|
||||
_ADMIN_AUTH_ATTEMPTS: dict[str, list[float]] = {}
|
||||
_ADMIN_AUTH_LOCK = threading.Lock()
|
||||
MAX_JSON_BODY_BYTES = 20 * 1024 * 1024
|
||||
MAX_UPLOAD_BYTES = 15 * 1024 * 1024
|
||||
REQUEST_READ_TIMEOUT_SECONDS = 15
|
||||
MAX_CONCURRENT_REQUESTS = 32
|
||||
ADMIN_AUTH_WINDOW_SECONDS = 15 * 60
|
||||
MAX_ADMIN_AUTH_ATTEMPTS = 5
|
||||
|
||||
|
||||
def detect_raster_image_type(body: bytes) -> str | None:
|
||||
@@ -67,6 +71,24 @@ def validate_web_attachments(value: object) -> list[dict]:
|
||||
return attachments
|
||||
|
||||
|
||||
def allow_admin_auth_attempt(client_ip: str, *, now: float | None = None) -> bool:
|
||||
"""Apply a bounded per-source budget to the password-only admin login."""
|
||||
timestamp = time.monotonic() if now is None else now
|
||||
with _ADMIN_AUTH_LOCK:
|
||||
attempts = [item for item in _ADMIN_AUTH_ATTEMPTS.get(client_ip, []) if timestamp - item < ADMIN_AUTH_WINDOW_SECONDS]
|
||||
if len(attempts) >= MAX_ADMIN_AUTH_ATTEMPTS:
|
||||
_ADMIN_AUTH_ATTEMPTS[client_ip] = attempts
|
||||
return False
|
||||
attempts.append(timestamp)
|
||||
_ADMIN_AUTH_ATTEMPTS[client_ip] = attempts
|
||||
return True
|
||||
|
||||
|
||||
def clear_admin_auth_attempts(client_ip: str) -> None:
|
||||
with _ADMIN_AUTH_LOCK:
|
||||
_ADMIN_AUTH_ATTEMPTS.pop(client_ip, None)
|
||||
|
||||
|
||||
def history_store() -> CalculationStore:
|
||||
global _HISTORY_STORE
|
||||
if _HISTORY_STORE is None:
|
||||
@@ -266,10 +288,15 @@ class Handler(BaseHTTPRequestHandler):
|
||||
try:
|
||||
payload = self._read_json_body()
|
||||
if self.path == "/api/admin/auth":
|
||||
client_ip = self.client_address[0]
|
||||
if not allow_admin_auth_attempt(client_ip):
|
||||
self._json(429, {"error": "Слишком много попыток. Повторите через 15 минут."})
|
||||
return
|
||||
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
|
||||
if not expected or not secrets.compare_digest(str(payload.get("password", "")), expected):
|
||||
self._json(401, {"error": "Неверный пароль"})
|
||||
return
|
||||
clear_admin_auth_attempts(client_ip)
|
||||
token = secrets.token_urlsafe(32)
|
||||
_ADMIN_SESSIONS.add(token)
|
||||
self._json_with_cookie(200, {"authenticated": True}, self._admin_cookie(token))
|
||||
|
||||
Reference in new issue
Block a user