From 240f1f9903198f4b6f47f54a8dacedfd05920618 Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Tue, 25 Aug 2026 03:38:49 +0300 Subject: [PATCH] fix(upload): validate public image payloads --- MEMORY.md | 1 + app/main.py | 56 ++++++++++++++++++++++++++++++++++++---- structure_and_data.md | 1 + tests/test_image_host.py | 10 +++++++ web/applications.html | 4 +-- web/calculator.html | 6 ++--- 6 files changed, 68 insertions(+), 10 deletions(-) diff --git a/MEMORY.md b/MEMORY.md index e8155c0..7e3aea9 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -33,6 +33,7 @@ - 2026-08-25: Belki fixes: natural bulk parsing now extracts `Имя ID` and `Имя [ID]` before a `HH:MM-HH:MM` range; web quick input is coaching-only; inspection resources use `+N название`; reports decline `раз/раза`; VK image mirroring defaults to `https://nyan.nyan404.ru`; `/belki` has a standalone goal calculator backed by `mode=goal`. - 2026-08-25: VK now exposes the goal calculator in the main keyboard and through `/цель`/`/калькулятор`; its interactive state collects points, session duration, skill, independence, and kitten count, then confirms the calculated result without screenshots. - 2026-08-25: public goal calculations reject non-finite scores and bound session length to 1–1440 minutes and kitten count to 1–50, consistently across domain, API, and VK input. +- 2026-08-25: screenshot uploads are public by product design but are bounded before JSON parsing (20 MiB) and after base64 decoding (15 MiB); only verified PNG/JPEG/WebP bytes and basename-only filenames reach image hosting. # 2026-08-16 — несколько котят в прокачке `CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде. diff --git a/app/main.py b/app/main.py index 7fc80d8..e0abacd 100644 --- a/app/main.py +++ b/app/main.py @@ -25,6 +25,28 @@ _HISTORY_STORE: CalculationStore | None = None _IDENTITY_DIR: IdentityDirectory | None = None _APPLICATION_STORE: ApplicationStore | None = None _ADMIN_SESSIONS: set[str] = set() +MAX_JSON_BODY_BYTES = 20 * 1024 * 1024 +MAX_UPLOAD_BYTES = 15 * 1024 * 1024 + + +def detect_raster_image_type(body: bytes) -> str | None: + """Returns the MIME type for supported raster image signatures only.""" + if body.startswith(b"\x89PNG\r\n\x1a\n"): + return "image/png" + if body.startswith(b"\xff\xd8\xff"): + return "image/jpeg" + if len(body) >= 12 and body.startswith(b"RIFF") and body[8:12] == b"WEBP": + return "image/webp" + return None + + +def safe_upload_name(value: object, content_type: str) -> str: + """Drops path-like input and supplies a stable name for the image host.""" + name = str(value or "").replace("\\", "/").split("/")[-1].replace("\x00", "").strip() + if not name: + suffix = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}[content_type] + return f"screenshot.{suffix}" + return name[:255] def history_store() -> CalculationStore: @@ -200,14 +222,32 @@ class Handler(BaseHTTPRequestHandler): self.end_headers() self.wfile.write(content) + def _read_json_body(self) -> dict: + """Read a bounded JSON request before passing it to public handlers.""" + content_type = self.headers.get("Content-Type", "") + if not content_type.lower().startswith("application/json"): + raise ApiError("Ожидалось содержимое в формате JSON") + try: + length = int(self.headers.get("Content-Length", "")) + except ValueError as exc: + raise ApiError("Некорректный размер запроса") from exc + if not 0 <= length <= MAX_JSON_BODY_BYTES: + raise ApiError(f"Слишком большой запрос (максимум {MAX_JSON_BODY_BYTES // 1024 // 1024} МБ)") + try: + payload = json.loads(self.rfile.read(length)) if length else {} + except json.JSONDecodeError as exc: + raise ApiError("Не удалось прочитать JSON") from exc + if not isinstance(payload, dict): + raise ApiError("Ожидался JSON-объект") + return payload + def do_POST(self) -> None: # noqa: N802 if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity", "/api/save-profile", "/api/get-profile", "/api/applications"): self._json(404, {"error": "Не найдено"}) return try: - length = int(self.headers.get("Content-Length", "0")) - payload = json.loads(self.rfile.read(length)) if length else {} + payload = self._read_json_body() if self.path == "/api/admin/auth": expected = os.getenv("BELKI_ADMIN_PASSWORD", "") if not expected or not secrets.compare_digest(str(payload.get("password", "")), expected): @@ -227,17 +267,23 @@ class Handler(BaseHTTPRequestHandler): body = base64.b64decode(raw, validate=True) except (ValueError, TypeError) as exc: raise ApiError("Не удалось прочитать изображение") from exc - if len(body) > 15 * 1024 * 1024: + if len(body) > MAX_UPLOAD_BYTES: raise ApiError("Файл слишком большой (максимум 15 МБ)") + content_type = detect_raster_image_type(body) + if content_type is None: + raise ApiError("Поддерживаются только изображения PNG, JPEG и WebP") + declared_type = str(payload.get("type", "")).split(";", 1)[0].strip().lower() + if declared_type and declared_type != content_type: + raise ApiError("Тип файла не совпадает с содержимым изображения") try: url = ImageHostClient(api_url=os.getenv("BELKI_IMAGE_HOST_API_URL", "https://nyan.nyan404.ru")).upload_bytes( - body, str(payload.get("name", "screenshot.jpg")), str(payload.get("type", "image/jpeg")) + body, safe_upload_name(payload.get("name"), content_type), content_type ) except ImageHostError as exc: raise ApiError(f"Не удалось загрузить изображение: {exc}") from exc if not url: raise ApiError("Хранилище изображений не настроено") - self._json(200, {"url": url, "name": payload.get("name", "screenshot.jpg")}) + self._json(200, {"url": url, "name": safe_upload_name(payload.get("name"), content_type)}) elif self.path == "/api/inspect-bulk": self._json(200, inspect_bulk_payload(payload)) elif self.path == "/api/resolve-identity": diff --git a/structure_and_data.md b/structure_and_data.md index 5228349..df7a66e 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -60,6 +60,7 @@ - 2026-08-25: fixed separator-free bulk parsing around time ranges, scoped web quick input to coaching, changed web inspection resources to `+N name`, corrected Russian inspection-count grammar, enabled VK image mirroring fallback, and added the standalone goal calculator mode/API. - 2026-08-25: added the goal calculator to the VK menu as `/цель` and `/калькулятор`; the bot now runs the same goal calculation interactively with step prompts, choice buttons, and confirmation without report attachments. - 2026-08-25: hardened the public goal calculator: point values must be finite, one session is limited to 1–1440 minutes, and one calculation to 1–50 kittens. The same validation is applied by the domain, JSON API, and VK dialogue, with regression tests for `NaN`, infinity, and excessive values. +- 2026-08-25: hardened public JSON and screenshot uploads. The web handler caps encoded JSON at 20 MiB before parsing, decodes at most 15 MiB of image bytes, accepts only PNG/JPEG/WebP signatures, rejects MIME mismatches, and strips path components from upload names. The public UI advertises the same supported formats. # Обновление 2026-08-16: несколько котят Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`. diff --git a/tests/test_image_host.py b/tests/test_image_host.py index 67c9ea8..2ea6764 100644 --- a/tests/test_image_host.py +++ b/tests/test_image_host.py @@ -2,9 +2,19 @@ import unittest from unittest.mock import MagicMock, patch from app.belki.image_host import ImageHostClient, ImageHostError +from app.main import MAX_JSON_BODY_BYTES, detect_raster_image_type, safe_upload_name class ImageHostClientTests(unittest.TestCase): + def test_upload_input_helpers_accept_only_supported_raster_signatures(self) -> None: + self.assertEqual(detect_raster_image_type(b"\x89PNG\r\n\x1a\ncontent"), "image/png") + self.assertEqual(detect_raster_image_type(b"\xff\xd8\xffcontent"), "image/jpeg") + self.assertEqual(detect_raster_image_type(b"RIFF\x00\x00\x00\x00WEBPcontent"), "image/webp") + self.assertIsNone(detect_raster_image_type(b"")) + self.assertEqual(safe_upload_name("../../report.png", "image/png"), "report.png") + self.assertEqual(safe_upload_name("", "image/webp"), "screenshot.webp") + self.assertEqual(MAX_JSON_BODY_BYTES, 20 * 1024 * 1024) + def test_default_client_targets_belki_image_host(self) -> None: with patch.dict("os.environ", {}, clear=True): self.assertEqual(ImageHostClient().api_url, "https://nyan.nyan404.ru") diff --git a/web/applications.html b/web/applications.html index 70ac5be..edefaa4 100644 --- a/web/applications.html +++ b/web/applications.html @@ -28,8 +28,8 @@
- - + +

Перья для казны

Укажите цвет, количество и откуда получены перья.

diff --git a/web/calculator.html b/web/calculator.html index ba1e35a..a766705 100644 --- a/web/calculator.html +++ b/web/calculator.html @@ -131,7 +131,7 @@ - +
@@ -177,8 +177,8 @@ - - + +

Перья для казны

Укажите количество, цвет и источник добычи.