Skip to contentSkip to conversation

Return 400 or 404 instead of server errors for bad URLs

PATCH New Tim Orling 1 participant 5 messages Nov 16

lore
Share & tools
lore

Tim Orling

author
#0 lore raw

cover Return 400 or 404 instead of server errors for bad URLs

Fuzzing the URLs of a test instance loaded with a copy of the production database found about 160 requests per pass that gave a 500 and about 350 that gave a 502, from a handful of causes. These fix four of them.

1: Bug 16517: an unknown field in an API "filter" or "orderby" raised a
bare BaseException, which killed the worker; a value of the wrong type, such as filter=id:abc, raised ValueError. Both are now a 400. In Piotr Buliński's analysis of the production access logs from July to November, 909 of the 912 API server errors were malformed filters.
2: Bug 16518: the API never applied "orderby" at all.
3: Bug 16519: a non-numeric id in a URL, or in branch_comparison's
from_branch and to_branch, gave a 500; it is now a 404.
4: Bug 16520: a NUL character in the URL gave a 500 on PostgreSQL. It is
now a 400 on every database.

With these, the fuzz runs give no 500s on PostgreSQL and one on MariaDB, the 4-byte emoji case of bug 16507, which these don't address. The 502s that remain are 5000-character URLs, which uWSGI rejects with its default 4 KB buffer; gunicorn returns a 400 for them.

Each fix comes with tests that fail without it. This applies on master-next, where "layerindex: add an RSS feed of recently published layers" changed the neighbouring line of layerindex/urls.py.

Tim Orling (4):
layerindex/querysethelper.py: reject an invalid API filter or orderby

    with a 400

layerindex/querysethelper.py: apply the API "orderby" parameter
layerindex: give a 404 for a non-numeric id in a URL layerindex/middleware.py: reject NUL characters in the URL with a 400

 docker/settings.py            |  1 +
 layerindex/middleware.py      | 21 +++++++++++-
 layerindex/querysethelper.py  | 41 +++++++++++++++++++----
 layerindex/urls.py            | 18 +++++-----
 layerindex/views.py           | 32 +++++++++---------
 settings.py                   |  1 +
 tests/test_nonnumeric_ids.py  | 51 ++++++++++++++++++++++++++++
 tests/test_null_characters.py | 45 +++++++++++++++++++++++++
 tests/test_restapi.py         | 62 +++++++++++++++++++++++++++++++++++
 9 files changed, 240 insertions(+), 32 deletions(-)
 create mode 100644 tests/test_nonnumeric_ids.py
 create mode 100644 tests/test_null_characters.py
Signature · 1 line
2.56.1
author
#1 lore raw

PATCH 1/4 layerindex/querysethelper.py: reject an invalid API filter or orderby with a 400

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

---
 layerindex/querysethelper.py | 16 ++++++++++++----
 tests/test_restapi.py        | 32 ++++++++++++++++++++++++++++++++
 2 files changed, 44 insertions(+), 4 deletions(-)
layerindex/querysethelper.py +12 -4
index 0d1f317..2ca466a 100644
@@ -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()
 
tests/test_restapi.py +32 -0
index af1f708..a1f733e 100644
@@ -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')
+
+
[email protected]_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'])
Signature · 1 line
2.56.1
author
#2 lore raw

PATCH 2/4 layerindex/querysethelper.py: apply the API "orderby" parameter

In reply to Tim Orling

params_to_queryset() worked out the column and direction from "orderby" but never ordered the queryset by them, so the parameter had no effect. Order by it, with a 400 for a field path that doesn't exist. It no longer evaluates the whole queryset just to check whether it is empty first.

[YOCTO #16518]

AI-Generated: Claude Opus 5.5

---
 layerindex/querysethelper.py | 27 +++++++++++++++++++++++----
 tests/test_restapi.py        | 30 ++++++++++++++++++++++++++++++
 2 files changed, 53 insertions(+), 4 deletions(-)
layerindex/querysethelper.py +23 -4
index 2ca466a..26f687a 100644
@@ -8,7 +8,7 @@
 
 import operator
 import functools
-from django.core.exceptions import FieldError, ValidationError
+from django.core.exceptions import FieldDoesNotExist, FieldError, ValidationError
 from django.db.models import Q, CharField
 from rest_framework.exceptions import ParseError
 
@@ -124,6 +124,18 @@ def get_search_tuple(request, model):
     return (filter_string, search_term, ordering_string)
 
 
+def _check_field_path(model, path):
+    """Raise ParseError unless path (e.g. "layerbranch__layer__name") names a field"""
+    for name in path.split('__'):
+        if model is None:
+            raise ParseError("Invalid orderby: " + path)
+        try:
+            field = model._meta.get_field(name)
+        except FieldDoesNotExist:
+            raise ParseError("Invalid orderby: " + path)
+        model = field.related_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:
@@ -139,12 +151,19 @@ def params_to_queryset(model, queryset, filter_string, search_term, ordering_str
     if search_term:
         queryset = _get_search_results(search_term, queryset, model)
 
-    if ordering_string and queryset:
+    # insure only distinct records (e.g. from multiple search hits) are returned
+    queryset = queryset.distinct()
+
+    if ordering_string:
         column, order = ordering_string.split(':')
         if order.lower() == DESCENDING:
             column = '-' + column
+        # The ordering was worked out but never applied. A bad field path
+        # only fails when the query runs, so check it here (AI-generated,
+        # Claude Opus 5.5)
+        _check_field_path(model, column.lstrip('-'))
+        queryset = queryset.order_by(column)
 
-    # insure only distinct records (e.g. from multiple search hits) are returned
-    return queryset.distinct()
+    return queryset
 
 
tests/test_restapi.py +30 -0
index a1f733e..fde1aec 100644
@@ -60,3 +60,33 @@ class TestRestApiInvalidParameters(TestCase):
                                    {'filter': 'name:meta-test', 'format': 'json'})
         self.assertEqual(response.status_code, 200)
         self.assertEqual([i['name'] for i in response.json()], ['meta-test'])
+
+
[email protected]_db
+class TestRestApiOrderby(TestCase):
+    """orderby sorts the results ([YOCTO #16518])"""
+
+    def setUp(self):
+        for name in ('meta-b', 'meta-a', 'meta-c'):
+            LayerItem.objects.create(name=name, status='P', layer_type='A',
+                                     summary='test', description='test',
+                                     vcs_url='git://example.com/%s.git' % name)
+
+    def names(self, orderby):
+        response = self.client.get('/layerindex/api/layerItems/',
+                                   {'orderby': orderby, 'format': 'json'})
+        self.assertEqual(response.status_code, 200)
+        return [i['name'] for i in response.json()]
+
+    def test_ascending(self):
+        self.assertEqual(self.names('name:+'), ['meta-a', 'meta-b', 'meta-c'])
+
+    def test_descending(self):
+        # DESCENDING in querysethelper.py
+        self.assertEqual(self.names('name:-'), ['meta-c', 'meta-b', 'meta-a'])
+
+    def test_unknown_related_field(self):
+        # "layerbranch" passes the field-name check; the rest of the path is wrong
+        response = self.client.get('/layerindex/api/layerItems/',
+                                   {'orderby': 'layerbranch__nosuchfield:+', 'format': 'json'})
+        self.assertEqual(response.status_code, 400)
Signature · 1 line
2.56.1
author
#3 lore raw

PATCH 3/4 layerindex: give a 404 for a non-numeric id in a URL

In reply to Tim Orling

The URL patterns captured primary keys with [-\w]+, and BranchCompareView passed the from_branch and to_branch parameters straight to the id lookup, so a value such as /layerindex/recipe/NaN/ or from_branch= raised ValueError and gave a 500. Match only digits in the URLs and check the branch parameters, so these are a 404.

[YOCTO #16519]

AI-Generated: Claude Opus 5.5

---
 layerindex/urls.py           | 18 ++++++-------
 layerindex/views.py          | 32 +++++++++++-----------
 tests/test_nonnumeric_ids.py | 51 ++++++++++++++++++++++++++++++++++++
 3 files changed, 77 insertions(+), 24 deletions(-)
 create mode 100644 tests/test_nonnumeric_ids.py
layerindex/urls.py +9 -9
index 32e51d9..9910eee 100644
@@ -72,19 +72,19 @@ urlpatterns = [
         name='layer_review'),
     re_path(r'^layer/(?P<slug>[-\.\w]+)/addnote/$',
         edit_layernote_view, {'template_name': 'layerindex/editlayernote.html'}, name="add_layernote"),
-    re_path(r'^layer/(?P<slug>[-\.\w]+)/editnote/(?P<pk>[-\w]+)/$',
+    re_path(r'^layer/(?P<slug>[-\.\w]+)/editnote/(?P<pk>\d+)/$',
         edit_layernote_view, {'template_name': 'layerindex/editlayernote.html'}, name="edit_layernote"),
-    re_path(r'^layer/(?P<slug>[-\.\w]+)/deletenote/(?P<pk>[-\w]+)/$',
+    re_path(r'^layer/(?P<slug>[-\.\w]+)/deletenote/(?P<pk>\d+)/$',
         delete_layernote_view, {'template_name': 'layerindex/deleteconfirm.html'}, name="delete_layernote"),
     re_path(r'^layer/(?P<slug>[-\.\w]+)/delete/$',
         delete_layer_view, {'template_name': 'layerindex/deleteconfirm.html'}, name="delete_layer"),
-    re_path(r'^recipe/(?P<pk>[-\w]+)/$',
+    re_path(r'^recipe/(?P<pk>\d+)/$',
         RecipeDetailView.as_view(
             template_name='layerindex/recipedetail.html'),
         name='recipe'),
     re_path(r'^layer/(?P<name>[-\.\w]+)/publish/$', publish_view, name="publish"),
     re_path(r'^layers/published/rss/$', PublishedLayersFeed(), name='published_layers_feed'),
-    re_path(r'^layerupdate/(?P<pk>[-\w]+)/$',
+    re_path(r'^layerupdate/(?P<pk>\d+)/$',
         LayerUpdateDetailView.as_view(
             template_name='layerindex/layerupdate.html'),
         name='layerupdate'),
@@ -114,7 +114,7 @@ urlpatterns = [
         UpdateListView.as_view(
             template_name='layerindex/updatelist.html'),
         name='update_list'),
-    re_path(r'^updates/(?P<pk>[-\w]+)/$',
+    re_path(r'^updates/(?P<pk>\d+)/$',
         UpdateDetailView.as_view(
             template_name='layerindex/updatedetail.html'),
         name='update'),
@@ -143,7 +143,7 @@ urlpatterns = [
     re_path(r'^oe-classic/stats/$',
         RedirectView.as_view(url=reverse_lazy('comparison_recipe_stats', kwargs={'branch': 'oe-classic'}), permanent=False),
         name='classic_recipe_stats'),
-    re_path(r'^oe-classic/recipe/(?P<pk>[-\w]+)/$',
+    re_path(r'^oe-classic/recipe/(?P<pk>\d+)/$',
         ClassicRecipeDetailView.as_view(
             template_name='layerindex/classicrecipedetail.html'),
         name='classic_recipe'),
@@ -161,15 +161,15 @@ urlpatterns = [
         ClassicRecipeStatsView.as_view(
             template_name='layerindex/classicstats.html'),
         name='comparison_recipe_stats'),
-    re_path(r'^comparison/recipe/(?P<pk>[-\w]+)/$',
+    re_path(r'^comparison/recipe/(?P<pk>\d+)/$',
         ClassicRecipeDetailView.as_view(
             template_name='layerindex/classicrecipedetail.html'),
         name='comparison_recipe'),
-    re_path(r'^comparison/select/(?P<pk>[-\w]+)/$',
+    re_path(r'^comparison/select/(?P<pk>\d+)/$',
         ComparisonRecipeSelectView.as_view(
             template_name='layerindex/comparisonrecipeselect.html'),
         name='comparison_select'),
-    re_path(r'^comparison/selectdetail/(?P<selectfor>[-\w]+)/(?P<pk>[-\w]+)/$',
+    re_path(r'^comparison/selectdetail/(?P<selectfor>[-\w]+)/(?P<pk>\d+)/$',
         ComparisonRecipeSelectDetailView.as_view(
             template_name='layerindex/comparisonrecipeselectdetail.html'),
         name='comparison_select_detail'),
layerindex/views.py +17 -15
index 92da12b..d503a94 100644
@@ -1979,33 +1979,35 @@ class BranchCompareView(FormView):
                     layer_ids.append(int(layer_id))
         return layer_ids
 
+    def get_branch(self, param):
+        # A non-numeric id is a 404, not a ValueError (AI-generated, Claude Opus 5.5)
+        branch_id = self.request.GET.get(param, None)
+        if branch_id is None:
+            return None
+        if not (branch_id.isascii() and branch_id.isdigit()):
+            raise Http404
+        return get_object_or_404(Branch, id=branch_id)
+
     def form_valid(self, form):
         return HttpResponseRedirect(reverse_lazy('branch_comparison', args=(form.cleaned_data['from_branch'].name, form.cleaned_data['to_branch'].name)))
 
     def get_initial(self):
         initial = super(BranchCompareView, self).get_initial()
-        from_branch_id = self.request.GET.get('from_branch', None)
-        if from_branch_id is not None:
-            initial['from_branch'] = get_object_or_404(Branch, id=from_branch_id)
-        to_branch_id = self.request.GET.get('to_branch', None)
-        if to_branch_id is not None:
-            initial['to_branch'] = get_object_or_404(Branch, id=to_branch_id)
+        from_branch = self.get_branch('from_branch')
+        if from_branch is not None:
+            initial['from_branch'] = from_branch
+        to_branch = self.get_branch('to_branch')
+        if to_branch is not None:
+            initial['to_branch'] = to_branch
         initial['layers'] = ','.join(str(i) for i in self.get_layer_ids())
         return initial
 
     def get_context_data(self, **kwargs):
         context = super(BranchCompareView, self).get_context_data(**kwargs)
-        from_branch_id = self.request.GET.get('from_branch', None)
-        to_branch_id = self.request.GET.get('to_branch', None)
-
         layer_ids = self.get_layer_ids()
-        from_branch = None
-        if from_branch_id is not None:
-            from_branch = get_object_or_404(Branch, id=from_branch_id)
+        from_branch = self.get_branch('from_branch')
         context['from_branch'] = from_branch
-        to_branch = None
-        if to_branch_id is not None:
-            to_branch = get_object_or_404(Branch, id=to_branch_id)
+        to_branch = self.get_branch('to_branch')
         context['to_branch'] = to_branch
         if from_branch and to_branch:
             context['added'], context['changed'], context['removed'] = self.get_recipes(from_branch, to_branch, layer_ids)
tests/test_nonnumeric_ids.py new file +51 -0

51 lines not on this page · raw message

Signature · 1 line
2.56.1
author
#4 lore raw

PATCH 4/4 layerindex/middleware.py: reject NUL characters in the URL with a 400

In reply to Tim Orling

PostgreSQL text can't hold a NUL character, so a search term, API filter or URL path containing one, e.g. ?q=%00, raised DataError and gave a 500. MariaDB just found nothing. Forms already reject NUL in what they clean, but many views read the URL directly, so reject it once in a middleware.

[YOCTO #16520]

AI-Generated: Claude Opus 5.5

---
 docker/settings.py            |  1 +
 layerindex/middleware.py      | 21 +++++++++++++++-
 settings.py                   |  1 +
 tests/test_null_characters.py | 45 +++++++++++++++++++++++++++++++++++
 4 files changed, 67 insertions(+), 1 deletion(-)
 create mode 100644 tests/test_null_characters.py
docker/settings.py +1 -0
index cd8bacb..0cfcd83 100644
@@ -96,6 +96,7 @@ SECRET_KEY = os.getenv('SECRET_KEY', '')
 
 MIDDLEWARE = (
     'corsheaders.middleware.CorsMiddleware',
+    'layerindex.middleware.RejectNullCharactersMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
layerindex/middleware.py +20 -1
index 6766b1d..1112448 100644
@@ -7,9 +7,28 @@
 # SPDX-License-Identifier: MIT
 
 from django.utils.deprecation import MiddlewareMixin
-from django.http import HttpResponseRedirect
+from django.http import HttpResponseBadRequest, HttpResponseRedirect
 from django.urls import reverse
 from reversion.middleware import RevisionMiddleware
 
 class NonAtomicRevisionMiddleware(RevisionMiddleware):
     atomic = False
+
+
+class RejectNullCharactersMiddleware:
+    """
+    Return a 400 for a request with a NUL character in its path or query
+    string. PostgreSQL text can't hold NUL, so any lookup with such a value
+    raised DataError and gave a 500. Forms already reject NUL in what they
+    clean; this covers the views that read the URL directly.
+    (AI-generated, Claude Opus 5.5)
+    """
+    def __init__(self, get_response):
+        self.get_response = get_response
+
+    def __call__(self, request):
+        if '\x00' in request.path or any(
+                '\x00' in key or any('\x00' in value for value in values)
+                for key, values in request.GET.lists()):
+            return HttpResponseBadRequest('NUL characters are not allowed')
+        return self.get_response(request)
settings.py +1 -0
index 495af1e..573311a 100644
@@ -96,6 +96,7 @@ SECRET_KEY = ''
 
 MIDDLEWARE = (
     'corsheaders.middleware.CorsMiddleware',
+    'layerindex.middleware.RejectNullCharactersMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
tests/test_null_characters.py new file +45 -0

45 lines not on this page · raw message

Signature · 1 line
2.56.1