Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add throttling for ingredient endpoints to protect against high load

Roland Geider00eb981945d6
diff --git a/settings/settings_global.py b/settings/settings_global.py
index e00dadc6b..9d5bfe502 100644
--- a/settings/settings_global.py
+++ b/settings/settings_global.py
@@ -394,7 +394,17 @@ REST_FRAMEWORK = {
'rest_framework.filters.OrderingFilter',
),
'DEFAULT_THROTTLE_CLASSES': ['rest_framework.throttling.ScopedRateThrottle'],
- 'DEFAULT_THROTTLE_RATES': {'login': '10/min', 'registration': '5/min'},
+ 'DEFAULT_THROTTLE_RATES': {
+ 'login': '10/min',
+ 'registration': '5/min',
+
+ # Ingredient endpoints — protect the multi-million-row table from
+ # crawlers and older sync clients. Throttling is per-IP for anonymous
+ # callers and per-user for authenticated ones.
+ 'ingredient_list': '120/min',
+ 'ingredient_detail': '300/min',
+ 'ingredient_sync': '600/min',
+ },
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
diff --git a/wger/nutrition/api/views.py b/wger/nutrition/api/views.py
index b3eae8395..5454854d7 100644
--- a/wger/nutrition/api/views.py
+++ b/wger/nutrition/api/views.py
@@ -67,6 +67,7 @@ from wger.utils.constants import (
)
from wger.utils.db import is_postgres_db
from wger.utils.language import load_language
+from wger.utils.pagination import IngredientCursorPagination
from wger.utils.viewsets import WgerOwnerObjectModelViewSet
@@ -86,6 +87,18 @@ class IngredientViewSet(viewsets.ReadOnlyModelViewSet):
'language',
'license',
).prefetch_related('ingredientweightunit_set')
+ throttle_scope = 'ingredient_list'
+
+ def get_throttles(self):
+ """
+ Apply distinct throttle scopes to list and detail actions.
+
+ List queries on a 3M-row table are expensive (sort, deep pagination);
+ detail queries are cheap PK lookups. Separate buckets keep autocomplete
+ and detail loads from competing for the same quota.
+ """
+ self.throttle_scope = ('ingredient_list' if self.action == 'list' else 'ingredient_detail')
+ return super().get_throttles()
@method_decorator(cache_page(settings.WGER_SETTINGS['INGREDIENT_CACHE_TTL']))
def list(self, request, *args, **kwargs):
diff --git a/wger/nutrition/tests/test_ingredient.py b/wger/nutrition/tests/test_ingredient.py
index 985e34540..35356f6da 100644
--- a/wger/nutrition/tests/test_ingredient.py
+++ b/wger/nutrition/tests/test_ingredient.py
@@ -16,14 +16,12 @@
# Standard Library
import datetime
import json
-from decimal import Decimal
from unittest.mock import (
MagicMock,
patch,
)
# Django
-from django.core.exceptions import ValidationError
from django.test import SimpleTestCase
from django.urls import reverse
@@ -41,6 +39,10 @@ from wger.core.tests.base_testcase import (
WgerEditTestCase,
WgerTestCase,
)
+from wger.nutrition.api.views import (
+ IngredientSyncViewSet,
+ IngredientViewSet,
+)
from wger.nutrition.extract_info.off import extract_info_from_off
from wger.nutrition.models import (
Ingredient,
@@ -767,3 +769,29 @@ class ImageFromJsonSimpleTests(SimpleTestCase):
self.assertIsInstance(img, Image)
self.assertNotEqual(str(img.uuid), json_data['uuid'])
self.assertEqual(img.size, 54321)
+
+
+class IngredientThrottleScopeTestCase(WgerTestCase):
+ """
+ Tests that ingredient viewsets are wired up with the right throttle scopes.
+
+ We don't exercise the rate limits themselves (the rates are config) — we
+ just assert that scopes are picked correctly per action so accidental
+ refactors can't silently strip throttling.
+ """
+
+ def test_ingredient_list_uses_list_scope(self):
+ view = IngredientViewSet()
+ view.action = 'list'
+ view.get_throttles()
+ self.assertEqual(view.throttle_scope, 'ingredient_list')
+
+ def test_ingredient_detail_uses_detail_scope(self):
+ view = IngredientViewSet()
+ view.action = 'retrieve'
+ view.get_throttles()
+ self.assertEqual(view.throttle_scope, 'ingredient_detail')
+
+ def test_ingredient_sync_uses_sync_scope(self):
+ self.assertEqual(IngredientSyncViewSet.throttle_scope, 'ingredient_sync')
+