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

+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":