fix(media): verify mirrored image signatures
This commit is contained in:
1 parent
355544de9c
commit
92171731ae
5 files changed
+33
-5
No files matched your search
@@ -37,6 +37,7 @@
|
|||||||
- 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`; the bounded in-memory registry expires entries after 30 minutes.
|
- 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: after the byte cap, VK attachment mirroring accepts only PNG/JPEG/WebP signatures and does not trust the external response Content-Type.
|
||||||
- 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.
|
||||||
- 2026-08-25: `project_mind_map.md` is the current source-controlled project map for Belki and deployment/security boundaries; update it when a data flow, service, or integration changes.
|
- 2026-08-25: `project_mind_map.md` is the current source-controlled project map for Belki and deployment/security boundaries; update it when a data flow, service, or integration changes.
|
||||||
|
|||||||
+16
-2
@@ -18,6 +18,17 @@ class ImageHostError(RuntimeError):
|
|||||||
MAX_MIRRORED_IMAGE_BYTES = 15 * 1024 * 1024
|
MAX_MIRRORED_IMAGE_BYTES = 15 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
def detect_raster_image_type(body: bytes) -> str | None:
|
||||||
|
"""Return the supported image MIME type from bytes, not an HTTP header."""
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
class ImageHostClient:
|
class ImageHostClient:
|
||||||
"""
|
"""
|
||||||
Клиент для mirror VK-фото на external image-host.
|
Клиент для mirror VK-фото на external image-host.
|
||||||
@@ -65,8 +76,11 @@ class ImageHostClient:
|
|||||||
body = response.read(MAX_MIRRORED_IMAGE_BYTES + 1)
|
body = response.read(MAX_MIRRORED_IMAGE_BYTES + 1)
|
||||||
if len(body) > MAX_MIRRORED_IMAGE_BYTES:
|
if len(body) > MAX_MIRRORED_IMAGE_BYTES:
|
||||||
raise ImageHostError("VK image is too large to mirror")
|
raise ImageHostError("VK image is too large to mirror")
|
||||||
content_type = response.headers.get_content_type() or "image/jpeg"
|
content_type = detect_raster_image_type(body)
|
||||||
file_name = f"vk-{photo.get('owner_id', 'photo')}-{photo.get('id', 'upload')}.jpg"
|
if content_type is None:
|
||||||
|
raise ImageHostError("VK attachment is not a supported raster image")
|
||||||
|
suffix = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}[content_type]
|
||||||
|
file_name = f"vk-{photo.get('owner_id', 'photo')}-{photo.get('id', 'upload')}.{suffix}"
|
||||||
return self.upload_bytes(body, file_name, content_type)
|
return self.upload_bytes(body, file_name, content_type)
|
||||||
|
|
||||||
def upload_bytes(self, body: bytes, file_name: str, content_type: str = "image/jpeg") -> str | None:
|
def upload_bytes(self, body: bytes, file_name: str, content_type: str = "image/jpeg") -> str | None:
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ mindmap
|
|||||||
Flexible punctuation and ID normalization
|
Flexible punctuation and ID normalization
|
||||||
Written Russian dates
|
Written Russian dates
|
||||||
Attachment mirroring
|
Attachment mirroring
|
||||||
|
bounded verified raster bytes
|
||||||
Applications dialog
|
Applications dialog
|
||||||
Data
|
Data
|
||||||
PostgreSQL production
|
PostgreSQL production
|
||||||
|
|||||||
@@ -65,6 +65,7 @@
|
|||||||
- 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 capped at 1000 URLs and expires after 30 minutes, matching 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: VK photo mirroring also verifies PNG/JPEG/WebP byte signatures and derives the upload MIME type and extension from those bytes, never from an upstream HTTP header.
|
||||||
- 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.
|
||||||
- 2026-08-25: application validation now bounds names, attachment and feather rows, and descriptive text for both web and VK submissions. Stored attachment and review links must be HTTPS; the optional profile link is restricted to a real VK host.
|
- 2026-08-25: application validation now bounds names, attachment and feather rows, and descriptive text for both web and VK submissions. Stored attachment and review links must be HTTPS; the optional profile link is restricted to a real VK host.
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import unittest
|
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, detect_raster_image_type as detect_mirrored_image_type
|
||||||
from app.main import (ADMIN_SESSION_TTL_SECONDS, MAX_ADMIN_AUTH_ATTEMPTS, MAX_ADMIN_SESSIONS, MAX_CONCURRENT_ADMIN_UPDATES, MAX_CONCURRENT_REQUESTS, MAX_ISSUED_WEB_UPLOAD_URLS, MAX_JSON_BODY_BYTES,
|
from app.main import (ADMIN_SESSION_TTL_SECONDS, MAX_ADMIN_AUTH_ATTEMPTS, MAX_ADMIN_SESSIONS, 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, _ADMIN_SESSIONS, _ISSUED_WEB_UPLOAD_URLS, admin_session_authorized, allow_admin_auth_attempt,
|
_ADMIN_AUTH_ATTEMPTS, _ADMIN_SESSIONS, _ISSUED_WEB_UPLOAD_URLS, admin_session_authorized, allow_admin_auth_attempt,
|
||||||
@@ -121,12 +121,23 @@ class ImageHostClientTests(unittest.TestCase):
|
|||||||
response = MagicMock()
|
response = MagicMock()
|
||||||
response.__enter__.return_value = response
|
response.__enter__.return_value = response
|
||||||
response.headers.get.return_value = None
|
response.headers.get.return_value = None
|
||||||
response.headers.get_content_type.return_value = "image/jpeg"
|
response.read.return_value = b"\x89PNG\r\n\x1a\nimage"
|
||||||
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"):
|
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})
|
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)
|
response.read.assert_called_once_with(MAX_MIRRORED_IMAGE_BYTES + 1)
|
||||||
|
|
||||||
|
def test_mirror_rejects_non_image_bytes_even_with_an_image_content_type(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"not an image"
|
||||||
|
with patch("app.belki.image_host.urlopen", return_value=response):
|
||||||
|
with self.assertRaisesRegex(ImageHostError, "not a supported"):
|
||||||
|
client.mirror({"url": "https://vk.example.test/photo.jpg"})
|
||||||
|
self.assertEqual(detect_mirrored_image_type(b"RIFF\x00\x00\x00\x00WEBPimage"), "image/webp")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
Reference in new issue
Block a user