diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index 50c5255cea..847dd03037 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 6a71067ac3..ac871b7032 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,)