Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Correctly handle malformed IDs

Roland Geiderdb427672391e
diff --git a/wger/nutrition/tests/test_meal.py b/wger/nutrition/tests/test_meal.py
index 5a8c354eb..300d8a04c 100644
--- a/wger/nutrition/tests/test_meal.py
+++ b/wger/nutrition/tests/test_meal.py
@@ -15,9 +15,14 @@
# Standard Library
import datetime
+import json
+
+# Django
+from django.urls import reverse
# wger
from wger.core.tests import api_base_test
+from wger.core.tests.base_testcase import WgerTestCase
from wger.nutrition.models import Meal
@@ -35,3 +40,19 @@ class MealApiTestCase(api_base_test.ApiBaseResourceTestCase):
'plan': '11111111-1111-1111-1111-000000000004',
'order': 1,
}
+
+
+class MealMalformedFkTestCase(WgerTestCase):
+ """
+ A malformed FK reference must not crash the ownership check.
+ """
+
+ def test_malformed_plan_reference_is_rejected_cleanly(self):
+ self.user_login('test')
+ response = self.client.post(
+ reverse('meal-list'),
+ data=json.dumps({'plan': '', 'time': '09:02'}),
+ content_type='application/json',
+ )
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('plan', response.json())
diff --git a/wger/utils/viewsets.py b/wger/utils/viewsets.py
index 25bb9c965..c5f43e01d 100644
--- a/wger/utils/viewsets.py
+++ b/wger/utils/viewsets.py
@@ -18,6 +18,9 @@
# Standard Library
import logging
+# Django
+from django.core.exceptions import ValidationError
+
# Third Party
from rest_framework import (
exceptions,
@@ -49,6 +52,11 @@ def check_fk_ownership(payload: dict, owner_objects: list[tuple], user_id: int)
except model_class.DoesNotExist:
logger.warning(f'{model_class.__name__} with pk {pk} not found during ownership check')
return False
+ except (ValidationError, ValueError, TypeError):
+ # The pk itself is malformed, so skip the ownership check here
+ # and let the serializer reject the field with a 400
+ logger.warning(f'{model_class.__name__} pk {pk!r} is malformed during ownership check')
+ continue
owner = obj.get_owner_object()
if owner and hasattr(owner, 'user') and owner.user_id != user_id: