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
+16
-2
@@ -18,6 +18,17 @@ class ImageHostError(RuntimeError):
|
||||
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:
|
||||
"""
|
||||
Клиент для mirror VK-фото на external image-host.
|
||||
@@ -65,8 +76,11 @@ class ImageHostClient:
|
||||
body = response.read(MAX_MIRRORED_IMAGE_BYTES + 1)
|
||||
if len(body) > MAX_MIRRORED_IMAGE_BYTES:
|
||||
raise ImageHostError("VK image is too large to mirror")
|
||||
content_type = response.headers.get_content_type() or "image/jpeg"
|
||||
file_name = f"vk-{photo.get('owner_id', 'photo')}-{photo.get('id', 'upload')}.jpg"
|
||||
content_type = detect_raster_image_type(body)
|
||||
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)
|
||||
|
||||
def upload_bytes(self, body: bytes, file_name: str, content_type: str = "image/jpeg") -> str | None:
|
||||
|
||||
Reference in new issue
Block a user