Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Bugfix to ensure image type is correctly extracted from content type (#4062)

thegreendrinker35197e98e735
diff --git a/api/api/utils/image_proxy/extension.py b/api/api/utils/image_proxy/extension.py
index a7da85e9c..2773b9d6a 100644
--- a/api/api/utils/image_proxy/extension.py
+++ b/api/api/utils/image_proxy/extension.py
@@ -1,4 +1,5 @@
import logging
+import mimetypes
from os.path import splitext
from urllib.parse import urlparse
@@ -78,6 +79,10 @@ def _get_file_extension_from_content_type(content_type: str) -> str | None:
Return the image extension if present in the Response's content type
header.
"""
- if content_type and "/" in content_type:
- return content_type.split("/")[1]
+ if (
+ content_type
+ and "/" in content_type
+ and (ext := mimetypes.guess_extension(content_type.split(";")[0], strict=False))
+ ):
+ return ext.strip(".")
return None
diff --git a/api/test/unit/utils/test_image_proxy.py b/api/test/unit/utils/test_image_proxy.py
index 8b5401e53..5dce10b01 100644
--- a/api/test/unit/utils/test_image_proxy.py
+++ b/api/test/unit/utils/test_image_proxy.py
@@ -512,6 +512,28 @@ def test__get_extension_from_url(image_url, expected_ext):
assert extension._get_file_extension_from_url(image_url) == expected_ext
+ "content_type, expected_ext",
+ [
+ ("image/png;charset=UTF-8", "png"),
+ ("image/jpeg", "jpg"),
+ ("image/png", "png"),
+ ("image/gif", "gif"),
+ ("image/svg+xml", "svg"),
+ ("audio/midi", "midi"),
+ ("audio/mpeg", "mp3"),
+ ("audio/ogg", None),
+ ("audio/opus", "opus"),
+ ("audio/wav", None),
+ ("video/webm", "webm"),
+ (None, None),
+ ("foobar", None),
+ ],
+)
+def test_get_extension_from_content_type(content_type, expected_ext):
+ assert extension._get_file_extension_from_content_type(content_type) == expected_ext
+
+
@pytest.mark.django_db
@pytest.mark.parametrize("image_type", ["apng", "tiff", "bmp"])
def test_photon_get_raises_by_not_allowed_types(photon_get, image_type):