Compare commits
3
Commits
0637426d5c
...
3492010cd6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3492010cd6 | ||
|
|
c9e06cd5af | ||
|
|
846145a00a |
@@ -28,22 +28,26 @@ REFRESH_EXPIRE = 604800 # 7 days
|
||||
LEGACY_USER = os.environ.get("SMETA_USER", "")
|
||||
LEGACY_PASS = os.environ.get("SMETA_PASS", "")
|
||||
|
||||
# Rate limiting
|
||||
# Rate limiting — по IP И по email. Только-IP обходится ротацией адресов:
|
||||
# атакующий брутит один аккаунт с тысяч IP. Лимит по email защищает сам аккаунт.
|
||||
# Порог по email выше (10/15мин), чтобы снизить риск lockout-DoS чужого аккаунта,
|
||||
# но всё равно делает перебор паролей бессмысленным.
|
||||
_login_attempts: dict[str, list[float]] = {}
|
||||
MAX_ATTEMPTS = 5
|
||||
MAX_ATTEMPTS = 5 # per-IP
|
||||
LOCKOUT_SECONDS = 300
|
||||
MAX_ATTEMPTS_EMAIL = 10 # per-email
|
||||
LOCKOUT_SECONDS_EMAIL = 900
|
||||
|
||||
|
||||
def _is_locked(ip: str) -> bool:
|
||||
def _is_locked(key: str, max_attempts: int = MAX_ATTEMPTS, window: int = LOCKOUT_SECONDS) -> bool:
|
||||
now = time.time()
|
||||
attempts = _login_attempts.get(ip, [])
|
||||
attempts = [t for t in attempts if now - t < LOCKOUT_SECONDS]
|
||||
_login_attempts[ip] = attempts
|
||||
return len(attempts) >= MAX_ATTEMPTS
|
||||
attempts = [t for t in _login_attempts.get(key, []) if now - t < window]
|
||||
_login_attempts[key] = attempts
|
||||
return len(attempts) >= max_attempts
|
||||
|
||||
|
||||
def _record_attempt(ip: str):
|
||||
_login_attempts.setdefault(ip, []).append(time.time())
|
||||
def _record_attempt(key: str):
|
||||
_login_attempts.setdefault(key, []).append(time.time())
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
@@ -104,7 +108,11 @@ def authenticate(username: str, password: str, client_ip: str = "") -> str | Non
|
||||
"""
|
||||
if not SECRET:
|
||||
return None
|
||||
if client_ip and _is_locked(client_ip):
|
||||
ip_key = f"ip:{client_ip}" if client_ip else None
|
||||
email_key = f"email:{username.lower().strip()}" if username else None
|
||||
if ip_key and _is_locked(ip_key, MAX_ATTEMPTS, LOCKOUT_SECONDS):
|
||||
return None
|
||||
if email_key and _is_locked(email_key, MAX_ATTEMPTS_EMAIL, LOCKOUT_SECONDS_EMAIL):
|
||||
return None
|
||||
|
||||
# 1. Legacy admin user from env vars
|
||||
@@ -118,8 +126,10 @@ def authenticate(username: str, password: str, client_ip: str = "") -> str | Non
|
||||
if user and user["verified"] and not user.get("blocked") and check_password(password, user["password_hash"]):
|
||||
return _make_token(user["email"], role=user["role"])
|
||||
|
||||
if client_ip:
|
||||
_record_attempt(client_ip)
|
||||
if ip_key:
|
||||
_record_attempt(ip_key)
|
||||
if email_key:
|
||||
_record_attempt(email_key)
|
||||
return None
|
||||
|
||||
|
||||
|
||||
+29
-3
@@ -28,6 +28,12 @@ _sessions: dict[tuple[str, str], str] = {}
|
||||
# Concurrency limit
|
||||
_semaphore = asyncio.Semaphore(3)
|
||||
|
||||
# Таймауты агентного запуска: без них зависший Docker-контейнер держит слот
|
||||
# семафора и даёт пользователю вечный спиннер. SILENCE — макс. пауза без вывода
|
||||
# (Docker-спинап и tool-паузы укладываются), DEADLINE — общий потолок на запрос.
|
||||
AGENT_READ_SILENCE = int(os.environ.get("AGENT_READ_SILENCE", "180"))
|
||||
AGENT_TOTAL_DEADLINE = int(os.environ.get("AGENT_TOTAL_DEADLINE", "600"))
|
||||
|
||||
|
||||
def _preprocess_xlsx(work_dir: Path):
|
||||
"""Convert xlsx files that openpyxl can't read into CSV + readable xlsx.
|
||||
@@ -165,8 +171,9 @@ async def stream_claude(
|
||||
f"{message}"
|
||||
)
|
||||
|
||||
# Pre-process xlsx files that openpyxl can't read → CSV
|
||||
_preprocess_xlsx(work_dir)
|
||||
# Pre-process xlsx files that openpyxl can't read → CSV.
|
||||
# В отдельном потоке: парсинг xlsx синхронный и блокирует event loop.
|
||||
await asyncio.to_thread(_preprocess_xlsx, work_dir)
|
||||
|
||||
instructions = APP_DIR / "claude_project_instructions.md"
|
||||
|
||||
@@ -275,9 +282,28 @@ async def stream_claude(
|
||||
limit=10 * 1024 * 1024,
|
||||
)
|
||||
|
||||
_loop = asyncio.get_running_loop()
|
||||
_deadline = _loop.time() + AGENT_TOTAL_DEADLINE
|
||||
|
||||
def _sse_abort(msg: str) -> str:
|
||||
# Строим без f-string: в payload есть \n, а Python <3.12 не разрешает
|
||||
# обратный слэш внутри выражения f-string.
|
||||
return ("event: text\ndata: " + json.dumps({"text": msg}, ensure_ascii=False)
|
||||
+ "\n\nevent: done\ndata: " + json.dumps({"result": ""}, ensure_ascii=False)
|
||||
+ "\n\n")
|
||||
|
||||
try:
|
||||
while True:
|
||||
raw_line = await proc.stdout.readline()
|
||||
if _loop.time() > _deadline:
|
||||
yield _sse_abort("\n\n⏱ Превышен лимит времени агента — задача прервана. Упростите запрос или повторите.")
|
||||
break
|
||||
try:
|
||||
raw_line = await asyncio.wait_for(
|
||||
proc.stdout.readline(), timeout=AGENT_READ_SILENCE
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
yield _sse_abort("\n\n⏱ Агент не отвечает (таймаут). Задача прервана.")
|
||||
break
|
||||
if not raw_line:
|
||||
break
|
||||
line = raw_line.decode().strip()
|
||||
|
||||
@@ -5,6 +5,7 @@ resources.json for code lookups, GLM-5 API for generation.
|
||||
No Docker, no subprocess — pure Python, fast.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -441,8 +442,9 @@ async def stream_claude(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Read files from work directory if they exist
|
||||
file_context = _read_work_dir_files(work_dir)
|
||||
# Read files from work directory if they exist.
|
||||
# В отдельном потоке: openpyxl/zip синхронны и на тяжёлых xlsx морозят event loop.
|
||||
file_context = await asyncio.to_thread(_read_work_dir_files, work_dir)
|
||||
|
||||
# Search normative RAG (TG posts + PDF)
|
||||
normative_context = _search_normative(message)
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Тест анти-брутфорса логина (2.4): легитимный вход работает; срабатывает лок
|
||||
по IP; срабатывает лок по EMAIL даже при ротации IP (главная защита аккаунта).
|
||||
Чистая логика authenticate(), без HTTP. Exit 1 при провале.
|
||||
|
||||
Запуск на дев-сервере (нужны SMETA_USER/SMETA_PASS из .env для позитивного кейса):
|
||||
set -a && . ./.env && set +a
|
||||
python3 tests/auth_lockout.py
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
import auth
|
||||
|
||||
U = os.environ.get("SMETA_USER", "smeta")
|
||||
P = os.environ.get("SMETA_PASS", "")
|
||||
fails = []
|
||||
|
||||
# 1. Позитив: верные креды с «чистого» IP → токен. (Успех ничего не пишет в счётчики.)
|
||||
ok_positive = auth.authenticate(U, P, "10.0.0.1") is not None
|
||||
if not ok_positive:
|
||||
fails.append("legit login failed (проверь SMETA_PASS в окружении)")
|
||||
|
||||
# 2. Лок по IP: MAX_ATTEMPTS неудач с одного IP → даже верные креды дают None.
|
||||
ip = "10.0.0.99"
|
||||
for _ in range(auth.MAX_ATTEMPTS):
|
||||
auth.authenticate(U, "wrongpass", ip)
|
||||
locked_ip = auth.authenticate(U, P, ip) is None
|
||||
if not locked_ip:
|
||||
fails.append("per-IP lockout не сработал")
|
||||
|
||||
# 3. Лок по EMAIL при РОТАЦИИ IP: каждый запрос с нового IP (по IP не залочить),
|
||||
# но email накапливает счётчик → после порога аккаунт защищён.
|
||||
victim = "victim@nonexistent.test"
|
||||
for i in range(auth.MAX_ATTEMPTS_EMAIL):
|
||||
auth.authenticate(victim, "x", f"10.1.{i}.5") # каждый IP уникален
|
||||
locked_email = auth.authenticate(victim, "x", "10.9.9.9") is None
|
||||
if not locked_email:
|
||||
fails.append("per-email lockout не сработал (ротация IP пробивает защиту)")
|
||||
|
||||
# 4. Несвязанный email не должен быть залочен побочно.
|
||||
other_free = not auth._is_locked("email:other@test", auth.MAX_ATTEMPTS_EMAIL,
|
||||
auth.LOCKOUT_SECONDS_EMAIL)
|
||||
if not other_free:
|
||||
fails.append("посторонний email ошибочно залочен")
|
||||
|
||||
print(f"positive_login={ok_positive} per_ip_lock={locked_ip} "
|
||||
f"per_email_lock={locked_email} other_free={other_free}")
|
||||
print("FAILS:", fails if fails else "none")
|
||||
sys.exit(1 if fails else 0)
|
||||
Reference in New Issue
Block a user