fix(upload): validate public image payloads

This commit is contained in:
nyan404 committed 2026-08-25 03:38:49 +03:00
1 parent 5d6e5987d1
commit 240f1f9903
6 files changed
+68 -10

No files matched your search

+1
View File
@@ -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-команде.
+51 -5
View File
@@ -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":
+1
View File
@@ -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]`.
+10
View File
@@ -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"<svg xmlns='http://www.w3.org/2000/svg'>"))
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")
+2 -2
View File
@@ -28,8 +28,8 @@
<form id="form" class="panel"><div class="grid">
<label>Имя персонажа<input name="name" required></label><label>ID персонажа<input name="character_id" type="number" min="1" required></label>
<label id="vkField" class="wide">Ссылка на страницу VK <span class="hint">(необязательно)</span><input name="vk_link" type="text" inputmode="url" placeholder="vk.com/id… или vk.ru/id…"></label>
<section id="kittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Перетащите изображение сюда или выберите файл</strong><span>PNG, JPG, JPEG до 15 МБ</span><input class="screenshots" type="file" accept="image/*" multiple></span></label><ul class="files"></ul></section>
<section id="curatorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>Нужен хотя бы один файл</span><input class="screenshots" type="file" accept="image/*" multiple></span></label><ul class="files"></ul></section>
<section id="kittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Перетащите изображение сюда или выберите файл</strong><span>PNG, JPEG или WebP до 15 МБ</span><input class="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
<section id="curatorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>PNG, JPEG или WebP; нужен хотя бы один файл</span><input class="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
<section id="flyingFields" class="wide hidden"><label>Сдавали практику ранее?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="practiceLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/... или https://vk.com/... "></label></section>
<section id="featherFields" class="wide"><h2>Перья для казны</h2><p class="hint">Укажите цвет, количество и откуда получены перья.</p><div id="feathers"></div><button id="addFeather" class="secondary" type="button">Добавить перо</button></section>
</div><p id="error" class="error" role="alert"></p><div class="actions"><button class="primary" type="submit">Отправить заявку</button></div></form><div id="success" class="success hidden"></div>
+3 -3
View File
@@ -131,7 +131,7 @@
<label>Количество котят<input name="kitten_count" type="number" min="1" value="1"></label>
</div>
<label id="reportAttachments" class="wide">Скриншоты отчёта<input id="screenshots" type="file" accept="image/*" multiple><span class="muted">Можно выбрать несколько фотографий. Они будут загружены на img.nyan404.ru.</span></label>
<label id="reportAttachments" class="wide">Скриншоты отчёта<input id="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple><span class="muted">Можно выбрать несколько изображений PNG, JPEG или WebP. Они будут загружены на img.nyan404.ru.</span></label>
<div id="reportActions" class="actions"><button class="primary" type="submit">Подготовить сообщение</button><button type="button" id="copy" disabled>Скопировать</button></div>
<div id="goalActions" class="actions hidden"><button class="primary" type="submit">Рассчитать цель</button><button type="button" id="goalCopy" disabled>Скопировать</button></div>
</form>
@@ -177,8 +177,8 @@
<label>Имя персонажа<input name="name" required></label>
<label>ID персонажа<input name="character_id" type="number" min="1" inputmode="numeric" required></label>
<label id="applicationVkField" class="wide hidden">Ссылка на страницу VK <span class="muted">(необязательно)</span><input name="vk_link" type="text" inputmode="url" placeholder="vk.com/id… или vk.ru/id…"></label>
<section id="applicationKittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Выберите или перетащите изображение</strong><span>PNG, JPG или JPEG до 15 МБ</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg" multiple></span></label><ul class="files"></ul></section>
<section id="applicationCuratorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>Нужен хотя бы один файл</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg" multiple></span></label><ul class="files"></ul></section>
<section id="applicationKittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Выберите или перетащите изображение</strong><span>PNG, JPEG или WebP до 15 МБ</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
<section id="applicationCuratorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>PNG, JPEG или WebP; нужен хотя бы один файл</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
<section id="applicationFlyingFields" class="wide hidden"><label>Сдавали практику ранее?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="applicationPracticeLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/… или https://vk.com/…"></label></section>
<section id="applicationFeatherFields" class="wide"><h2>Перья для казны</h2><p class="muted">Укажите количество, цвет и источник добычи.</p><div id="applicationFeathers"></div><button id="applicationAddFeather" type="button">Добавить перо</button></section>
</div>