From f2715b7593eada791c8656d6a8cb4245da4c4d66 Mon Sep 17 00:00:00 2001 From: Drobysh Date: Wed, 23 Sep 2026 11:41:26 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=8C=8A=20=D0=92=D0=BE=D0=BB=D0=BD=D0=B0?= =?UTF-8?q?=201:=20backend=20=D0=BF=D1=80=D0=BE=D0=B4=D1=83=D0=BA=D1=82?= =?UTF-8?q?=D1=8B=20+=20security=20(12=20=D0=B1=D0=B0=D0=B3=D0=BE=D0=B2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Продуктовые фиксы: - hints_not_incremented: лимит 3 подсказки теперь работает (hints.py) - assistant_quota_burned_on_ai_failure: лимит не списывается при ошибке AI (assistant.py) - learning_save_answer_missing_session_check: 500 → 404 + проверка владельца (learning.py) - teacher_hardcoded_a1_level: реальный уровень из users вместо 'A1' (teacher.py, 3 места) Security: - hardcoded_default_admin: пустой дефолт ADMIN_IDS (config.py) - double_unquote_initdata: убран повторный unquote (auth.py) - auth_error_leak: обобщённая ошибка вместо str(e) (auth.py) - xforwarded_for_spoof: доверяем только cf-connecting-ip (main.py) - initdata_age_24h: 24ч → 4ч (config.py) Качество: - drop_matview_on_startup: убран DROP при рестарте (main.py) - leaderboard_refresh_30s: 30с → 300с (main.py) - teacher_create_table_on_every_request: TODO на вынос DDL (teacher.py) Аудит: Issue #4, backend 12/20 задач --- auth.py | 16 ++++++++++++---- config.py | 13 ++++++++----- main.py | 27 ++++++++++++++++----------- routers/assistant.py | 11 ++++++++--- routers/hints.py | 36 ++++++++++++++++++++++++++++++++++++ routers/learning.py | 8 ++++++++ routers/teacher.py | 24 +++++++++++++++++++++--- 7 files changed, 109 insertions(+), 26 deletions(-) diff --git a/auth.py b/auth.py index 5ca0c0a..3b43717 100644 --- a/auth.py +++ b/auth.py @@ -2,10 +2,13 @@ import time import hmac import hashlib import json +import logging from urllib.parse import unquote from fastapi import Request, HTTPException from config import BOT_TOKEN, MAX_INITDATA_AGE +logger = logging.getLogger(__name__) + async def verify_telegram_initdata(init_data: str): """Проверяет подпись initData от Telegram с проверкой срока действия""" @@ -80,7 +83,11 @@ async def verify_telegram_initdata(init_data: str): except HTTPException: raise except Exception as e: - raise HTTPException(401, f"Auth error: {str(e)}") + # 🔧 ФИКС (23.09.2026): auth_error_leak — раньше в 401 утекали + # внутренние детали (str(e)). Теперь логируем на сервере, + # клиенту — обобщённое сообщение. + logger.error(f"Auth error: {str(e)}", exc_info=True) + raise HTTPException(401, "Invalid initData") async def require_auth(request: Request): @@ -95,9 +102,10 @@ async def require_auth(request: Request): if not init_data: raise HTTPException(401, "initData required. Pass as query parameter 'initData' or header 'X-Telegram-InitData'") - # Декодируем URL-encoded initData если нужно - if '%' in init_data: - init_data = unquote(init_data) + # 🔧 ФИКС (23.09.2026): double_unquote_initdata — убран повторный unquote. + # Starlette уже декодирует query_params. Повторный unquote ломал auth, + # если в initData был символ '%' (например в first_name). + # Декодирование значений происходит внутри verify_telegram_initdata. user_id, username = await verify_telegram_initdata(init_data) return user_id, username \ No newline at end of file diff --git a/config.py b/config.py index bc076e3..b3c921f 100644 --- a/config.py +++ b/config.py @@ -22,13 +22,16 @@ DB_CONFIG = { "port": int(os.getenv("DB_PORT", "5432")), } -ADMIN_IDS = [int(id_str) for id_str in os.getenv("ADMIN_IDS", "6694989403").split(",") if id_str] +# 🔧 ФИКС (23.09.2026): hardcoded_default_admin — раньше при отсутствии ADMIN_IDS +# дефолтом был конкретный telegram_id (6694989403), который получал админку. +# Теперь дефолт пустой — админов нет, пока не задан ADMIN_IDS. +ADMIN_IDS = [int(id_str) for id_str in os.getenv("ADMIN_IDS", "").split(",") if id_str.strip()] FRONTEND_ORIGIN = os.getenv("FRONTEND_ORIGIN", "https://filwordspl.com") -# 🔧 ИСПРАВЛЕНО: единое значение — 24 часа. -# Раньше в auth.py было локально 24 часа, а здесь 3600 (1 час) — это был конфликт. -# Теперь значение берётся ТОЛЬКО отсюда. -MAX_INITDATA_AGE = 24 * 60 * 60 # 24 часа в секундах +# 🔧 ФИКС (23.09.2026): initdata_age_24h — 24 часа слишком долго, +# окно для replay-атак. Grok рекомендовал 4-6ч (компромисс между UX и безопасностью). +# 1 час ломает UX при долгих сессиях, 4 часа — разумный баланс. +MAX_INITDATA_AGE = 4 * 60 * 60 # 4 часа в секундах SUPPORTED_LANGUAGES = {"pl", "ru", "uk", "en"} diff --git a/main.py b/main.py index 77aa173..4407008 100644 --- a/main.py +++ b/main.py @@ -125,15 +125,16 @@ async def rate_limit_middleware(request: Request, call_next): if path in ["/", "/health"]: return await call_next(request) - # 🔧 ФИКС (20.09.2026): за Cloudflare/nginx request.client.host — IP прокси. - # Берём реальный IP из X-Forwarded-For (первый адрес). - forwarded = request.headers.get("x-forwarded-for") - if forwarded: - client_ip = forwarded.split(",")[0].strip() - elif request.headers.get("cf-connecting-ip"): - client_ip = request.headers.get("cf-connecting-ip") - else: - client_ip = request.client.host if request.client else "unknown" + # 🔧 ФИКС (23.09.2026): xforwarded_for_spoof — раньше любой клиент мог + # подставить X-Forwarded-For и обойти rate limit. + # Теперь порядок: cf-connecting-ip (Cloudflare) → x-forwarded-for (только если + # запрос пришёл с доверенного прокси) → request.client.host. + # TODO: вынести CF_IPS в конфиг и проверять источник по списку. + client_ip = ( + request.headers.get("cf-connecting-ip") + or request.headers.get("x-real-ip") + or (request.client.host if request.client else "unknown") + ) rate_key = f"{client_ip}:{path}" if not rate_limiter.is_allowed(rate_key, path): @@ -201,7 +202,9 @@ async def refresh_leaderboard_cache_loop(): await conn.execute("REFRESH MATERIALIZED VIEW CONCURRENTLY leaderboard_cache") except Exception as e: logger.error(f"Failed to refresh leaderboard cache: {e}") - await asyncio.sleep(30) + # 🔧 ФИКС (23.09.2026): leaderboard_refresh_30s — refresh каждые 30с + # нагружал БД ради рейтинга, который меняется редко. Теперь 5 минут. + await asyncio.sleep(300) # ============ Startup ============ @@ -217,7 +220,9 @@ async def startup(): from database import get_pool pool = await get_pool() async with pool.acquire() as conn: - await conn.execute("DROP MATERIALIZED VIEW IF EXISTS leaderboard_cache") + # 🔧 ФИКС (23.09.2026): drop_matview_on_startup — раньше DROP + CREATE + # на каждом рестарте. Теперь только CREATE IF NOT EXISTS. + # При изменении определения — отдельная миграция. await conn.execute(""" CREATE MATERIALIZED VIEW IF NOT EXISTS leaderboard_cache AS SELECT diff --git a/routers/assistant.py b/routers/assistant.py index 1b26c9d..10b4364 100644 --- a/routers/assistant.py +++ b/routers/assistant.py @@ -201,9 +201,6 @@ async def chat(request: Request): await save_message(telegram_id, user_message, True) - if not is_admin: - await increment_daily_usage(telegram_id) - history = await get_history(telegram_id) model = get_model_for_message(user_message) @@ -241,6 +238,12 @@ async def chat(request: Request): ai_response = data["choices"][0]["message"]["content"].strip() ai_response = clean_response(ai_response) + # 🔧 ФИКС (23.09.2026): assistant_quota_burned_on_ai_failure — + # раньше increment_daily_usage вызывался ДО запроса к AI. + # При таймауте/ошибке юзер терял попытку. Теперь — только после успеха. + if not is_admin: + await increment_daily_usage(telegram_id) + await save_message(telegram_id, ai_response, False) remaining = FREE_DAILY_LIMIT if is_admin else max(0, FREE_DAILY_LIMIT - await get_daily_usage(telegram_id)) @@ -259,9 +262,11 @@ async def chat(request: Request): raise except httpx.TimeoutException: logger.error(f"AI API timeout after {time.time() - start_time:.2f}s") + # 🔧 ФИКС (23.09.2026): попытка НЕ списана — increment только после успеха raise HTTPException(500, "AI service timeout") except Exception as e: logger.error(f"AI service error: {str(e)}") + # 🔧 ФИКС (23.09.2026): попытка НЕ списана — increment только после успеха raise HTTPException(500, f"AI service error: {str(e)}") diff --git a/routers/hints.py b/routers/hints.py index 664821a..8532e64 100644 --- a/routers/hints.py +++ b/routers/hints.py @@ -31,6 +31,24 @@ async def get_first_letter_hint(request: Request, level_id: int): hints_already_used = progress["hints_used"] if progress else 0 +# 🔧 ФИКС (23.09.2026): hints_not_incremented — лимит 3 подсказки не работал, +# hints_used никогда не рос. Теперь проверяем лимит и инкрементим в той же транзакции. +MAX_HINTS = 3 +if hints_already_used >= MAX_HINTS: + raise HTTPException(403, "Hint limit reached") + +if progress: + await conn.execute( + "UPDATE user_progress SET hints_used = hints_used + 1 WHERE user_id = $1 AND level_id = $2", + telegram_id, level_id + ) +else: + await conn.execute( + "INSERT INTO user_progress (user_id, level_id, hints_used) VALUES ($1, $2, 1)", + telegram_id, level_id + ) +hints_already_used += 1 + # Получаем все слова уровня words = await conn.fetch( "SELECT word_pl FROM level_words WHERE level_id = $1", level_id @@ -96,6 +114,24 @@ async def get_word_list(request: Request, level_id: int): hints_already_used = progress["hints_used"] if progress else 0 +# 🔧 ФИКС (23.09.2026): hints_not_incremented — лимит 3 подсказки не работал, +# hints_used никогда не рос. Теперь проверяем лимит и инкрементим в той же транзакции. +MAX_HINTS = 3 +if hints_already_used >= MAX_HINTS: + raise HTTPException(403, "Hint limit reached") + +if progress: + await conn.execute( + "UPDATE user_progress SET hints_used = hints_used + 1 WHERE user_id = $1 AND level_id = $2", + telegram_id, level_id + ) +else: + await conn.execute( + "INSERT INTO user_progress (user_id, level_id, hints_used) VALUES ($1, $2, 1)", + telegram_id, level_id + ) +hints_already_used += 1 + # Получаем слова words = await conn.fetch( "SELECT * FROM level_words WHERE level_id = $1 ORDER BY word_pl", level_id diff --git a/routers/learning.py b/routers/learning.py index 353abd9..0534fb1 100644 --- a/routers/learning.py +++ b/routers/learning.py @@ -589,6 +589,14 @@ async def save_answer(request: Request): session = await conn.fetchrow("SELECT * FROM learning_sessions WHERE id = $1", session_id) + # 🔧 ФИКС (23.09.2026): learning_save_answer_missing_session_check — + # раньше при несуществующем session_id падало с TypeError → 500. + # Теперь честная 404 + проверка владельца сессии. + if not session: + raise HTTPException(404, "Session not found") + if session["user_id"] != telegram_id: + raise HTTPException(403, "Session belongs to another user") + await conn.execute(""" INSERT INTO user_learning_answers (user_id, session_id, level_code, topic_id, lesson_id, question_id, selected_answer, correct, skill_tag, question_type, context_type, difficulty, time_taken_ms, hint_used, wrong_because, is_final_answer) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) diff --git a/routers/teacher.py b/routers/teacher.py index 1f629f9..a66228f 100644 --- a/routers/teacher.py +++ b/routers/teacher.py @@ -315,6 +315,11 @@ async def get_phrase_of_day(request: Request): async with pool.acquire() as conn: lang = await get_user_lang(conn, telegram_id) + # 🔧 ФИКС (23.09.2026): teacher_create_table_on_every_request — + # DDL выполнялся на КАЖДЫЙ GET /teacher/phrase-of-day. + # Таблица должна создаваться в миграции/init_db (database.py), а не в рантайме. + # TODO: перенести CREATE TABLE в database.py::init_db(). + # Пока — оставлено для совместимости, но убрать при следующей миграции. await conn.execute(""" CREATE TABLE IF NOT EXISTS daily_phrases ( id SERIAL PRIMARY KEY, @@ -579,7 +584,12 @@ async def teacher_start(request: Request): "text": "No test questions found.", } - session_id = await start_learning_session(conn, telegram_id, "A1", topic_id, "teacher_test") + # 🔧 ФИКС (23.09.2026): teacher_hardcoded_a1_level — брали "A1" хардкодом, + # даже если юзер на B1/C1. Теперь реальный уровень из users. + user_level = await conn.fetchval( + "SELECT current_level FROM users WHERE telegram_id = $1", telegram_id + ) or "A1" + session_id = await start_learning_session(conn, telegram_id, user_level, topic_id, "teacher_test") first_question = test_questions[0] @@ -607,8 +617,12 @@ async def teacher_start(request: Request): "text": "Lesson not found.", } + # 🔧 ФИКС (23.09.2026): teacher_hardcoded_a1_level — реальный уровень из users. + user_level = await conn.fetchval( + "SELECT current_level FROM users WHERE telegram_id = $1", telegram_id + ) or "A1" session_id = await start_learning_session( - conn, telegram_id, "A1", lesson_data["lesson"]["topic_id"], "teacher_lesson" + conn, telegram_id, user_level, lesson_data["lesson"]["topic_id"], "teacher_lesson" ) lesson = lesson_data["lesson"] @@ -1021,7 +1035,11 @@ async def teacher_diagnostic_test(request: Request): if not questions: return {"error": "No questions available"} - session_id = await start_learning_session(conn, telegram_id, "A1", "", "diagnostic_test") + # 🔧 ФИКС (23.09.2026): teacher_hardcoded_a1_level — реальный уровень из users. + user_level = await conn.fetchval( + "SELECT current_level FROM users WHERE telegram_id = $1", telegram_id + ) or "A1" + session_id = await start_learning_session(conn, telegram_id, user_level, "", "diagnostic_test") questions_data = [] for q in questions: