diff mbox series

[layerindex-web,1/4] layerindex/querysethelper.py: reject an invalid API filter or orderby with a 400

Message ID 20261116230401.42917-2-tim.orling@konsulko.com
State New
Headers show
Series Return 400 or 404 instead of server errors for bad URLs | expand

Commit Message

Tim Orling Nov. 16, 2026, 11:03 p.m. UTC
An unknown field in "filter" or "orderby" raised BaseException, which
neither Django nor the WSGI server catches, so the worker died and the
client got a 502 (uWSGI) or 500. A filter value of the wrong type for
its field, e.g. filter=id:abc, raised ValueError and gave a 500. Raise
the REST framework's ParseError instead, which returns a 400 with the
reason.

[YOCTO #16517]

AI-Generated: Claude Opus 5.5
Signed-off-by: Tim Orling <tim.orling@konsulko.com>
---
 layerindex/querysethelper.py | 16 ++++++++++++----
 tests/test_restapi.py        | 32 ++++++++++++++++++++++++++++++++
 2 files changed, 44 insertions(+), 4 deletions(-)
diff mbox series

Patch

diff --git a/layerindex/querysethelper.py b/layerindex/querysethelper.py
index 0d1f317..2ca466a 100644
--- a/layerindex/querysethelper.py
+++ b/layerindex/querysethelper.py
@@ -8,7 +8,9 @@ 
 
 import operator
 import functools
+from django.core.exceptions import FieldError, ValidationError
 from django.db.models import Q, CharField
+from rest_framework.exceptions import ParseError
 
 def _verify_parameters(g, mandatory_parameters):
     miss = []
@@ -109,12 +111,14 @@  def _get_search_results(search_term, queryset, model):
 # it uses the request and the model to validate input for the filter and orderby values
 def get_search_tuple(request, model):
     ordering_string, invalid = _validate_input(request.GET.get('orderby', ''), model)
+    # A 400 for the client: BaseException isn't caught by Django or the WSGI
+    # server, so it killed the worker (AI-generated, Claude Opus 5.5)
     if invalid:
-        raise BaseException("Invalid ordering model:" + str(model) + str(invalid))
+        raise ParseError("Invalid orderby: " + str(invalid))
 
     filter_string, invalid = _validate_input(request.GET.get('filter', ''), model)
     if invalid:
-        raise BaseException("Invalid filter " + str(invalid))
+        raise ParseError("Invalid filter: " + str(invalid))
 
     search_term = request.GET.get('search', '')
     return (filter_string, search_term, ordering_string)
@@ -123,8 +127,12 @@  def get_search_tuple(request, model):
 # returns a lazy-evaluated queryset for a filter/search/order combination
 def params_to_queryset(model, queryset, filter_string, search_term, ordering_string):
     if filter_string:
-        filter_query = _get_filtering_query(filter_string)
-        queryset = queryset.filter(filter_query)
+        try:
+            filter_query = _get_filtering_query(filter_string)
+            queryset = queryset.filter(filter_query)
+        except (ValueError, ValidationError, FieldError) as e:
+            # e.g. filter=id:abc (AI-generated, Claude Opus 5.5)
+            raise ParseError("Invalid filter: " + str(e))
     else:
         queryset = queryset.all()
 
diff --git a/tests/test_restapi.py b/tests/test_restapi.py
index af1f708..a1f733e 100644
--- a/tests/test_restapi.py
+++ b/tests/test_restapi.py
@@ -28,3 +28,35 @@  class TestRestApiDatetimes(TestCase):
         items = data['results'] if isinstance(data, dict) else data
         item = next(i for i in items if i['name'] == 'meta-test')
         self.assertEqual(item['updated'], '2026-10-18T14:37:05+0000')
+
+
+@pytest.mark.django_db
+class TestRestApiInvalidParameters(TestCase):
+    """Invalid filter and orderby values give a 400 ([YOCTO #16517])"""
+
+    def assert_bad_request(self, params):
+        response = self.client.get('/layerindex/api/layerItems/', dict(params, format='json'))
+        self.assertEqual(response.status_code, 400, params)
+
+    def test_unknown_filter_field(self):
+        # Raised BaseException, which killed the worker
+        self.assert_bad_request({'filter': 'pn:x'})
+
+    def test_filter_without_value(self):
+        self.assert_bad_request({'filter': 'name'})
+
+    def test_filter_value_of_wrong_type(self):
+        # Raised ValueError: a 500
+        self.assert_bad_request({'filter': 'id:abc'})
+
+    def test_unknown_orderby_field(self):
+        self.assert_bad_request({'orderby': 'pn:-'})
+
+    def test_valid_filter(self):
+        LayerItem.objects.create(name='meta-test', status='P', layer_type='A',
+                                 summary='test', description='test',
+                                 vcs_url='git://example.com/meta-test.git')
+        response = self.client.get('/layerindex/api/layerItems/',
+                                   {'filter': 'name:meta-test', 'format': 'json'})
+        self.assertEqual(response.status_code, 200)
+        self.assertEqual([i['name'] for i in response.json()], ['meta-test'])