Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add throttling for exercise creation
Roland Geider0ff2e5d9ea38
diff --git a/settings/settings_global.py b/settings/settings_global.pyindex e7f6dbc60..859e4193c 100644--- a/settings/settings_global.py+++ b/settings/settings_global.py@@ -406,12 +406,17 @@ REST_FRAMEWORK = {'login': '10/min','registration': '5/min',- # Ingredient endpoints — protect the multi-million-row table from+ # 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',++ # Exercise endpoints: Shared cap across all create endpoints (submission,+ # exercise, translation) to stop scripts from bulk-creating exercises. Only+ # POSTs are throttled, reads and edits are not (see CreateScopedRateThrottle).+ 'exercise_create': '20/hour',},'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',}diff --git a/wger/exercises/api/throttling.py b/wger/exercises/api/throttling.pynew file mode 100644index 000000000..b9059c12c--- /dev/null+++ b/wger/exercises/api/throttling.py@@ -0,0 +1,39 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++# Third Party+from rest_framework.throttling import ScopedRateThrottle+++class CreateScopedRateThrottle(ScopedRateThrottle):+ """+ Scoped rate throttle that only limits object creation (POST requests).++ Reads, edits and deletes pass through unthrottled, so browsing and editing+ stay fast. Used to cap how quickly new exercises and translations can be+ created through the API.++ Users with the ``exercises.add_exercise`` permission are exempt.+ """++ def allow_request(self, request, view):+ if request.method != 'POST':+ return True++ user = request.user+ if user.is_authenticated and user.has_perm('exercises.add_exercise'):+ return True++ return super().allow_request(request, view)diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.pyindex 0e16891e9..81fc4ad06 100644--- a/wger/exercises/api/views.py+++ b/wger/exercises/api/views.py@@ -24,7 +24,6 @@ from django.views.decorators.cache import cache_page# Third Partyfrom actstream import action as actstream_action-from drf_spectacular.utils import extend_schemafrom easy_thumbnails.alias import aliasesfrom easy_thumbnails.files import get_thumbnailerfrom rest_framework import viewsets@@ -36,6 +35,7 @@ from rest_framework.viewsets import ModelViewSet# wgerfrom wger.exercises.api.filtersets import ExerciseFilterSetfrom wger.exercises.api.permissions import CanContributeExercises+from wger.exercises.api.throttling import CreateScopedRateThrottlefrom wger.exercises.api.serializers import (DeletionLogSerializer,EquipmentSerializer,@@ -75,6 +75,8 @@ class ExerciseViewSet(ModelViewSet):queryset = Exercise.with_translations.all()serializer_class = ExerciseSerializerpermission_classes = (CanContributeExercises,)+ throttle_classes = (CreateScopedRateThrottle,)+ throttle_scope = 'exercise_create'ordering_fields = '__all__'filterset_fields = ('category',@@ -155,6 +157,8 @@ class ExerciseTranslationViewSet(ModelViewSet):queryset = Translation.objects.all()permission_classes = (CanContributeExercises,)+ throttle_classes = (CreateScopedRateThrottle,)+ throttle_scope = 'exercise_create'serializer_class = ExerciseTranslationSerializerordering_fields = '__all__'filterset_fields = (@@ -254,6 +258,8 @@ class ExerciseSubmissionViewSet(CreateAPIView):serializer_class = ExerciseSubmissionSerializerqueryset = Exercise.objects.all()permission_classes = (CanContributeExercises,)+ throttle_classes = (CreateScopedRateThrottle,)+ throttle_scope = 'exercise_create'class EquipmentViewSet(viewsets.ReadOnlyModelViewSet):diff --git a/wger/exercises/tests/api/test_create_throttle.py b/wger/exercises/tests/api/test_create_throttle.pynew file mode 100644index 000000000..b4edac8cb--- /dev/null+++ b/wger/exercises/tests/api/test_create_throttle.py@@ -0,0 +1,103 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++# Standard Library+from unittest import mock++# Django+from django.urls import reverse++# Third Party+from rest_framework import status+from rest_framework.settings import api_settings+from rest_framework.test import APIRequestFactory++# wger+from wger.core.tests.api_base_test import ApiBaseTestCase+from wger.core.tests.base_testcase import BaseTestCase+from wger.exercises.api.throttling import CreateScopedRateThrottle+from wger.exercises.api.views import (+ ExerciseSubmissionViewSet,+ ExerciseTranslationViewSet,+ ExerciseViewSet,+)+++class ExerciseCreateThrottleTestCase(BaseTestCase, ApiBaseTestCase):+ """+ Tests the write-only create throttle shared by the exercise create endpoints.+ """++ @staticmethod+ def get_payload():+ return {+ 'category': 3,+ 'license': 5,+ 'license_author': 'tester',+ 'translations': [+ {+ 'name': 'Throttle Test Exercise',+ 'description_source': (+ 'A sufficiently long English description so the language '+ 'detector recognises it and the minimum length passes.'+ ),+ 'language': 2,+ 'license_author': 'tester',+ },+ ],+ }++ def test_create_endpoints_use_throttle_scope(self):+ """All create endpoints share the throttle scope and class."""+ for view in (ExerciseViewSet, ExerciseTranslationViewSet, ExerciseSubmissionViewSet):+ self.assertEqual(view.throttle_scope, 'exercise_create')+ self.assertIn(CreateScopedRateThrottle, view.throttle_classes)++ def test_throttle_skips_non_post_requests(self):+ """Only POST is throttled; reads and edits always pass through."""+ throttle = CreateScopedRateThrottle()+ factory = APIRequestFactory()+ view = ExerciseViewSet()+ view.throttle_scope = 'exercise_create'++ for method in ('get', 'put', 'patch', 'delete', 'options', 'head'):+ request = getattr(factory, method)('/api/v2/exercise/')+ self.assertTrue(throttle.allow_request(request, view))++ def test_post_is_throttled(self):+ """A second create within the window is rejected with 429."""+ url = reverse('exercise-submission')+ # trainer1 is a trustworthy contributor without the add_exercise+ # permission, so the throttle applies to them.+ self.authenticate('trainer1')++ with mock.patch.dict(api_settings.DEFAULT_THROTTLE_RATES, {'exercise_create': '1/min'}):+ first = self.client.post(url, data=self.get_payload())+ second = self.client.post(url, data=self.get_payload())++ self.assertEqual(first.status_code, status.HTTP_201_CREATED)+ self.assertEqual(second.status_code, status.HTTP_429_TOO_MANY_REQUESTS)++ def test_add_exercise_permission_is_exempt(self):+ """Users with the add_exercise permission (admins/editors) aren't throttled."""+ url = reverse('exercise-submission')+ self.authenticate('admin')++ with mock.patch.dict(api_settings.DEFAULT_THROTTLE_RATES, {'exercise_create': '1/min'}):+ first = self.client.post(url, data=self.get_payload())+ second = self.client.post(url, data=self.get_payload())++ self.assertEqual(first.status_code, status.HTTP_201_CREATED)+ self.assertEqual(second.status_code, status.HTTP_201_CREATED)