From e6b98b14b26e6ac5820ba759221a30972e91a66e Mon Sep 17 00:00:00 2001 From: mohamed ali Date: Thu, 8 Oct 2026 13:29:36 +0000 Subject: [PATCH] Return 404 for a cursor whose position is invalid for the ordering field CursorPagination.decode_cursor() validates the offset and reverse parts of a cursor but passes the position through, and paginate_queryset() filters on it directly. A client-supplied cursor such as base64('p=abc') on an integer or UUID ordering field therefore raised ValueError or django.core.exceptions.ValidationError from queryset.filter(), a 500. Treat it like any other malformed cursor and raise NotFound with the "Invalid cursor" message. --- rest_framework/pagination.py | 8 +++++++- tests/test_pagination.py | 10 ++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index 164d7c2f85..73bb0fdf1a 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -8,6 +8,7 @@ from collections import namedtuple from urllib import parse +from django.core.exceptions import ValidationError as DjangoValidationError from django.core.paginator import InvalidPage from django.core.paginator import Paginator as DjangoPaginator from django.template import loader @@ -576,7 +577,12 @@ def paginate_queryset(self, queryset, request, view=None): else: kwargs = {order_attr + '__gt': current_position} - queryset = queryset.filter(**kwargs) + try: + queryset = queryset.filter(**kwargs) + except (TypeError, ValueError, DjangoValidationError): + # The position in the cursor is not a valid value for the + # ordering field: the client sent a cursor we did not issue. + raise NotFound(self.invalid_cursor_message) # If we have an offset cursor then offset the entire page by that amount. # We also always fetch an extra item in order to determine if there is a diff --git a/tests/test_pagination.py b/tests/test_pagination.py index 8f772d8103..111718bbd9 100644 --- a/tests/test_pagination.py +++ b/tests/test_pagination.py @@ -1,3 +1,5 @@ +from base64 import b64encode + import pytest from django.core.paginator import Paginator as DjangoPaginator from django.db import models @@ -616,6 +618,14 @@ def test_invalid_cursor(self): with pytest.raises(exceptions.NotFound): self.pagination.paginate_queryset(self.queryset, request) + def test_invalid_cursor_position(self): + # A well-formed cursor whose position is not a valid value for the + # ordering field is a client error, not a server error. + cursor = b64encode(b'p=abc').decode('ascii') + request = Request(factory.get('/', {'cursor': cursor})) + with pytest.raises(exceptions.NotFound): + self.pagination.paginate_queryset(self.queryset, request) + def test_use_with_ordering_filter(self): class MockView: filter_backends = (filters.OrderingFilter,)