From f41fcf01b56074333f94a975dba3e23cd5b0a57e Mon Sep 17 00:00:00 2001 From: anor Date: Tue, 24 Mar 2026 18:35:45 +1000 Subject: [PATCH] =?UTF-8?q?fix(security):=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=83=D1=8F=D0=B7=D0=B2?= =?UTF-8?q?=D0=B8=D0=BC=D0=BE=D1=81=D1=82=D0=B5=D0=B9=20=D0=BF=D0=BE=20?= =?UTF-8?q?=D1=80=D0=B5=D0=B7=D1=83=D0=BB=D1=8C=D1=82=D0=B0=D1=82=D0=B0?= =?UTF-8?q?=D0=BC=20=D0=B0=D1=83=D0=B4=D0=B8=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- auth.py | 54 +++++++++++++--- claude_bridge.py | 158 ++++++++++++++++++++++++++++------------------- main.py | 45 ++++++++++---- static/chat.html | 9 ++- 4 files changed, 178 insertions(+), 88 deletions(-) diff --git a/auth.py b/auth.py index 83e0244..c4e734c 100644 --- a/auth.py +++ b/auth.py @@ -1,30 +1,68 @@ """JWT authentication — single user from env vars.""" +import hmac +import logging import os import time from jose import jwt -SECRET = os.environ.get("SESSION_SECRET", "change-me-in-production") -ALGORITHM = "HS256" -TOKEN_EXPIRE = 86400 * 7 # 7 days +logger = logging.getLogger(__name__) -VALID_USER = os.environ.get("SMETA_USER", "smeta") +# #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 authenticate(username: str, password: str) -> str | None: + +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 VALID_PASS: - return None # password must be set - if username == VALID_USER and password == VALID_PASS: + 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") diff --git a/claude_bridge.py b/claude_bridge.py index af06954..db984ac 100644 --- a/claude_bridge.py +++ b/claude_bridge.py @@ -9,11 +9,14 @@ from typing import AsyncGenerator CLAUDE_BIN = os.environ.get( "CLAUDE_BIN", os.path.expanduser("~/.npm-global/bin/claude") ) -DATA_DIR = Path(os.environ.get("DATA_DIR", "/tmp/smeta-web-data")) +DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) APP_DIR = Path(__file__).parent -# Session tracking: tab_id -> claude session_id -_sessions: dict[str, str] = {} +# Session tracking: (username, tab_id) -> claude session_id (#12) +_sessions: dict[tuple[str, str], str] = {} + +# Concurrency limit (#11 DoS) +_semaphore = asyncio.Semaphore(3) def get_work_dir(username: str, tab_id: str) -> Path: @@ -22,16 +25,43 @@ def get_work_dir(username: str, tab_id: str) -> Path: return d -def get_session_id(tab_id: str) -> str | None: - return _sessions.get(tab_id) +def get_session_id(username: str, tab_id: str) -> str | None: + return _sessions.get((username, tab_id)) -def set_session_id(tab_id: str, sid: str): - _sessions[tab_id] = sid +def set_session_id(username: str, tab_id: str, sid: str): + _sessions[(username, tab_id)] = sid -def clear_session(tab_id: str): - _sessions.pop(tab_id, None) +def clear_session(username: str, tab_id: str): + _sessions.pop((username, tab_id), None) + + +# Whitelist of allowed file extensions (#6) +ALLOWED_EXTENSIONS = { + ".xlsx", ".xls", ".docx", ".doc", ".pdf", + ".csv", ".txt", ".xml", ".json", ".yaml", ".yml", +} + + +def is_allowed_file(filename: str) -> bool: + return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS + + +# Minimal env for subprocess (#7 — don't leak all env vars) +def _build_claude_env() -> dict[str, str]: + env = { + "HOME": os.environ.get("HOME", "/home/mcp-user"), + "PATH": os.environ.get("PATH", "/usr/bin:/bin"), + "LANG": os.environ.get("LANG", "en_US.UTF-8"), + "HTTPS_PROXY": os.environ.get("HTTPS_PROXY", "http://127.0.0.1:10809"), + "HTTP_PROXY": os.environ.get("HTTP_PROXY", "http://127.0.0.1:10809"), + } + # Claude Code needs XDG dirs + for k in ("XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "NODE_PATH"): + if k in os.environ: + env[k] = os.environ[k] + return env async def stream_claude( @@ -40,71 +70,69 @@ async def stream_claude( tab_id: str = "default", ) -> AsyncGenerator[str, None]: """Run claude CLI, yield SSE-formatted events.""" - work_dir = get_work_dir(username, tab_id) - session_id = get_session_id(tab_id) + async with _semaphore: + work_dir = get_work_dir(username, tab_id) + session_id = get_session_id(username, tab_id) - instructions = APP_DIR / "claude_project_instructions.md" + instructions = APP_DIR / "claude_project_instructions.md" - cmd = [ - CLAUDE_BIN, "-p", message, - "--output-format", "stream-json", - "--verbose", - "--allowedTools", "Bash,Read,Write,Edit,Glob,Grep", - ] - if instructions.exists(): - cmd.extend(["--append-system-prompt-file", str(instructions)]) - if session_id: - cmd.extend(["--resume", session_id]) + cmd = [ + CLAUDE_BIN, "-p", message, + "--output-format", "stream-json", + "--verbose", + "--allowedTools", "Bash,Read,Write,Edit,Glob,Grep", + ] + if instructions.exists(): + cmd.extend(["--append-system-prompt-file", str(instructions)]) + if session_id: + cmd.extend(["--resume", session_id]) - env = os.environ.copy() - # Proxy for Anthropic API (xray on server) - env.setdefault("HTTPS_PROXY", "http://127.0.0.1:10809") - env.setdefault("HTTP_PROXY", "http://127.0.0.1:10809") + env = _build_claude_env() - proc = await asyncio.create_subprocess_exec( - *cmd, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, - cwd=str(work_dir), - env=env, - ) + proc = await asyncio.create_subprocess_exec( + *cmd, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + cwd=str(work_dir), + env=env, + ) - try: - while True: - raw_line = await proc.stdout.readline() - if not raw_line: - break - line = raw_line.decode().strip() - if not line: - continue - try: - event = json.loads(line) - except json.JSONDecodeError: - continue + try: + while True: + raw_line = await proc.stdout.readline() + if not raw_line: + break + line = raw_line.decode().strip() + if not line: + continue + try: + event = json.loads(line) + except json.JSONDecodeError: + continue - etype = event.get("type", "") + etype = event.get("type", "") - if etype == "assistant": - msg = event.get("message", {}) - for block in msg.get("content", []): - if block.get("type") == "text": - text = block["text"] - yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n" - elif block.get("type") == "tool_use": - name = block.get("name", "") - yield f"event: tool\ndata: {json.dumps({'tool': name}, ensure_ascii=False)}\n\n" + if etype == "assistant": + msg = event.get("message", {}) + for block in msg.get("content", []): + if block.get("type") == "text": + text = block["text"] + yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n" + elif block.get("type") == "tool_use": + name = block.get("name", "") + yield f"event: tool\ndata: {json.dumps({'tool': name}, ensure_ascii=False)}\n\n" - elif etype == "result": - sid = event.get("session_id", "") - if sid: - set_session_id(tab_id, sid) - result_text = event.get("result", "") - yield f"event: done\ndata: {json.dumps({'result': result_text}, ensure_ascii=False)}\n\n" + elif etype == "result": + sid = event.get("session_id", "") + if sid: + set_session_id(username, tab_id, sid) + result_text = event.get("result", "") + yield f"event: done\ndata: {json.dumps({'result': result_text}, ensure_ascii=False)}\n\n" - finally: - if proc.returncode is None: - proc.terminate() - await proc.wait() + finally: + if proc.returncode is None: + proc.terminate() + await proc.wait() def list_user_files(username: str, tab_id: str = "default") -> list[dict]: diff --git a/main.py b/main.py index 3783102..e66065f 100644 --- a/main.py +++ b/main.py @@ -12,6 +12,7 @@ from auth import authenticate, verify_token from claude_bridge import ( clear_session, get_work_dir, + is_allowed_file, list_user_files, stream_claude, ) @@ -20,6 +21,7 @@ app = FastAPI(title="smeta-web") app.mount("/static", StaticFiles(directory="static"), name="static") MAX_UPLOAD_SIZE = 50 * 1024 * 1024 # 50 MB +MAX_MESSAGE_LEN = 10_000 # #14 DoS: limit prompt length def _get_user(request: Request) -> str: @@ -51,7 +53,8 @@ async def login(request: Request): body = await request.json() username = body.get("username", "") password = body.get("password", "") - token = authenticate(username, password) + client_ip = request.client.host if request.client else "" + token = authenticate(username, password, client_ip) if not token: raise HTTPException(401, "Wrong credentials") return {"token": token, "username": username} @@ -65,6 +68,8 @@ async def chat(request: Request): tab_id = _get_tab(request, body) if not message: raise HTTPException(400, "Empty message") + if len(message) > MAX_MESSAGE_LEN: + raise HTTPException(400, f"Message too long (max {MAX_MESSAGE_LEN} chars)") return StreamingResponse( stream_claude(message, user, tab_id), @@ -82,16 +87,32 @@ async def upload(request: Request, file: UploadFile): tab_id = request.headers.get("x-tab-id", "default") work_dir = get_work_dir(user, tab_id) - content = await file.read() - if len(content) > MAX_UPLOAD_SIZE: - raise HTTPException(413, f"File too large (max {MAX_UPLOAD_SIZE // 1024 // 1024}MB)") - safe_name = Path(file.filename).name if not safe_name or safe_name.startswith("."): raise HTTPException(400, "Invalid filename") + + # #6 HIGH: whitelist file extensions + if not is_allowed_file(safe_name): + raise HTTPException( + 400, + f"File type not allowed. Allowed: xlsx, docx, pdf, csv, txt, xml, json, yaml", + ) + + # #15: read in chunks to avoid OOM on huge files + chunks = [] + total = 0 + while True: + chunk = await file.read(1024 * 1024) # 1MB chunks + if not chunk: + break + total += len(chunk) + if total > MAX_UPLOAD_SIZE: + raise HTTPException(413, f"File too large (max {MAX_UPLOAD_SIZE // 1024 // 1024}MB)") + chunks.append(chunk) + dest = work_dir / safe_name - dest.write_bytes(content) - return {"filename": safe_name, "size": len(content)} + dest.write_bytes(b"".join(chunks)) + return {"filename": safe_name, "size": total} @app.get("/api/files") @@ -115,17 +136,15 @@ async def download_file(filename: str, request: Request): @app.post("/api/reset") async def reset_session(request: Request): user = _get_user(request) - body = await request.json() - tab_id = _get_tab(request, body) - clear_session(tab_id) + tab_id = request.headers.get("x-tab-id", "default") + clear_session(user, tab_id) return {"status": "ok"} @app.post("/api/clear-files") async def clear_files(request: Request): user = _get_user(request) - body = await request.json() - tab_id = _get_tab(request, body) + tab_id = request.headers.get("x-tab-id", "default") work_dir = get_work_dir(user, tab_id) for f in work_dir.iterdir(): if f.name.startswith("."): @@ -134,7 +153,7 @@ async def clear_files(request: Request): f.unlink() elif f.is_dir(): shutil.rmtree(f) - clear_session(tab_id) + clear_session(user, tab_id) return {"status": "ok"} diff --git a/static/chat.html b/static/chat.html index 30de7a7..6ac4bfc 100644 --- a/static/chat.html +++ b/static/chat.html @@ -186,7 +186,12 @@ function renderFileList() { pendingFiles.forEach((f, i) => { const badge = document.createElement('span'); badge.className = 'file-badge'; - badge.innerHTML = f.name + ' ×'; + badge.textContent = f.name + ' '; + const rm = document.createElement('span'); + rm.className = 'remove'; + rm.textContent = '×'; + rm.onclick = () => removeFile(i); + badge.appendChild(rm); fl.appendChild(badge); }); } @@ -310,7 +315,7 @@ async function sendMessage() { // --- Session --- async function resetSession() { - await fetch(API + '/api/reset', {method: 'POST', headers: authHeaders()}); + await fetch(API + '/api/reset', {method: 'POST', headers: {...authHeaders(), 'Content-Type': 'application/json'}, body: '{}'}); msgs.innerHTML = ''; addMsg('system', 'Новый диалог начат.'); }