From a105be48225d7148d94ef35763ccd09116fa20de Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Tue, 25 Aug 2026 03:41:21 +0300 Subject: [PATCH] fix(media): bound attachment and request resources --- MEMORY.md | 3 +++ app/belki/image_host.py | 14 +++++++++++- app/main.py | 48 +++++++++++++++++++++++++++++++++++++++- structure_and_data.md | 3 +++ tests/test_image_host.py | 46 ++++++++++++++++++++++++++++++++++++-- 5 files changed, 110 insertions(+), 4 deletions(-) diff --git a/MEMORY.md b/MEMORY.md index b315331..f4ce2bb 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -35,6 +35,9 @@ - 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-25: public web identity completion is deliberately ephemeral; it no longer writes the identity directory used by VK, and unused global web-profile endpoints were removed. +- 2026-08-25: public JSON cannot choose arbitrary attachment URLs. Web attachments are accepted only after the running process issued their image-host URL through `/api/web/upload`. +- 2026-08-25: VK attachment mirroring has a strict 15 MiB transfer cap, including a Content-Length precheck and bounded read. +- 2026-08-25: the web service uses `BelkiHTTPServer` with 15-second socket reads and a 32-request semaphore in addition to the bounded JSON body reader. # 2026-08-16 — несколько котят в прокачке `CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде. diff --git a/app/belki/image_host.py b/app/belki/image_host.py index 035105c..f4712a1 100644 --- a/app/belki/image_host.py +++ b/app/belki/image_host.py @@ -15,6 +15,9 @@ class ImageHostError(RuntimeError): """Ошибка при работе с image-host.""" +MAX_MIRRORED_IMAGE_BYTES = 15 * 1024 * 1024 + + class ImageHostClient: """ Клиент для mirror VK-фото на external image-host. @@ -52,7 +55,16 @@ class ImageHostClient: return None source_url = str(photo["url"]) with urlopen(source_url, timeout=self.timeout) as response: - body = response.read() + raw_length = response.headers.get("Content-Length") + try: + content_length = int(raw_length) if raw_length else None + except ValueError: + content_length = None + if content_length is not None and content_length > MAX_MIRRORED_IMAGE_BYTES: + raise ImageHostError("VK image is too large to mirror") + body = response.read(MAX_MIRRORED_IMAGE_BYTES + 1) + if len(body) > MAX_MIRRORED_IMAGE_BYTES: + raise ImageHostError("VK image is too large to mirror") content_type = response.headers.get_content_type() or "image/jpeg" file_name = f"vk-{photo.get('owner_id', 'photo')}-{photo.get('id', 'upload')}.jpg" return self.upload_bytes(body, file_name, content_type) diff --git a/app/main.py b/app/main.py index c609f84..5ef35f8 100644 --- a/app/main.py +++ b/app/main.py @@ -6,6 +6,7 @@ import hashlib import mimetypes import os import secrets +import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path @@ -25,8 +26,11 @@ _HISTORY_STORE: CalculationStore | None = None _IDENTITY_DIR: IdentityDirectory | None = None _APPLICATION_STORE: ApplicationStore | None = None _ADMIN_SESSIONS: set[str] = set() +_ISSUED_WEB_UPLOAD_URLS: set[str] = set() MAX_JSON_BODY_BYTES = 20 * 1024 * 1024 MAX_UPLOAD_BYTES = 15 * 1024 * 1024 +REQUEST_READ_TIMEOUT_SECONDS = 15 +MAX_CONCURRENT_REQUESTS = 32 def detect_raster_image_type(body: bytes) -> str | None: @@ -49,6 +53,20 @@ def safe_upload_name(value: object, content_type: str) -> str: return name[:255] +def validate_web_attachments(value: object) -> list[dict]: + """Accept only attachments that this process received from image hosting.""" + if not isinstance(value, list) or len(value) > 10: + raise ApiError("Можно приложить от 0 до 10 изображений") + attachments: list[dict] = [] + for item in value: + if not isinstance(item, dict) or not isinstance(item.get("url"), str): + raise ApiError("Некорректное вложение") + if item["url"] not in _ISSUED_WEB_UPLOAD_URLS: + raise ApiError("Вложение должно быть загружено через форму Белок") + attachments.append(item) + return attachments + + def history_store() -> CalculationStore: global _HISTORY_STORE if _HISTORY_STORE is None: @@ -75,6 +93,31 @@ def sync_application_exports() -> int: return GoogleSheetsExportService(application_store()).sync_pending() +class BelkiHTTPServer(ThreadingHTTPServer): + """Threaded server with bounded slow-client and worker resource use.""" + + def __init__(self, server_address: tuple[str, int], handler_class: type[BaseHTTPRequestHandler]) -> None: + super().__init__(server_address, handler_class) + self._request_slots = threading.BoundedSemaphore(MAX_CONCURRENT_REQUESTS) + + def get_request(self): # type: ignore[no-untyped-def] + request, client_address = super().get_request() + request.settimeout(REQUEST_READ_TIMEOUT_SECONDS) + return request, client_address + + def process_request(self, request, client_address) -> None: # type: ignore[no-untyped-def] + if not self._request_slots.acquire(blocking=False): + request.close() + return + super().process_request(request, client_address) + + def process_request_thread(self, request, client_address) -> None: # type: ignore[no-untyped-def] + try: + super().process_request_thread(request, client_address) + finally: + self._request_slots.release() + + class Handler(BaseHTTPRequestHandler): server_version = "BelkiCalculator/0.1" protocol_version = "HTTP/1.1" @@ -257,17 +300,20 @@ class Handler(BaseHTTPRequestHandler): raise ApiError(f"Не удалось загрузить изображение: {exc}") from exc if not url: raise ApiError("Хранилище изображений не настроено") + _ISSUED_WEB_UPLOAD_URLS.add(url) 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": self._json(200, resolve_identity_payload(payload)) elif self.path == "/api/applications": + payload["attachments"] = validate_web_attachments(payload.get("attachments", [])) application = validate_application(payload) application_id = application_store().create(application=application, actor_id=None, reply_peer_id=None, source="web") sync_application_exports() self._json(201, {"id": application_id, "status": "pending", "message": "Заявка отправлена на рассмотрение."}) else: + payload["attachments"] = validate_web_attachments(payload.get("attachments", [])) self._json(200, calculate_and_store(payload, actor_id=None, source="web")) except (ApiError, ApplicationError) as exc: self._json(400, {"error": str(exc)}) @@ -324,7 +370,7 @@ class Handler(BaseHTTPRequestHandler): def serve() -> None: host = os.getenv("BELKI_HOST", "0.0.0.0") port = int(os.getenv("BELKI_PORT", "8080")) - ThreadingHTTPServer((host, port), Handler).serve_forever() + BelkiHTTPServer((host, port), Handler).serve_forever() if __name__ == "__main__": diff --git a/structure_and_data.md b/structure_and_data.md index 9208651..ddbfcfe 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -62,6 +62,9 @@ - 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-25: removed unused public web-profile endpoints and made `/api/resolve-identity` stateless for submitted pairs. A browser can fill its current inspection form, but cannot overwrite the persistent identity directory shared with VK users. +- 2026-08-25: web calculations and applications now accept attachment URLs only when the same web process received them from the image-host upload endpoint. This prevents public JSON from planting arbitrary browser-fetchable URLs in the admin interface; the in-memory authorization is intentionally limited to the active upload-and-submit flow. +- 2026-08-25: VK image mirroring checks the advertised byte length and reads at most 15 MiB plus a one-byte sentinel before uploading. Oversized upstream photos no longer allocate unbounded memory in the bot process. +- 2026-08-25: `BelkiHTTPServer` supersedes the unbounded standard threaded server. It rejects oversized declared JSON before reading, times out a slow client after 15 seconds, and serves at most 32 concurrent connections. # Обновление 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 2ea6764..a6a756d 100644 --- a/tests/test_image_host.py +++ b/tests/test_image_host.py @@ -1,8 +1,11 @@ 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 +from app.belki.image_host import MAX_MIRRORED_IMAGE_BYTES, ImageHostClient, ImageHostError +from app.main import (MAX_CONCURRENT_REQUESTS, MAX_JSON_BODY_BYTES, REQUEST_READ_TIMEOUT_SECONDS, + BelkiHTTPServer, Handler, _ISSUED_WEB_UPLOAD_URLS, detect_raster_image_type, + safe_upload_name, validate_web_attachments) +from app.belki.api import ApiError class ImageHostClientTests(unittest.TestCase): @@ -15,6 +18,24 @@ class ImageHostClientTests(unittest.TestCase): self.assertEqual(safe_upload_name("", "image/webp"), "screenshot.webp") self.assertEqual(MAX_JSON_BODY_BYTES, 20 * 1024 * 1024) + def test_web_attachments_must_come_from_image_host_upload(self) -> None: + _ISSUED_WEB_UPLOAD_URLS.clear() + _ISSUED_WEB_UPLOAD_URLS.add("https://img.nyan404.ru/photo/known.jpg") + self.assertEqual( + validate_web_attachments([{"type": "photo", "url": "https://img.nyan404.ru/photo/known.jpg"}]), + [{"type": "photo", "url": "https://img.nyan404.ru/photo/known.jpg"}], + ) + with self.assertRaisesRegex(ApiError, "через форму Белок"): + validate_web_attachments([{"type": "photo", "url": "http://127.0.0.1:8080/private"}]) + + def test_http_server_limits_read_time_and_concurrent_requests(self) -> None: + server = BelkiHTTPServer(("127.0.0.1", 0), Handler) + try: + self.assertEqual(REQUEST_READ_TIMEOUT_SECONDS, 15) + self.assertEqual(MAX_CONCURRENT_REQUESTS, 32) + finally: + server.server_close() + 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") @@ -36,6 +57,27 @@ class ImageHostClientTests(unittest.TestCase): with self.assertRaisesRegex(ImageHostError, "image host upload failed"): client.upload_bytes(b"image", "screenshot.jpg") + def test_mirror_stops_before_reading_an_oversized_vk_image(self) -> None: + client = ImageHostClient(api_url="https://api.example.test") + response = MagicMock() + response.__enter__.return_value = response + response.headers.get.side_effect = lambda name: str(MAX_MIRRORED_IMAGE_BYTES + 1) if name == "Content-Length" else None + with patch("app.belki.image_host.urlopen", return_value=response): + with self.assertRaisesRegex(ImageHostError, "too large"): + client.mirror({"url": "https://vk.example.test/photo.jpg"}) + response.read.assert_not_called() + + def test_mirror_reads_at_most_the_configured_limit_plus_sentinel(self) -> None: + client = ImageHostClient(api_url="https://api.example.test") + response = MagicMock() + response.__enter__.return_value = response + response.headers.get.return_value = None + response.headers.get_content_type.return_value = "image/jpeg" + response.read.return_value = b"image" + with patch("app.belki.image_host.urlopen", return_value=response), patch.object(client, "upload_bytes", return_value="https://img.example.test/a.jpg"): + client.mirror({"url": "https://vk.example.test/photo.jpg", "owner_id": 1, "id": 2}) + response.read.assert_called_once_with(MAX_MIRRORED_IMAGE_BYTES + 1) + if __name__ == "__main__": unittest.main()