🌊 Волна 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:
+60
-2
@@ -424,7 +424,8 @@ async def admin_update_feed_post(request: Request, post_id: int):
|
||||
"is_pinned": true/false,
|
||||
"is_published": true/false,
|
||||
"expires_at": "..." | null,
|
||||
"translate_again": true — перевести заново через AI
|
||||
"translate_again": true, — перевести заново через AI
|
||||
"removed_images": ["..."] — 🔧 ФИКС (24.09.2026): URL'ы удалённых картинок
|
||||
}
|
||||
"""
|
||||
telegram_id, _ = await require_auth(request)
|
||||
@@ -443,6 +444,38 @@ async def admin_update_feed_post(request: Request, post_id: int):
|
||||
|
||||
source_language = existing["source_language"]
|
||||
|
||||
# 🔧 ФИКС (24.09.2026): existing_image_removal_no_delete —
|
||||
# обрабатываем удалённые картинки: удаляем из БД и с диска.
|
||||
removed_images = body.get("removed_images", [])
|
||||
if removed_images and isinstance(removed_images, list):
|
||||
for img_url in removed_images:
|
||||
# img_url приходит как полный URL: https://api.filwordspl.com/uploads/feed/...
|
||||
# или относительный: /uploads/feed/...
|
||||
# Приводим к относительному виду для БД
|
||||
rel_path = img_url
|
||||
if img_url.startswith("http"):
|
||||
# Вырезаем /uploads/...
|
||||
idx = img_url.find("/uploads/")
|
||||
if idx >= 0:
|
||||
rel_path = img_url[idx:]
|
||||
else:
|
||||
logger.warning(f"[removed_images] cannot parse URL: {img_url}")
|
||||
continue
|
||||
|
||||
# Удаляем из БД
|
||||
deleted = await conn.execute("""
|
||||
DELETE FROM feed_attachments
|
||||
WHERE post_id = $1 AND file_path = $2
|
||||
""", post_id, rel_path)
|
||||
deleted_count = int(deleted.split()[-1]) if deleted else 0
|
||||
|
||||
if deleted_count > 0:
|
||||
logger.info(f"[removed_images] deleted from DB: {rel_path}")
|
||||
else:
|
||||
logger.warning(f"[removed_images] not found in DB: {rel_path}")
|
||||
|
||||
logger.info(f"[removed_images] post #{post_id}: processed {len(removed_images)} items")
|
||||
|
||||
# Мерджим поля: если не передано — оставляем старое
|
||||
title = body.get("title", existing.get(f"title_{source_language}") or "")
|
||||
post_body = body.get("body", existing.get(f"body_{source_language}") or "")
|
||||
@@ -516,7 +549,32 @@ async def admin_update_feed_post(request: Request, post_id: int):
|
||||
post_id,
|
||||
)
|
||||
|
||||
return {"status": "ok", "post_id": post_id}
|
||||
# 🔧 ФИКС (24.09.2026): existing_image_removal_no_delete —
|
||||
# удаляем файлы с диска ВНЕ pool.acquire.
|
||||
if removed_images and isinstance(removed_images, list):
|
||||
for img_url in removed_images:
|
||||
rel_path = img_url
|
||||
if img_url.startswith("http"):
|
||||
idx = img_url.find("/uploads/")
|
||||
if idx >= 0:
|
||||
rel_path = img_url[idx:]
|
||||
else:
|
||||
continue
|
||||
|
||||
# "/uploads/feed/16_0_abc.jpg" → "feed/16_0_abc.jpg"
|
||||
rel_disk = rel_path.replace("/uploads/", "", 1).lstrip("/")
|
||||
abs_path = Path(UPLOADS_DIR) / rel_disk
|
||||
|
||||
try:
|
||||
if abs_path.exists():
|
||||
abs_path.unlink()
|
||||
logger.info(f"[removed_images] removed file: {abs_path}")
|
||||
else:
|
||||
logger.warning(f"[removed_images] file not found: {abs_path}")
|
||||
except Exception as e:
|
||||
logger.error(f"[removed_images] failed to remove {abs_path}: {e}")
|
||||
|
||||
return {"status": "ok", "post_id": post_id}
|
||||
|
||||
|
||||
# 🔧 ФИКС (18.09.2026): POST вместо DELETE.
|
||||
|
||||
Reference in New Issue
Block a user