🌊 Волна 14: backend #6 — security + БД (8 багов + бонус)
Security: - cf_connecting_ip_spoof: whitelist CF_IPS, доверие только от Cloudflare (config.py + main.py) БД: - get_pool_race: asyncio.Lock вокруг create_pool (database.py) - init_db_no_transaction: обёрнут в conn.transaction() (database.py) - drop_constraint_cascade: убран CASCADE (database.py) - add_pk_on_duplicates: DELETE дублей перед ADD PK (database.py) - redundant_index_users_telegram: удалены дубли индексов (database.py) - fstring_sql_migration: whitelist regex (database.py) Качество: - cleanup_task_not_cancelled: cancel в shutdown (main.py) Бонус: - removed_images: обработка удалённых картинок в feed.py (TODO из v1) Пропущено осознанно: - matview_if_not_exists_stale (Alembic, отдельно) - initdata_in_query_param (fallback для deleteFeedPost) Аудит v3: Issue #6, backend 8/10 задач
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import ipaddress
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
@@ -10,7 +11,7 @@ from fastapi import FastAPI, Request, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from config import FRONTEND_ORIGIN, UPLOADS_DIR
|
||||
from config import FRONTEND_ORIGIN, UPLOADS_DIR, CF_IPS
|
||||
from database import init_db
|
||||
from routers import users, game, hints, leaderboard, sentences, achievements, wordquiz, bubblewords, pronunciation, assistant, learning, tts, typing, teacher, support, admin, feed, admin_content
|
||||
from routers.sentences import init_sentences
|
||||
@@ -125,6 +126,25 @@ class RateLimiter:
|
||||
rate_limiter = RateLimiter()
|
||||
|
||||
|
||||
# 🔧 ФИКС (24.09.2026): cf_connecting_ip_spoof —
|
||||
# проверяем, что IP клиента входит в список Cloudflare.
|
||||
def _is_cloudflare_ip(ip_str: str) -> bool:
|
||||
"""Проверяет, что IP входит в CF_IPS (Cloudflare)."""
|
||||
if not ip_str:
|
||||
return False
|
||||
try:
|
||||
ip = ipaddress.ip_address(ip_str)
|
||||
except ValueError:
|
||||
return False
|
||||
for cidr in CF_IPS:
|
||||
try:
|
||||
if ip in ipaddress.ip_network(cidr, strict=False):
|
||||
return True
|
||||
except ValueError:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
# ============ Фоновое обновление кэша рейтинга ============
|
||||
async def refresh_leaderboard_cache_loop():
|
||||
await asyncio.sleep(10)
|
||||
@@ -151,7 +171,9 @@ async def lifespan(app: FastAPI):
|
||||
await init_achievements()
|
||||
await init_learning_data()
|
||||
|
||||
asyncio.create_task(rate_limiter.start_cleanup())
|
||||
# 🔧 ФИКС (24.09.2026): cleanup_task_not_cancelled —
|
||||
# сохраняем ссылку и отменяем в shutdown.
|
||||
cleanup_task = asyncio.create_task(rate_limiter.start_cleanup())
|
||||
|
||||
from database import get_pool
|
||||
pool = await get_pool()
|
||||
@@ -218,6 +240,14 @@ async def lifespan(app: FastAPI):
|
||||
except asyncio.CancelledError:
|
||||
logger.info("Leaderboard refresh task cancelled")
|
||||
|
||||
# 🔧 ФИКС (24.09.2026): cleanup_task_not_cancelled —
|
||||
# отменяем cleanup-задачу rate limiter.
|
||||
cleanup_task.cancel()
|
||||
try:
|
||||
await cleanup_task
|
||||
except asyncio.CancelledError:
|
||||
logger.info("Rate limiter cleanup task cancelled")
|
||||
|
||||
logger.info(f"Filwords API v{APP_VERSION} stopped")
|
||||
|
||||
|
||||
@@ -232,16 +262,22 @@ async def rate_limit_middleware(request: Request, call_next):
|
||||
if path in ["/", "/health"]:
|
||||
return await call_next(request)
|
||||
|
||||
# 🔧 ФИКС (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")
|
||||
)
|
||||
# 🔧 ФИКС (24.09.2026): cf_connecting_ip_spoof —
|
||||
# доверяем cf-connecting-ip ТОЛЬКО если запрос пришёл с IP Cloudflare.
|
||||
# Иначе — берём request.client.host (реальный IP клиента).
|
||||
real_client_ip = request.client.host if request.client else "unknown"
|
||||
|
||||
if _is_cloudflare_ip(real_client_ip):
|
||||
# Запрос от Cloudflare — доверяем cf-connecting-ip
|
||||
client_ip = (
|
||||
request.headers.get("cf-connecting-ip")
|
||||
or request.headers.get("x-real-ip")
|
||||
or real_client_ip
|
||||
)
|
||||
else:
|
||||
# Запрос не от Cloudflare — игнорируем заголовки, берём реальный IP
|
||||
client_ip = real_client_ip
|
||||
|
||||
rate_key = f"{client_ip}:{path}"
|
||||
|
||||
if not rate_limiter.is_allowed(rate_key, path):
|
||||
|
||||
Reference in New Issue
Block a user