Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Remove bespoke throttle exemption (#792)
sarayourfriend419082f15537
diff --git a/api/catalog/api/migrations/0048_alter_throttledapplication_rate_limit_model.py b/api/catalog/api/migrations/0048_alter_throttledapplication_rate_limit_model.pynew file mode 100644index 000000000..577d2b562--- /dev/null+++ b/api/catalog/api/migrations/0048_alter_throttledapplication_rate_limit_model.py@@ -0,0 +1,18 @@+# Generated by Django 4.0.4 on 2022-07-11 16:55++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('api', '0047_help_text'),+ ]++ operations = [+ migrations.AlterField(+ model_name='throttledapplication',+ name='rate_limit_model',+ field=models.CharField(choices=[('standard', 'standard'), ('enhanced', 'enhanced'), ('exempt', 'exempt')], default='standard', max_length=20),+ ),+ ]diff --git a/api/catalog/api/models/oauth.py b/api/catalog/api/models/oauth.pyindex e81eab2ef..fbb7bb908 100644--- a/api/catalog/api/models/oauth.py+++ b/api/catalog/api/models/oauth.py@@ -33,8 +33,10 @@ class ThrottledApplication(AbstractApplication):RATE_LIMIT_MODELS = [("standard", "standard"), # Default rate limit for all API keys.- ("enhanced", "enhanced") # Rate limits for "super" keys, granted on a+ ("enhanced", "enhanced"), # Rate limits for "super" keys, granted on a# case-by-case basis.+ ("exempt", "exempt"), # Rate limits used for internal infrastructure to+ # by-pass rate limiting entirely.]rate_limit_model = models.CharField(max_length=20, choices=RATE_LIMIT_MODELS, default="standard"diff --git a/api/catalog/api/utils/oauth2_helper.py b/api/catalog/api/utils/oauth2_helper.pyindex e7673e771..02a6c99de 100644--- a/api/catalog/api/utils/oauth2_helper.py+++ b/api/catalog/api/utils/oauth2_helper.py@@ -8,6 +8,8 @@ from catalog.api import modelsparent_logger = logging.getLogger(__name__)+_no_result = (None, None, None)+def get_token_info(token: str):"""@@ -17,25 +19,33 @@ def get_token_info(token: str)::param token: An OAuth2 access token.:return: If the token is valid, return the client ID associated with thetoken, rate limit model, and email verification status as a tuple; else- return (None, None, None).+ return ``(None, None, None)``."""logger = parent_logger.getChild("get_token_info")try:token = AccessToken.objects.get(token=token)except AccessToken.DoesNotExist:- return None, None, None- if token.expires >= dt.datetime.now(token.expires.tzinfo):- try:- application = models.ThrottledApplication.objects.get(accesstoken=token)- client_id = str(application.client_id)- rate_limit_model = application.rate_limit_model- verified = application.verified- except models.ThrottledApplication.DoesNotExist:- logger.warning("Failed to find application associated with access token.")- client_id = None- rate_limit_model = None- verified = None- return client_id, rate_limit_model, verified- else:- logger.warning("Rejected expired access token.")- return None, None, None+ return _no_result++ try:+ application = models.ThrottledApplication.objects.get(accesstoken=token)+ except models.ThrottledApplication.DoesNotExist:+ # Critical because it indicates a data integrity problem.+ # In practice should never occur so long as the preceeding+ # operation to retrieve the access token was successful.+ logger.critical("Failed to find application associated with access token.")+ return _no_result++ expired = token.expires < dt.datetime.now(token.expires.tzinfo)+ if expired:+ logger.info(+ "rejected expired access token "+ f"application.name={application.name} "+ f"application.client_id={application.client_id} "+ )+ return _no_result++ client_id = str(application.client_id)+ rate_limit_model = application.rate_limit_model+ verified = application.verified+ return client_id, rate_limit_model, verifieddiff --git a/api/catalog/api/utils/throttle.py b/api/catalog/api/utils/throttle.pyindex 43120196a..1814b2d1d 100644--- a/api/catalog/api/utils/throttle.py+++ b/api/catalog/api/utils/throttle.py@@ -1,4 +1,5 @@import abc+import loggingfrom rest_framework.throttling import SimpleRateThrottle@@ -7,144 +8,74 @@ from django_redis import get_redis_connectionfrom catalog.api.utils.oauth2_helper import get_token_info-class ThrottleExemption(abc.ABC):- """- Abstract class describing a given throttle exemption.-- To be included in an iterable of ``ThrottleExemption``s- in children of ``ExemptionAwareThrottle``.- """-- def __init__(self, throttle_class, request):- """- :param throttle_class: The throttle class the exemption modifies.- :param request: The current request against which to evaluate the exemption.- """- self.throttle_class = throttle_class- self.request = request-- @abc.abstractmethod- def is_exempt(self) -> bool:- """- Whether the current request is exempt from throttling.-- :return: ``True`` if exempt, ``False`` otherwise.- """- ...---class ExemptionAwareThrottle(SimpleRateThrottle):- """- An throttle exemption aware base throttle.-- Classes in ``exemption_classes`` are evaluated for each- request. If any of them detect an exempted request then- the request will not be throttled.- """-- exemption_classes = []-- def allow_request(self, request, view):- """- Short circuit ``allow_request`` if _any_ exemption- declares the request to be exempt from the throttle.- """- for exemption_class in self.exemption_classes:- if exemption_class(self, request).is_exempt():- return True-- return super().allow_request(request, view)-+parent_logger = logging.getLogger(__name__)-class InternalNetworkExemption(ThrottleExemption):- redis_set_name = "ip-whitelist"- def is_exempt(self):- """- Exempts requests coming from within Openverse's own- network. In practical terms this prevents the Nuxt server- from being rate-limited when server-side-rendering.- """- ip = self.throttle_class.get_ident(self.request)- redis = get_redis_connection("default", write=False)- return redis.sismember(self.redis_set_name, ip)---class ApiKeyExemption(ThrottleExemption):- redis_set_name = "client-id-allowlist"-- def is_exempt(self):- """- Exempt certain API keys from throttling. In practical- terms this is used to prevent large consumers of- Openverse's API like WordPress.com and Jetpack from- being rate-limited.- """- client_id, _, _ = get_token_info(str(self.request.auth))- if not client_id:- return False-- redis = get_redis_connection("default")- return redis.sismember(self.redis_set_name, client_id)---class AnonRateThrottle(ExemptionAwareThrottle):+class AbstractAnonRateThrottle(SimpleRateThrottle, metaclass=abc.ABCMeta):"""Limits the rate of API calls that may be made by a anonymous users.The IP address of the request will be used as the unique cache key."""- scope = "anon"- exemption_classes = [InternalNetworkExemption, ApiKeyExemption]+ logger = parent_logger.getChild("AnonRateThrottle")def get_cache_key(self, request, view):- # Do not throttle requests with a valid access token.+ logger = self.logger.getChild("get_cache_key")+ # Do not apply anonymous throttle to request with valid tokens.if request.auth:client_id, _, verified = get_token_info(str(request.auth))if client_id and verified:return None+ ident = self.get_ident(request)+ redis = get_redis_connection("default", write=False)+ if redis.sismember("ip-whitelist", ident):+ logger.info(f"bypassing rate limiting for ident={ident}")+ """+ Exempt internal IP addresses. Exists as a legacy holdover and usages of this+ should be replaced with the exempt API key as it is easier to manage via+ Django admin and doesn't require leaky permissions in our production infra.+ """+ return None+return self.cache_format % {"scope": self.scope,- "ident": self.get_ident(request),+ "ident": ident,}-class PostRequestThrottler(AnonRateThrottle):- rate = "30/day"---class BurstRateThrottle(AnonRateThrottle):+class BurstRateThrottle(AbstractAnonRateThrottle):scope = "anon_burst"-class SustainedRateThrottle(AnonRateThrottle):+class SustainedRateThrottle(AbstractAnonRateThrottle):scope = "anon_sustained"-class TenPerDay(AnonRateThrottle):+class TenPerDay(AbstractAnonRateThrottle):rate = "10/day"-class OneThousandPerMinute(AnonRateThrottle):+class OneThousandPerMinute(AbstractAnonRateThrottle):rate = "1000/min"-class OnePerSecond(AnonRateThrottle):+class OnePerSecond(AbstractAnonRateThrottle):rate = "1/second"-class OAuth2IdThrottleRate(ExemptionAwareThrottle):+class AbstractOAuth2IdRateThrottle(SimpleRateThrottle, metaclass=abc.ABCMeta):"""- Limits the rate of API calls that may be made by a given user's Oauth2- client ID. Can be configured to apply to either standard or enhanced- API keys.+ Ties a particular configured throttling scope from ``settings.py`` to+ a "rate limit model". See ``ThrottledApplication.rate_limit_model``+ for an explanation of that concept."""- scope = "oauth2_client_credentials"- applies_to_rate_limit_model = "standard"- exemption_classes = [InternalNetworkExemption, ApiKeyExemption]+ scope: str+ # The name of the scope. Used to retrieve the rate limit from settings.+ applies_to_rate_limit_model: str+ # The ``ThrottledApplication.rate_limit_model`` to which the scope applies.def get_cache_key(self, request, view):# Find the client ID associated with the access token.@@ -153,28 +84,32 @@ class OAuth2IdThrottleRate(ExemptionAwareThrottle):if client_id and rate_limit_model == self.applies_to_rate_limit_model:ident = client_idelse:- # Don't throttle invalid tokens; leave that to the anonymous- # throttlers. Don't throttle enhanced rate limit tokens either.+ # Return None, fallback to the anonymous rate limitingreturn Nonereturn self.cache_format % {"scope": self.scope, "ident": ident}-class OAuth2IdThrottleSustainedRate(OAuth2IdThrottleRate):+class OAuth2IdSustainedRateThrottle(AbstractOAuth2IdRateThrottle):applies_to_rate_limit_model = "standard"scope = "oauth2_client_credentials_sustained"-class OAuth2IdThrottleBurstRate(OAuth2IdThrottleRate):+class OAuth2IdBurstRateThrottle(AbstractOAuth2IdRateThrottle):applies_to_rate_limit_model = "standard"scope = "oauth2_client_credentials_burst"-class EnhancedOAuth2IdThrottleSustainedRate(OAuth2IdThrottleRate):+class EnhancedOAuth2IdSustainedRateThrottle(AbstractOAuth2IdRateThrottle):applies_to_rate_limit_model = "enhanced"scope = "enhanced_oauth2_client_credentials_sustained"-class EnhancedOAuth2IdThrottleBurstRate(OAuth2IdThrottleRate):+class EnhancedOAuth2IdBurstRateThrottle(AbstractOAuth2IdRateThrottle):applies_to_rate_limit_model = "enhanced"scope = "enhanced_oauth2_client_credentials_burst"+++class ExemptOAuth2IdRateThrottle(AbstractOAuth2IdRateThrottle):+ applies_to_rate_limit_model = "exempt"+ scope = "exempt_oauth2_client_credentials"diff --git a/api/catalog/settings.py b/api/catalog/settings.pyindex 2e018011e..72edb602a 100644--- a/api/catalog/settings.py+++ b/api/catalog/settings.py@@ -142,10 +142,11 @@ REST_FRAMEWORK = {"DEFAULT_THROTTLE_CLASSES": ("catalog.api.utils.throttle.BurstRateThrottle","catalog.api.utils.throttle.SustainedRateThrottle",- "catalog.api.utils.throttle.OAuth2IdThrottleSustainedRate",- "catalog.api.utils.throttle.OAuth2IdThrottleBurstRate",- "catalog.api.utils.throttle.EnhancedOAuth2IdThrottleSustainedRate",- "catalog.api.utils.throttle.EnhancedOAuth2IdThrottleBurstRate",+ "catalog.api.utils.throttle.OAuth2IdSustainedRateThrottle",+ "catalog.api.utils.throttle.OAuth2IdBurstRateThrottle",+ "catalog.api.utils.throttle.EnhancedOAuth2IdSustainedRateThrottle",+ "catalog.api.utils.throttle.EnhancedOAuth2IdBurstRateThrottle",+ "catalog.api.utils.throttle.ExemptOAuth2IdRateThrottle",),"DEFAULT_THROTTLE_RATES": {"anon_burst": THROTTLE_ANON_BURST,@@ -154,12 +155,18 @@ REST_FRAMEWORK = {"oauth2_client_credentials_burst": "100/min","enhanced_oauth2_client_credentials_sustained": "20000/day","enhanced_oauth2_client_credentials_burst": "200/min",+ # ``None`` completely by-passes the rate limiting+ "exempt_oauth2_client_credentials": None,},"EXCEPTION_HANDLER": "catalog.api.utils.exceptions.exception_handler",}if config("DISABLE_GLOBAL_THROTTLING", default=True, cast=bool):- del REST_FRAMEWORK["DEFAULT_THROTTLE_RATES"]+ # Set all to ``None`` rather than deleting so that explicitly configured+ # throttled views in tests still have the default rates to fall back onto+ REST_FRAMEWORK["DEFAULT_THROTTLE_RATES"].update(+ **{k: None for k, _ in REST_FRAMEWORK["DEFAULT_THROTTLE_RATES"].items()}+ )del REST_FRAMEWORK["DEFAULT_THROTTLE_CLASSES"]REDIS_HOST = config("REDIS_HOST", default="localhost")diff --git a/api/docs/reference/api/authentication_and_throttling.md b/api/docs/reference/api/authentication_and_throttling.mdnew file mode 100644index 000000000..9260b4313--- /dev/null+++ b/api/docs/reference/api/authentication_and_throttling.md@@ -0,0 +1,33 @@+# Authentication and Throttling++This document primarily serves to document our additions to DRF's built-in throttling support. In order to accomplish this, some basic facts about our OAuth flow and configuration must also be explained.++This document deals primarily with the server's perspective of the OAuth flow and assumes you are familiar with the user's perspective. If you are not familiar with the user's perspective, please study the [Register and Authenticate](https://api.openverse.engineering/v1/#section/Register-and-Authenticate) section of the API documentation.++Furthermore, this section assumes at least a surface level understanding of the `django-oauth-toolkit` library and its concepts. In particular, it is necessary to understand the [`Application` concept, the docs for which can be found here](https://django-oauth-toolkit.readthedocs.io/en/latest/advanced_topics.html#extending-the-application-model).++## Flow++When a user makes the initial request to create their OAuth application, we create a `ThrottledApplication` model to associate to the likewise generated OAuth client. Whenever the user generates a new token using their client ID and key pair, it is automatically associated with the `ThrottledApplication` for the client via a [foreign key referencing the application on the access token](https://django-oauth-toolkit.readthedocs.io/en/latest/models.html#oauth2_provider.models.AbstractAccessToken). This allows us to retrieve the application for the token using just the token itself.++## `ThrottledApplication`++The `ThrottledApplication` is an extension of the base `AbstractApplication` class from `django-oauth-toolkit` that adds an additional concept of a `rate_limit_model`. Each rate limit model can be thought of as a "tiers" of rate limiting that the Openverse API supports.++## Rate limit models (tiers)++The following tiers exist:++* `standard`: The default rate limit that anyone is able to unlock simply by authenticating. Slightly higher and much more useful limit for an application.+* `enhanced`: A selectively granted rate limit that allows for significantly higher burst and sustained requests.+* `exempt`: A rate limit model that exists purely to accommodate internal infrastructural needs. For example, the server that renders the frontend can use tokens of this tier to prevent itself from being rate limited by the API during server side rendering. Likewise, when we need to circumvent the throttling to do load testing, we use a key of this tier.++## Throttles++Each of these tiers also have corresponding throttle classes that are configured in `settings.py`. Each throttle class declares a "scope" applied to it. The "scope" defines the rate. The throttle class merely indicates to the view whether it itself applies to the incoming request. If it does not, then it returns a `None` cache key from `get_cache_key` and the view ignores the throttle class. If the throttle does apply to the request, then it returns a formatted cache key that the base DRF view then uses to determine whether the requester is still within the limits of their scope.++To further understand this concept, it may be helpful to read the code for [`SimpleRateThrottle`](https://github.com/encode/django-rest-framework/blob/129890ab1bbbba2deb96b8e30675dfb1060d7615/rest_framework/throttling.py#L50) and the [`check_throttles` method of the DRF base view class](https://github.com/encode/django-rest-framework/blob/101aff6c43f6fa96174683e050988428143d1040/rest_framework/views.py#L352-L371).++Each of the tiers above have their own scope namespace. For example, enhanced applications will use the scopes namespaced with `enhanced_oauth2_client_credentials`. To determine which scope a given authenticated request should have applied to it, we need to determine which application rate limit tier it belongs to. To simplify this abstract process, we use the `OAuth2IdRateThrottle` base class. All it does is take an incoming authenticated request, retrieve the application for the given access token, and then create a cache key based on the client ID and scope if the class is configured to handle the application's rate limit tier.++Individual tiers have complementary subclasses of `OAuth2IdRateThrottle` that configure which scope to apply to a particular rate limit tier. Please refer to the `catalog.api.utils.throttle` module for example implementations of this pattern.diff --git a/api/docs/reference/api/index.rst b/api/docs/reference/api/index.rstindex 3a8e539d2..75f837fd4 100644--- a/api/docs/reference/api/index.rst+++ b/api/docs/reference/api/index.rst@@ -1,6 +1,13 @@catalog.api package===================+Concepts+--------++.. toctree::++ authentication_and_throttling.md+Subpackages-----------diff --git a/api/test/unit/management/commands/resendoauthverification_test.py b/api/test/unit/management/commands/resendoauthverification_test.pyindex 5b6e7e4d1..d2c27baaf 100644--- a/api/test/unit/management/commands/resendoauthverification_test.py+++ b/api/test/unit/management/commands/resendoauthverification_test.py@@ -19,7 +19,6 @@ from catalog.api.models.oauth import (OAuth2Verification,ThrottledApplication,)-from catalog.api.utils.throttle import ExemptionAwareThrottlefrom catalog.api.views.oauth2_views import Register@@ -339,7 +338,8 @@ def register_with_email_times(email: str, times: int) -> list:]view = Register.as_view()- return [view(request) for request in requests]+ with mock.patch.object(Register, "throttle_classes", ()):+ return [view(request) for request in requests]@pytest.mark.django_db@@ -351,13 +351,10 @@ def test_create_tokens_with_view(captured_emails):]with mock.patch("catalog.api.views.oauth2_views.send_mail"):- with mock.patch.object(- ExemptionAwareThrottle, "allow_request", return_value=True- ):- for email in emails:- responses = register_with_email_times(email, 10)- for response in responses:- assert response.status_code == 201+ for email in emails:+ responses = register_with_email_times(email, 10)+ for response in responses:+ assert response.status_code == 201# assert everything was created in the registration viewfor email in emails:diff --git a/api/test/unit/utils/throttle_test.py b/api/test/unit/utils/throttle_test.pyindex c112cadb5..61a6ac360 100644--- a/api/test/unit/utils/throttle_test.py+++ b/api/test/unit/utils/throttle_test.py@@ -1,66 +1,18 @@from test.factory.models.oauth2 import AccessTokenFactory-from rest_framework.response import Responsefrom rest_framework.test import APIRequestFactory, force_authenticatefrom rest_framework.views import APIViewimport pytestfrom fakeredis import FakeRedis-from catalog.api.utils.oauth2_helper import get_token_info+from catalog.api.models.oauth import ThrottledApplicationfrom catalog.api.utils.throttle import (- ApiKeyExemption,- ExemptionAwareThrottle,- InternalNetworkExemption,- ThrottleExemption,+ AbstractAnonRateThrottle,+ AbstractOAuth2IdRateThrottle,)-class HardThrottle(ExemptionAwareThrottle):- """- A test throttle that denies all requests.-- This is helpful for testing whether the exemptions- are working.- """-- rate = "0/second"- scope = "test"-- def get_cache_key(self, request, view):- return {- "scope": self.scope,- "ident": self.get_ident(request),- }---class MockInternalNetworkExemptThrottle(HardThrottle):- exemption_classes = (InternalNetworkExemption,)---class MockApiKeyExemptThrottle(HardThrottle):- exemption_classes = (ApiKeyExemption,)---class FooRouteExemption(ThrottleExemption):- def is_exempt(self):- return self.request.path.startswith("/foo")---class MockMultipleExemptionThrottle(HardThrottle):- exemption_classes = (InternalNetworkExemption, ApiKeyExemption, FooRouteExemption)---def get_throttled_view(throttle_class):- class MockView(APIView):- throttle_classes = (throttle_class,)-- def get(self, request):- return Response("foo")-- return MockView().as_view()--@pytest.fixture(autouse=True)def redis(monkeypatch) -> FakeRedis:fake_redis = FakeRedis()@@ -85,7 +37,10 @@ def request_factory() -> APIRequestFactory():@pytest.fixturedef access_token():- return AccessTokenFactory.create()+ token = AccessTokenFactory.create()+ token.application.verified = True+ token.application.save()+ return token@pytest.fixture@@ -97,104 +52,82 @@ def authed_request(access_token, request_factory):return request-def assert_view_consistent_status_code(view, request, expected_status, times=4):- for _ in range(times):- assert view(request).status_code == expected_status---def assert_throttles(view, request, times=4):- assert_view_consistent_status_code(view, request, expected_status=429, times=times)---def assert_does_not_throttle(view, request, times=4):- assert_view_consistent_status_code(view, request, expected_status=200, times=times)---def test_hard_throttle_denies_requests(request_factory):- view = get_throttled_view(HardThrottle)- request = request_factory.get("/")- assert_throttles(view, request)---def test_internal_network_exemption_passes_when_ip_in_allowlist(redis, request_factory):- view = get_throttled_view(MockInternalNetworkExemptThrottle)- request = request_factory.get("/")- redis.sadd(InternalNetworkExemption.redis_set_name, request.META["REMOTE_ADDR"])- assert_does_not_throttle(view, request)---def test_internal_network_exemption_throttles_when_ip_not_in_allowlist(- redis, request_factory-):- view = get_throttled_view(MockInternalNetworkExemptThrottle)- request = request_factory.get("/")- assert not redis.sismember(- InternalNetworkExemption.redis_set_name, request.META["REMOTE_ADDR"]- )- assert_throttles(view, request)+def view():+ return APIView()+ "throttle_class",+ AbstractAnonRateThrottle.__subclasses__(),+)@pytest.mark.django_db-def test_api_key_exemption_passes_when_token_in_allowlist(- redis, access_token, authed_request+def test_anon_rate_throttle_ignores_authed_requests(+ throttle_class, authed_request, view):- view = get_throttled_view(MockApiKeyExemptThrottle)- client_id, _, _ = get_token_info(access_token.token)- redis.sadd(ApiKeyExemption.redis_set_name, client_id)- assert_does_not_throttle(view, authed_request)+ throttle = throttle_class()+ assert throttle.get_cache_key(view.initialize_request(authed_request), view) is None+ "throttle_class",+ AbstractAnonRateThrottle.__subclasses__(),+)@pytest.mark.django_db-def test_api_key_exemption_throttles_when_token_not_in_allowlist(- redis, access_token, authed_request+def test_anon_rate_throttle_ignores_exempted_ips(+ throttle_class, redis, request_factory, view):- view = get_throttled_view(MockApiKeyExemptThrottle)- client_id, _, _ = get_token_info(access_token.token)- assert not redis.sismember(ApiKeyExemption.redis_set_name, client_id)- assert_throttles(view, authed_request)---def test_api_key_exemption_throttles_with_unauthed_request(request_factory):request = request_factory.get("/")- view = get_throttled_view(MockApiKeyExemptThrottle)- assert_throttles(view, request)+ redis.sadd("ip-whitelist", request.META["REMOTE_ADDR"])+ throttle = throttle_class()+ assert throttle.get_cache_key(view.initialize_request(request), view) is None+ "throttle_class",+ AbstractAnonRateThrottle.__subclasses__(),+)@pytest.mark.django_db-def test_multiple_exemptions_allows_if_one_passes_api_key(- redis, access_token, authed_request+def test_anon_rate_throttle_returns_formatted_cache_key_for_anonymous_request(+ throttle_class, request_factory, view):- view = get_throttled_view(MockMultipleExemptionThrottle)- client_id, _, _ = get_token_info(access_token.token)- redis.sadd(ApiKeyExemption.redis_set_name, client_id)- assert not redis.sismember(- InternalNetworkExemption.redis_set_name, authed_request.META["REMOTE_ADDR"]- )- assert_does_not_throttle(view, authed_request)+ request = request_factory.get("/")+ throttle = throttle_class()+ assert throttle.get_cache_key(view.initialize_request(request), view) is not None+ "throttle_class",+ AbstractOAuth2IdRateThrottle.__subclasses__(),+)@pytest.mark.django_db-def test_multiple_exemptions_allows_if_one_passes_internal_network(- redis, access_token, authed_request+def test_abstract_oauth2_id_rate_throttle_applies_if_token_app_rate_limit_model_matches(+ access_token, authed_request, view, throttle_class):- view = get_throttled_view(MockMultipleExemptionThrottle)- client_id, _, _ = get_token_info(access_token.token)- redis.sadd(- InternalNetworkExemption.redis_set_name, authed_request.META["REMOTE_ADDR"]+ throttle = throttle_class()+ access_token.application.rate_limit_model = (+ throttle_class.applies_to_rate_limit_model+ )+ access_token.application.save()+ assert (+ throttle.get_cache_key(view.initialize_request(authed_request), view)+ is not None)- assert not redis.sismember(ApiKeyExemption.redis_set_name, client_id)- assert_does_not_throttle(view, authed_request)+ "throttle_class",+ AbstractOAuth2IdRateThrottle.__subclasses__(),+)@pytest.mark.django_db-def test_multiple_exemptions_throttles_if_none_pass(- redis, access_token, authed_request+def test_abstract_oauth2_id_rate_throttle_does_not_apply_if_token_app_rate_limit_model_differs(+ access_token, authed_request, view, throttle_class):- view = get_throttled_view(MockMultipleExemptionThrottle)- client_id, _, _ = get_token_info(access_token.token)- assert not redis.sismember(- InternalNetworkExemption.redis_set_name, authed_request.META["REMOTE_ADDR"]+ throttle = throttle_class()+ access_token.application.rate_limit_model = next(+ m[0]+ for m in ThrottledApplication.RATE_LIMIT_MODELS+ if m[0] != throttle_class.applies_to_rate_limit_model)- assert not redis.sismember(ApiKeyExemption.redis_set_name, client_id)- assert_throttles(view, authed_request)+ access_token.application.save()+ assert throttle.get_cache_key(view.initialize_request(authed_request), view) is Nonediff --git a/justfile b/justfileindex 507d995e8..731354318 100644--- a/justfile+++ b/justfile@@ -53,6 +53,10 @@ recreate:logs services="" args=(if IS_CI != "" { "" } else { "-f" }):docker-compose {{ DOCKER_FILE }} logs {{ args }} {{ services }}+# Attach to the specificed `service`. Enables interacting with the TTY of the running service.+attach service:+ docker attach $(docker-compose ps | grep {{ service }} | awk '{print $1}')+EXEC_DEFAULTS := if IS_CI == "" { "" } else { "-T" }# Execute statement in service containers using Docker Compose