fix(media): bound attachment and request resources

This commit is contained in:
nyan404 committed 2026-08-25 03:41:21 +03:00
1 parent 2065fe2acd
commit a105be4822
5 files changed
+110 -4

No files matched your search

+47 -1
View File
@@ -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__":