Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Set rate-limit headers on each response (#775)
Dhruv Bhanushali9bfba45295e5
diff --git a/api/catalog/api/docs/README.md b/api/catalog/api/docs/README.mdindex cf59ea2bd..69d2351bc 100644--- a/api/catalog/api/docs/README.md+++ b/api/catalog/api/docs/README.md@@ -1,5 +1,6 @@This documentation is focused towards consumers who are using the Openverse API.-The developer documentation for the Openverse API can be found [here]().+To contribute to the development of the Openverse API, please refer to the+[Openverse developer documentation](https://wordpress.githb.io/openverse/).# Introduction@@ -9,12 +10,25 @@ openly-licensed works, including articles, songs, videos, photographs,paintings, and more. Using this API, developers will be able to access thedigital commons in their own applications.-Please note that there is a rate limit of 100 requests per day and 5 requests-per hour rate limit in place for anonymous users. This is fine for introducing-yourself to the API, but we strongly recommend that you obtain an API key as-soon as possible. Authorized clients have a higher rate limit of 10000 requests-per day and 100 requests per minute. Additionally, Openverse can give your key-an even higher limit that fits your application's needs. See the+# Rate limits++Please note that the API has imposed rate limits to prevent abuse. In the+response for each request that is subject to rate-limits, you can see the+`X-RateLimit-` headers for information about your permitted and available usage.+Exceeding the limit will result in '429: Too Many Requests' responses.++## Anonymous usage++Anonymous usage is subject to a rate limit of 100 requests per day and,+simultaneously, 5 requests per hour. This is fine for introducing yourself to+the API, but we strongly recommend that you obtain an API key as soon as+possible.++## Authenticated usage++Authorized clients have a higher rate limit of 10000 requests per day and 100+requests per minute. Additionally, Openverse can give your key an even higher+limit that fits your application's needs. See the[Register and Authenticate section](#section/Register-and-Authenticate) forinstructions on obtaining an API key.@@ -36,6 +50,7 @@ $ curl \```If your request is successful, you will get a `client_id` and `client_secret`.+Save these keys securely because you will not be able to see them again.Example of successful request:diff --git a/api/catalog/api/utils/throttle.py b/api/catalog/api/utils/throttle.pyindex 5ff5bd6dd..d57f9362a 100644--- a/api/catalog/api/utils/throttle.py+++ b/api/catalog/api/utils/throttle.py@@ -11,7 +11,36 @@ from catalog.api.utils.oauth2_helper import get_token_infoparent_logger = logging.getLogger(__name__)-class AbstractAnonRateThrottle(SimpleRateThrottle, metaclass=abc.ABCMeta):+class SimpleRateThrottleHeader(SimpleRateThrottle, metaclass=abc.ABCMeta):+ """+ Extends the ``SimpleRateThrottle`` class to provide additional functionality such as+ rate-limit headers in the response.+ """++ def allow_request(self, request, view):+ is_allowed = super().allow_request(request, view)+ view.headers |= self.headers()+ return is_allowed++ def headers(self):+ """+ Get `X-RateLimit-` headers for this particular throttle. Each pair of headers+ contains the limit and the number of requests left in the limit. Since multiple+ rate limits can apply concurrently, the suffix identifies each pair uniquely.+ """++ prefix = "X-RateLimit"+ suffix = self.scope or self.__class__.__name__.lower()+ if hasattr(self, "history"):+ return {+ f"{prefix}-Limit-{suffix}": self.rate,+ f"{prefix}-Available-{suffix}": self.num_requests - len(self.history),+ }+ else:+ return {}+++class AbstractAnonRateThrottle(SimpleRateThrottleHeader, metaclass=abc.ABCMeta):"""Limits the rate of API calls that may be made by a anonymous users.@@ -61,15 +90,11 @@ class TenPerDay(AbstractAnonRateThrottle):rate = "10/day"-class OneThousandPerMinute(AbstractAnonRateThrottle):- rate = "1000/min"--class OnePerSecond(AbstractAnonRateThrottle):rate = "1/second"-class AbstractOAuth2IdRateThrottle(SimpleRateThrottle, metaclass=abc.ABCMeta):+class AbstractOAuth2IdRateThrottle(SimpleRateThrottleHeader, metaclass=abc.ABCMeta):"""Ties a particular throttling scope from ``settings.py`` to a rate limit model.diff --git a/api/catalog/api/views/audio_views.py b/api/catalog/api/views/audio_views.pyindex fb65cd78a..3a2f9e5c5 100644--- a/api/catalog/api/views/audio_views.py+++ b/api/catalog/api/views/audio_views.py@@ -23,7 +23,10 @@ from catalog.api.serializers.audio_serializers import (AudioWaveformSerializer,)from catalog.api.serializers.media_serializers import MediaThumbnailRequestSerializer-from catalog.api.utils.throttle import OneThousandPerMinute+from catalog.api.utils.throttle import (+ AnonThumbnailRateThrottle,+ OAuth2IdThumbnailRateThrottle,+)from catalog.api.views.media_views import MediaViewSet@@ -54,7 +57,7 @@ class AudioViewSet(MediaViewSet):url_path="thumb",url_name="thumb",serializer_class=MediaThumbnailRequestSerializer,- throttle_classes=[OneThousandPerMinute],+ throttle_classes=[AnonThumbnailRateThrottle, OAuth2IdThumbnailRateThrottle],)def thumbnail(self, request, *_, **__):audio = self.get_object()@@ -72,7 +75,7 @@ class AudioViewSet(MediaViewSet):@action(detail=True,serializer_class=AudioWaveformSerializer,- throttle_classes=[OneThousandPerMinute],+ throttle_classes=[AnonThumbnailRateThrottle, OAuth2IdThumbnailRateThrottle],)def waveform(self, *_, **__):audio = self.get_object()diff --git a/api/test/unit/utils/throttle_test.py b/api/test/unit/utils/throttle_test.pyindex f3cd08e57..7d47c4daa 100644--- a/api/test/unit/utils/throttle_test.py+++ b/api/test/unit/utils/throttle_test.py@@ -1,5 +1,6 @@from test.factory.models.oauth2 import AccessTokenFactory+from django.core.cache import cachefrom rest_framework.test import force_authenticatefrom rest_framework.views import APIView@@ -10,6 +11,8 @@ from catalog.api.models.oauth import ThrottledApplicationfrom catalog.api.utils.throttle import (AbstractAnonRateThrottle,AbstractOAuth2IdRateThrottle,+ BurstRateThrottle,+ TenPerDay,)@@ -124,3 +127,50 @@ def test_abstract_oauth2_id_rate_throttle_does_not_apply_if_token_app_rate_limit)access_token.application.save()assert throttle.get_cache_key(view.initialize_request(authed_request), view) is None+++def test_rate_limit_headers(request_factory):+ cache.delete_pattern("throttle_*")+ limit = 2++ class DummyThrottle(BurstRateThrottle):+ THROTTLE_RATES = {"anon_burst": f"{limit}/hour"}++ class ThrottledView(APIView):+ throttle_classes = [DummyThrottle]++ view = ThrottledView().as_view()+ request = request_factory.get("/")++ # Send three requests. The third one should be throttled.+ for idx in range(1, limit + 2):+ response = view(request)+ headers = [h for h in response.headers.items() if "X-RateLimit" in h[0]]++ # Assert that request returns 429 response if limit has been exceeded.+ assert response.status_code == 429 if idx == limit + 1 else 200++ # Assert that the 'Available' header constantly decrements, but not below zero.+ assert [+ ("X-RateLimit-Limit-anon_burst", f"{limit}/hour"),+ ("X-RateLimit-Available-anon_burst", str(max(0, limit - idx))),+ ] == headers+++def test_rate_limit_headers_when_no_scope(request_factory):+ cache.delete_pattern("throttle_*")++ class ThrottledView(APIView):+ throttle_classes = [TenPerDay]++ view = ThrottledView().as_view()+ request = request_factory.get("/")++ response = view(request)+ headers = [h for h in response.headers.items() if "X-RateLimit" in h[0]]+ assert [+ ("X-RateLimit-Limit-tenperday", "10/day"),+ ("X-RateLimit-Available-tenperday", "9"),+ ] == headers