Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Check the file type of the thumbnail before passing it to Photon (#2086)
Krystle Salazar8bc6ab7988d3
diff --git a/api/api/utils/photon.py b/api/api/utils/photon.pyindex 14e130d68..82923264c 100644--- a/api/api/utils/photon.py+++ b/api/api/utils/photon.py@@ -1,10 +1,11 @@import logging+from os.path import splitextfrom urllib.parse import urlparsefrom django.conf import settingsfrom django.http import HttpResponsefrom rest_framework import status-from rest_framework.exceptions import APIException+from rest_framework.exceptions import APIException, UnsupportedMediaTypeimport django_redisimport requests@@ -20,6 +21,8 @@ class UpstreamThumbnailException(APIException):default_code = "upstream_photon_failure"+ALLOWED_TYPES = {"gif", "jpg", "jpeg", "png", "webp"}+HEADERS = {"User-Agent": settings.OUTBOUND_USER_AGENT_TEMPLATE.format(purpose="ThumbnailGeneration"@@ -27,6 +30,46 @@ HEADERS = {}+def _get_file_extension_from_url(image_url: str) -> str:+ """Return the image extension if present in the URL."""+ parsed = urlparse(image_url)+ _, ext = splitext(parsed.path)+ return ext[1:] # remove the leading dot+++def check_image_type(image_url: str, media_obj) -> None:+ cache = django_redis.get_redis_connection("default")+ key = f"media:{media_obj.identifier}:thumb_type"++ ext = _get_file_extension_from_url(image_url)++ if not ext:+ # If the extension is not present in the URL, try to get it from the redis cache+ ext = cache.get(key)++ if not ext:+ # If the extension is still not present, try getting it from the content type+ try:+ response = requests.head(image_url)+ response.raise_for_status()+ except Exception as exc:+ sentry_sdk.capture_exception(exc)+ raise UpstreamThumbnailException(+ "Failed to render thumbnail due to inability to check media "+ f"type. {exc}"+ )+ else:+ ext = response.headers["Content-Type"]+ if ext and "/" in ext:+ ext = ext.split("/")[1]+ cache.set(key, ext)+ else:+ ext = None++ if ext not in ALLOWED_TYPES:+ raise UnsupportedMediaType(ext)++def _get_photon_params(image_url, is_full_size, is_compressed):"""Photon options documented here:@@ -64,6 +107,8 @@ def get(is_compressed: bool = True,) -> HttpResponse:logger = parent_logger.getChild("get")+ cache = django_redis.get_redis_connection("default")+params, parsed_image_url = _get_photon_params(image_url, is_full_size, is_compressed)@@ -89,7 +134,6 @@ def get(except requests.ReadTimeout as exc:# Count the incident so that we can identify providers with most timeouts.key = f"{settings.THUMBNAIL_TIMEOUT_PREFIX}{domain}"- cache = django_redis.get_redis_connection("default")try:cache.incr(key)except ValueError: # Key does not exist.@@ -99,6 +143,19 @@ def get(raise UpstreamThumbnailException(f"Failed to render thumbnail due to timeout: {exc}")+ except requests.HTTPError as exc:+ # Save number of occurrences to redis. Only raise a Sentry error when+ # the number of occurrences reaches the configured threshold, to+ # prevent provider API downtime from causing excessive Sentry events.+ key = f"{settings.THUMBNAIL_HTTP_ERROR_PREFIX}{domain}"+ errors = 1+ try:+ errors = cache.incr(key)+ except ValueError: # Key does not exist.+ cache.set(key, 1)+ if errors >= settings.THUMBNAIL_HTTP_ERROR_THRESHOLD_TO_NOTIFY:+ sentry_sdk.capture_exception(exc)+ raise UpstreamThumbnailException(f"Failed to render thumbnail. {exc}")except requests.RequestException as exc:sentry_sdk.capture_exception(exc)raise UpstreamThumbnailException(f"Failed to render thumbnail. {exc}")diff --git a/api/api/views/audio_views.py b/api/api/views/audio_views.pyindex 82beda5c3..7d50e78ce 100644--- a/api/api/views/audio_views.py+++ b/api/api/views/audio_views.py@@ -66,14 +66,14 @@ class AudioViewSet(MediaViewSet):audio = self.get_object()image_url = None- if thumbnail := audio.thumbnail:- image_url = thumbnail- elif audio.audio_set and (thumbnail := audio.audio_set.thumbnail):- image_url = thumbnail+ if audio_thumbnail := audio.thumbnail:+ image_url = audio_thumbnail+ elif audio.audio_set and (audio_thumbnail := audio.audio_set.thumbnail):+ image_url = audio_thumbnailif not image_url:raise NotFound("Could not find artwork.")- return super().thumbnail(image_url, request)+ return super().thumbnail(request, audio, image_url)@waveform@action(diff --git a/api/api/views/image_views.py b/api/api/views/image_views.pyindex 6102b3b77..030c74a08 100644--- a/api/api/views/image_views.py+++ b/api/api/views/image_views.py@@ -118,7 +118,7 @@ class ImageViewSet(MediaViewSet):if "iip.smk.dk" in image_url and image.thumbnail:image_url = image.thumbnail- return super().thumbnail(image_url, request)+ return super().thumbnail(request, image, image_url)@watermark_doc@action(detail=True, url_path="watermark", url_name="watermark")diff --git a/api/api/views/media_views.py b/api/api/views/media_views.pyindex 7f824793c..8a2c790a9 100644--- a/api/api/views/media_views.py+++ b/api/api/views/media_views.py@@ -152,9 +152,12 @@ class MediaViewSet(ReadOnlyModelViewSet):return Response(data=serializer.data, status=status.HTTP_201_CREATED)- def thumbnail(self, image_url, request, *_, **__):+ def thumbnail(self, request, media_obj, image_url):serializer = self.get_serializer(data=request.query_params)serializer.is_valid(raise_exception=True)++ photon.check_image_type(image_url, media_obj)+return photon.get(image_url,accept_header=request.headers.get("Accept", "image/*"),diff --git a/api/conf/settings/thumbnails.py b/api/conf/settings/thumbnails.pyindex f936b52df..15a4e5948 100644--- a/api/conf/settings/thumbnails.py+++ b/api/conf/settings/thumbnails.py@@ -19,3 +19,11 @@ THUMBNAIL_QUALITY = config("THUMBNAIL_JPG_QUALITY", default="80")THUMBNAIL_TIMEOUT_PREFIX = config("THUMBNAIL_TIMEOUT_PREFIX", default="thumbnail_timeout:")++THUMBNAIL_HTTP_ERROR_PREFIX = config(+ "THUMBNAIL_HTTP_ERROR_PREFIX", default="thumbnail_http_error:"+)++THUMBNAIL_HTTP_ERROR_THRESHOLD_TO_NOTIFY = config(+ "THUMBNAIL_HTTP_ERROR_THRESHOLD_TO_NOTIFY", default=1000, cast=int+)diff --git a/api/test/unit/utils/test_photon.py b/api/test/unit/utils/test_photon.pyindex 51ad4f629..d1e0eeb32 100644--- a/api/test/unit/utils/test_photon.py+++ b/api/test/unit/utils/test_photon.py@@ -1,12 +1,20 @@+from test.factory.models.image import ImageFactory+from unittest import mockfrom urllib.parse import urlencodefrom django.conf import settings+from rest_framework.exceptions import UnsupportedMediaTypeimport pookimport pytestimport requests-from api.utils.photon import HEADERS, UpstreamThumbnailException+from api.utils.photon import (+ HEADERS,+ UpstreamThumbnailException,+ _get_file_extension_from_url,+ check_image_type,+)from api.utils.photon import get as photon_get@@ -239,6 +247,24 @@ def test_get_timeout_existing_cache_key(assert redis.get(key) == b"6"+def test_get_http_error_pass_threshold(+ capture_exception, setup_requests_get_exception, redis+):+ exc = requests.HTTPError()+ setup_requests_get_exception(exc)+ key = f"{settings.THUMBNAIL_HTTP_ERROR_PREFIX}subdomain.example.com"+ redis.set(key, settings.THUMBNAIL_HTTP_ERROR_THRESHOLD_TO_NOTIFY - 1)++ with pytest.raises(+ UpstreamThumbnailException, match=r"Failed to render thumbnail."+ ):+ photon_get(TEST_IMAGE_URL)++ capture_exception.assert_called_once_with(exc)++ assert redis.get(key) == b"1000"++@pytest.mark.parametrize("exception, expected_message",[@@ -287,7 +313,7 @@ def test_get_successful_https_image_url_sends_ssl_parameter(mock_image_data):@pook.on-def test_get_unsuccessful_request_raises_exception():+def test_get_unsuccessful_request_raises_custom_exception():mock_get: pook.Mock = pook.get(PHOTON_URL_FOR_TEST_IMAGE).reply(404).mockwith pytest.raises(@@ -296,3 +322,44 @@ def test_get_unsuccessful_request_raises_exception():photon_get(TEST_IMAGE_URL)assert mock_get.matched+++ "image_url, expected_ext",+ [+ ("www.example.com/image.jpg", "jpg"),+ ("https://example.com/image.jpeg", "jpeg"),+ ("https://subdomain.example.com/image.svg", "svg"),+ ("https://example.com/image.png?foo=1&bar=2#fragment", "png"),+ ("https://example.com/possibleimagewithoutext", ""),+ (+ "https://iip.smk.dk/iiif/jp2/kksgb22133.tif.jp2/full/!400,/0/default.jpg",+ "jpg",+ ),+ ],+)+def test__get_extension_from_url(image_url, expected_ext):+ assert _get_file_extension_from_url(image_url) == expected_ext++[email protected]("image_type", ["apng", "svg", "bmp"])+def test_check_image_type_raises_by_not_allowed_types(image_type):+ image_url = TEST_IMAGE_URL.replace(".jpg", f".{image_type}")+ image = ImageFactory.create(url=image_url)++ with pytest.raises(UnsupportedMediaType):+ check_image_type(image_url, image)+++def test_check_image_type_saves_image_type_to_cache(redis):+ image_url = TEST_IMAGE_URL.replace(".jpg", "")+ image = ImageFactory.create(url=image_url)++ with mock.patch("requests.head") as mock_head, pytest.raises(UnsupportedMediaType):+ mock_head.return_value.headers = {"Content-Type": "image/svg+xml"}+ check_image_type(image_url, image)++ key = f"media:{image.identifier}:thumb_type"+ assert redis.get(key) == b"svg+xml"diff --git a/api/test/unit/views/test_image_views.py b/api/test/unit/views/test_image_views.pyindex ac2612bc5..7dbaa2745 100644--- a/api/test/unit/views/test_image_views.py+++ b/api/test/unit/views/test_image_views.py@@ -78,4 +78,4 @@ def test_thumbnail_uses_upstream_thumb_for_smk(mock_response = HttpResponse("mock_response")thumb_call.return_value = mock_responseapi_client.get(f"/v1/images/{image.identifier}/thumb/")- thumb_call.assert_called_once_with(expected_thumb_url, ANY)+ thumb_call.assert_called_once_with(ANY, image, expected_thumb_url)