fix(upload): expire issued attachment URLs
This commit is contained in:
1 parent
947cebc256
commit
38c74395ed
4 files changed
+48
-11
No files matched your search
@@ -35,7 +35,7 @@
|
|||||||
- 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: 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: 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 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: 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`; the bounded in-memory registry expires entries after 30 minutes.
|
||||||
- 2026-08-25: VK attachment mirroring has a strict 15 MiB transfer cap, including a Content-Length precheck and bounded read.
|
- 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-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-25: natural bulk parsing prioritizes explicit Russian mentor/student labels, then falls back to the original pair order when labels are absent.
|
- 2026-08-25: natural bulk parsing prioritizes explicit Russian mentor/student labels, then falls back to the original pair order when labels are absent.
|
||||||
|
|||||||
+25
-4
@@ -26,7 +26,8 @@ _HISTORY_STORE: CalculationStore | None = None
|
|||||||
_IDENTITY_DIR: IdentityDirectory | None = None
|
_IDENTITY_DIR: IdentityDirectory | None = None
|
||||||
_APPLICATION_STORE: ApplicationStore | None = None
|
_APPLICATION_STORE: ApplicationStore | None = None
|
||||||
_ADMIN_SESSIONS: set[str] = set()
|
_ADMIN_SESSIONS: set[str] = set()
|
||||||
_ISSUED_WEB_UPLOAD_URLS: set[str] = set()
|
_ISSUED_WEB_UPLOAD_URLS: dict[str, float] = {}
|
||||||
|
_ISSUED_WEB_UPLOADS_LOCK = threading.Lock()
|
||||||
_ADMIN_AUTH_ATTEMPTS: dict[str, list[float]] = {}
|
_ADMIN_AUTH_ATTEMPTS: dict[str, list[float]] = {}
|
||||||
_ADMIN_AUTH_LOCK = threading.Lock()
|
_ADMIN_AUTH_LOCK = threading.Lock()
|
||||||
MAX_JSON_BODY_BYTES = 20 * 1024 * 1024
|
MAX_JSON_BODY_BYTES = 20 * 1024 * 1024
|
||||||
@@ -37,6 +38,8 @@ MAX_CONCURRENT_ADMIN_UPDATES = 8
|
|||||||
ADMIN_AUTH_WINDOW_SECONDS = 15 * 60
|
ADMIN_AUTH_WINDOW_SECONDS = 15 * 60
|
||||||
MAX_ADMIN_AUTH_ATTEMPTS = 5
|
MAX_ADMIN_AUTH_ATTEMPTS = 5
|
||||||
_ADMIN_UPDATE_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_ADMIN_UPDATES)
|
_ADMIN_UPDATE_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_ADMIN_UPDATES)
|
||||||
|
WEB_UPLOAD_URL_TTL_SECONDS = 30 * 60
|
||||||
|
MAX_ISSUED_WEB_UPLOAD_URLS = 1_000
|
||||||
|
|
||||||
|
|
||||||
def detect_raster_image_type(body: bytes) -> str | None:
|
def detect_raster_image_type(body: bytes) -> str | None:
|
||||||
@@ -59,11 +62,29 @@ def safe_upload_name(value: object, content_type: str) -> str:
|
|||||||
return name[:255]
|
return name[:255]
|
||||||
|
|
||||||
|
|
||||||
def validate_web_attachments(value: object) -> list[dict]:
|
def remember_issued_web_upload(url: str, *, now: float | None = None) -> None:
|
||||||
"""Accept only attachments that this process received from image hosting."""
|
"""Register one upload URL for the short upload-and-submit web flow."""
|
||||||
|
timestamp = time.monotonic() if now is None else now
|
||||||
|
with _ISSUED_WEB_UPLOADS_LOCK:
|
||||||
|
expired = [item for item, expiry in _ISSUED_WEB_UPLOAD_URLS.items() if expiry <= timestamp]
|
||||||
|
for item in expired:
|
||||||
|
del _ISSUED_WEB_UPLOAD_URLS[item]
|
||||||
|
if url not in _ISSUED_WEB_UPLOAD_URLS and len(_ISSUED_WEB_UPLOAD_URLS) >= MAX_ISSUED_WEB_UPLOAD_URLS:
|
||||||
|
oldest = min(_ISSUED_WEB_UPLOAD_URLS, key=_ISSUED_WEB_UPLOAD_URLS.__getitem__)
|
||||||
|
del _ISSUED_WEB_UPLOAD_URLS[oldest]
|
||||||
|
_ISSUED_WEB_UPLOAD_URLS[url] = timestamp + WEB_UPLOAD_URL_TTL_SECONDS
|
||||||
|
|
||||||
|
|
||||||
|
def validate_web_attachments(value: object, *, now: float | None = None) -> list[dict]:
|
||||||
|
"""Accept only unexpired attachments issued by this process to the web form."""
|
||||||
if not isinstance(value, list) or len(value) > 10:
|
if not isinstance(value, list) or len(value) > 10:
|
||||||
raise ApiError("Можно приложить от 0 до 10 изображений")
|
raise ApiError("Можно приложить от 0 до 10 изображений")
|
||||||
|
timestamp = time.monotonic() if now is None else now
|
||||||
attachments: list[dict] = []
|
attachments: list[dict] = []
|
||||||
|
with _ISSUED_WEB_UPLOADS_LOCK:
|
||||||
|
expired = [item for item, expiry in _ISSUED_WEB_UPLOAD_URLS.items() if expiry <= timestamp]
|
||||||
|
for item in expired:
|
||||||
|
del _ISSUED_WEB_UPLOAD_URLS[item]
|
||||||
for item in value:
|
for item in value:
|
||||||
if not isinstance(item, dict) or not isinstance(item.get("url"), str):
|
if not isinstance(item, dict) or not isinstance(item.get("url"), str):
|
||||||
raise ApiError("Некорректное вложение")
|
raise ApiError("Некорректное вложение")
|
||||||
@@ -343,7 +364,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
raise ApiError(f"Не удалось загрузить изображение: {exc}") from exc
|
raise ApiError(f"Не удалось загрузить изображение: {exc}") from exc
|
||||||
if not url:
|
if not url:
|
||||||
raise ApiError("Хранилище изображений не настроено")
|
raise ApiError("Хранилище изображений не настроено")
|
||||||
_ISSUED_WEB_UPLOAD_URLS.add(url)
|
remember_issued_web_upload(url)
|
||||||
self._json(200, {"url": url, "name": safe_upload_name(payload.get("name"), content_type)})
|
self._json(200, {"url": url, "name": safe_upload_name(payload.get("name"), content_type)})
|
||||||
elif self.path == "/api/inspect-bulk":
|
elif self.path == "/api/inspect-bulk":
|
||||||
self._json(200, inspect_bulk_payload(payload))
|
self._json(200, inspect_bulk_payload(payload))
|
||||||
|
|||||||
@@ -63,7 +63,7 @@
|
|||||||
- 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 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: 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: 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: 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 capped at 1000 URLs and expires after 30 minutes, matching 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: 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-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-25: long-lived authenticated admin refresh WebSockets now have a separate eight-connection pool, so they cannot consume all 32 request workers; additional connections receive an explicit temporary-unavailable response.
|
- 2026-08-25: long-lived authenticated admin refresh WebSockets now have a separate eight-connection pool, so they cannot consume all 32 request workers; additional connections receive an explicit temporary-unavailable response.
|
||||||
|
|||||||
@@ -2,11 +2,12 @@ import unittest
|
|||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from app.belki.image_host import MAX_MIRRORED_IMAGE_BYTES, ImageHostClient, ImageHostError
|
from app.belki.image_host import MAX_MIRRORED_IMAGE_BYTES, ImageHostClient, ImageHostError
|
||||||
from app.main import (MAX_ADMIN_AUTH_ATTEMPTS, MAX_CONCURRENT_ADMIN_UPDATES, MAX_CONCURRENT_REQUESTS, MAX_JSON_BODY_BYTES,
|
from app.main import (MAX_ADMIN_AUTH_ATTEMPTS, MAX_CONCURRENT_ADMIN_UPDATES, MAX_CONCURRENT_REQUESTS, MAX_ISSUED_WEB_UPLOAD_URLS, MAX_JSON_BODY_BYTES,
|
||||||
REQUEST_READ_TIMEOUT_SECONDS, ADMIN_AUTH_WINDOW_SECONDS, BelkiHTTPServer, Handler,
|
REQUEST_READ_TIMEOUT_SECONDS, ADMIN_AUTH_WINDOW_SECONDS, BelkiHTTPServer, Handler,
|
||||||
_ADMIN_AUTH_ATTEMPTS, _ISSUED_WEB_UPLOAD_URLS, allow_admin_auth_attempt,
|
_ADMIN_AUTH_ATTEMPTS, _ISSUED_WEB_UPLOAD_URLS, allow_admin_auth_attempt,
|
||||||
acquire_admin_update_slot, clear_admin_auth_attempts, detect_raster_image_type,
|
acquire_admin_update_slot, clear_admin_auth_attempts, detect_raster_image_type,
|
||||||
release_admin_update_slot, safe_upload_name, validate_web_attachments)
|
remember_issued_web_upload, release_admin_update_slot, safe_upload_name,
|
||||||
|
validate_web_attachments, WEB_UPLOAD_URL_TTL_SECONDS)
|
||||||
from app.belki.api import ApiError
|
from app.belki.api import ApiError
|
||||||
|
|
||||||
|
|
||||||
@@ -22,13 +23,28 @@ class ImageHostClientTests(unittest.TestCase):
|
|||||||
|
|
||||||
def test_web_attachments_must_come_from_image_host_upload(self) -> None:
|
def test_web_attachments_must_come_from_image_host_upload(self) -> None:
|
||||||
_ISSUED_WEB_UPLOAD_URLS.clear()
|
_ISSUED_WEB_UPLOAD_URLS.clear()
|
||||||
_ISSUED_WEB_UPLOAD_URLS.add("https://img.nyan404.ru/photo/known.jpg")
|
remember_issued_web_upload("https://img.nyan404.ru/photo/known.jpg", now=100)
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
validate_web_attachments([{"type": "photo", "url": "https://img.nyan404.ru/photo/known.jpg"}]),
|
validate_web_attachments([{"type": "photo", "url": "https://img.nyan404.ru/photo/known.jpg"}], now=100),
|
||||||
[{"type": "photo", "url": "https://img.nyan404.ru/photo/known.jpg"}],
|
[{"type": "photo", "url": "https://img.nyan404.ru/photo/known.jpg"}],
|
||||||
)
|
)
|
||||||
with self.assertRaisesRegex(ApiError, "через форму Белок"):
|
with self.assertRaisesRegex(ApiError, "через форму Белок"):
|
||||||
validate_web_attachments([{"type": "photo", "url": "http://127.0.0.1:8080/private"}])
|
validate_web_attachments([{"type": "photo", "url": "http://127.0.0.1:8080/private"}], now=100)
|
||||||
|
|
||||||
|
def test_web_upload_url_authorization_expires(self) -> None:
|
||||||
|
_ISSUED_WEB_UPLOAD_URLS.clear()
|
||||||
|
url = "https://img.nyan404.ru/photo/temporary.jpg"
|
||||||
|
remember_issued_web_upload(url, now=100)
|
||||||
|
with self.assertRaisesRegex(ApiError, "через форму Белок"):
|
||||||
|
validate_web_attachments([{"type": "photo", "url": url}], now=100 + WEB_UPLOAD_URL_TTL_SECONDS)
|
||||||
|
self.assertNotIn(url, _ISSUED_WEB_UPLOAD_URLS)
|
||||||
|
|
||||||
|
def test_web_upload_url_authorization_has_a_fixed_capacity(self) -> None:
|
||||||
|
_ISSUED_WEB_UPLOAD_URLS.clear()
|
||||||
|
for index in range(MAX_ISSUED_WEB_UPLOAD_URLS + 1):
|
||||||
|
remember_issued_web_upload(f"https://img.nyan404.ru/photo/{index}.jpg", now=index)
|
||||||
|
self.assertEqual(len(_ISSUED_WEB_UPLOAD_URLS), MAX_ISSUED_WEB_UPLOAD_URLS)
|
||||||
|
self.assertNotIn("https://img.nyan404.ru/photo/0.jpg", _ISSUED_WEB_UPLOAD_URLS)
|
||||||
|
|
||||||
def test_http_server_limits_read_time_and_concurrent_requests(self) -> None:
|
def test_http_server_limits_read_time_and_concurrent_requests(self) -> None:
|
||||||
server = BelkiHTTPServer(("127.0.0.1", 0), Handler)
|
server = BelkiHTTPServer(("127.0.0.1", 0), Handler)
|
||||||
|
|||||||
Reference in new issue
Block a user