Files
smeta-web/auth.py
T
anorandClaude Opus 4.6 f41fcf01b5 fix(security): исправление уязвимостей по результатам аудита
CRITICAL:
- #1 JWT секрет: убран fallback, fail-fast без SESSION_SECRET
- #7 env leak: минимальный env для subprocess (не os.environ.copy())

HIGH:
- #4 timing attack: hmac.compare_digest вместо ==
- #5 brute force: rate limiting 5 попыток / 5 мин на IP
- #6 upload: whitelist расширений (xlsx, docx, pdf, csv, txt, xml, json, yaml)

MEDIUM:
- #9 XSS: textContent вместо innerHTML для имён файлов
- #10 token expire: 24ч вместо 7 дней
- #11 DoS: asyncio.Semaphore(3) на Claude-процессы
- #12 session isolation: ключ (username, tab_id) вместо tab_id
- #14 DoS: лимит длины сообщения 10000 символов
- #15 OOM: чтение upload по чанкам 1MB

LOW:
- #19 reset endpoint: POST с body

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 18:35:45 +10:00

71 lines
1.9 KiB
Python

"""JWT authentication — single user from env vars."""
import hmac
import logging
import os
import time
from jose import jwt
logger = logging.getLogger(__name__)
# #1 CRITICAL: no fallback — fail loudly if not set
SECRET = os.environ.get("SESSION_SECRET", "")
if not SECRET:
logger.warning("SESSION_SECRET not set! Auth will reject all tokens.")
ALGORITHM = "HS256"
TOKEN_EXPIRE = 86400 # 24 hours (was 7 days — #11)
VALID_USER = os.environ.get("SMETA_USER", "")
VALID_PASS = os.environ.get("SMETA_PASS", "")
# Login rate limiting (#5)
_login_attempts: dict[str, list[float]] = {}
MAX_ATTEMPTS = 5
LOCKOUT_SECONDS = 300
def _is_locked(ip: str) -> bool:
now = time.time()
attempts = _login_attempts.get(ip, [])
# Remove old attempts
attempts = [t for t in attempts if now - t < LOCKOUT_SECONDS]
_login_attempts[ip] = attempts
return len(attempts) >= MAX_ATTEMPTS
def _record_attempt(ip: str):
_login_attempts.setdefault(ip, []).append(time.time())
def authenticate(username: str, password: str, client_ip: str = "") -> str | None:
"""Return JWT token if credentials are valid, else None."""
if not SECRET or not VALID_PASS or not VALID_USER:
return None
if client_ip and _is_locked(client_ip):
return None
# #4 HIGH: constant-time comparison
user_ok = hmac.compare_digest(username, VALID_USER)
pass_ok = hmac.compare_digest(password, VALID_PASS)
if user_ok and pass_ok:
payload = {"sub": username, "exp": int(time.time()) + TOKEN_EXPIRE}
return jwt.encode(payload, SECRET, algorithm=ALGORITHM)
if client_ip:
_record_attempt(client_ip)
return None
def verify_token(token: str) -> str | None:
"""Return username if token is valid, else None."""
if not SECRET:
return None
try:
payload = jwt.decode(token, SECRET, algorithms=[ALGORITHM])
return payload.get("sub")
except Exception:
return None