From 8b05b8289b2da89582c8287ebf1851ab46b2719b Mon Sep 17 00:00:00 2001 From: Trenton H <797416+stumpylog@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:32:29 -0800 Subject: [PATCH] Fix: reject invalid filters before bulk selection, keep REST boolean and ISO datetime filters, bound datetime years to 2..9998 --- src/documents/filters.py | 14 +- .../tests/test_filter_input_bounds.py | 170 ++++++++++++++++++ src/documents/views.py | 16 +- 3 files changed, 192 insertions(+), 8 deletions(-) diff --git a/src/documents/filters.py b/src/documents/filters.py index e3568e11a..243849d02 100644 --- a/src/documents/filters.py +++ b/src/documents/filters.py @@ -33,14 +33,15 @@ from django.db.models.functions import NullIf from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django_filters import DateFilter -from django_filters.filterset import FILTER_FOR_DBFIELD_DEFAULTS +from django_filters.fields import IsoDateTimeField +from django_filters.filters import IsoDateTimeFilter from django_filters.rest_framework import BooleanFilter from django_filters.rest_framework import CharFilter -from django_filters.rest_framework import DateTimeFilter from django_filters.rest_framework import Filter from django_filters.rest_framework import FilterSet from django_filters.rest_framework import MultipleChoiceFilter from django_filters.rest_framework import NumberFilter +from django_filters.rest_framework.filterset import FILTER_FOR_DBFIELD_DEFAULTS from drf_spectacular.utils import extend_schema_field from guardian.utils import get_group_obj_perms_model from guardian.utils import get_user_obj_perms_model @@ -107,6 +108,9 @@ INT64_MAX = 2**63 - 1 # Real UTC offsets run from -12:00 to +14:00, databases reject anything much larger. MAX_UTC_OFFSET = timedelta(hours=14) DATE_PART_BOUNDS = {"year": (1, 9999), "month": (1, 12), "day": (1, 31)} +# A datetime year is turned into UTC boundaries in the active timezone, so the first +# and last year overflow for any timezone other than UTC +DATETIME_YEAR_BOUNDS = (2, 9998) def in_id_range(value: int) -> bool: @@ -128,7 +132,7 @@ class BoundedNumberFilter(NumberFilter): field_class = BoundedDecimalField -class BoundedDateTimeField(forms.DateTimeField): +class BoundedDateTimeField(IsoDateTimeField): def clean(self, value: Any) -> Any: value = super().clean(value) if value is not None and timezone.is_aware(value): @@ -148,7 +152,7 @@ class BoundedDateTimeField(forms.DateTimeField): return value -class BoundedDateTimeFilter(DateTimeFilter): +class BoundedDateTimeFilter(IsoDateTimeFilter): field_class = BoundedDateTimeField @@ -183,6 +187,8 @@ class BoundedFilterSet(FilterSet): # The lookup resolves to a plain integer field, so only here is it known to be # a year, month or day bounds = DATE_PART_BOUNDS.get(lookup_expr) + if lookup_expr == "year" and isinstance(field, models.DateTimeField): + bounds = DATETIME_YEAR_BOUNDS if bounds is not None and isinstance(filter_, NumberFilter): filter_.extra["min_value"], filter_.extra["max_value"] = bounds return filter_ diff --git a/src/documents/tests/test_filter_input_bounds.py b/src/documents/tests/test_filter_input_bounds.py index b36c56f1d..54d68376f 100644 --- a/src/documents/tests/test_filter_input_bounds.py +++ b/src/documents/tests/test_filter_input_bounds.py @@ -1,7 +1,12 @@ +from unittest import mock + import pytest from rest_framework import status from rest_framework.test import APIClient +from documents.models import Document +from documents.models import Tag +from paperless_testing.factories import CorrespondentFactory from paperless_testing.factories import DocumentFactory from paperless_testing.factories import TagFactory @@ -155,6 +160,171 @@ class TestFilterInputBounds: assert response.status_code == status.HTTP_200_OK +class TestDatetimeYearBounds: + @pytest.mark.parametrize("timezone_name", ["Europe/Berlin", "America/New_York"]) + @pytest.mark.parametrize("year", [1, 9999]) + def test_first_and_last_year_of_a_datetime_is_a_400( + self, + admin_client: APIClient, + settings, + timezone_name: str, + year: int, + ) -> None: + """ + GIVEN: + - A deployment in a timezone other than UTC + WHEN: + - A datetime field is filtered by the first or last year + THEN: + - The response is a 400, as the year boundary overflows when converted + to UTC + """ + settings.TIME_ZONE = timezone_name + + response = admin_client.get(f"/api/documents/?added__year={year}") + + assert response.status_code == status.HTTP_400_BAD_REQUEST + + @pytest.mark.parametrize("timezone_name", ["Europe/Berlin", "America/New_York"]) + @pytest.mark.parametrize( + ("field", "year"), + [("added", 2), ("added", 9998), ("created", 1), ("created", 9999)], + ) + def test_supported_years_succeed( + self, + admin_client: APIClient, + settings, + timezone_name: str, + field: str, + year: int, + ) -> None: + """ + GIVEN: + - A deployment in a timezone other than UTC + WHEN: + - A datetime field is filtered by a year inside the supported range, or + a date only field by any year + THEN: + - The request succeeds + """ + settings.TIME_ZONE = timezone_name + + response = admin_client.get(f"/api/documents/?{field}__year={year}") + + assert response.status_code == status.HTTP_200_OK + + +class TestFilterValueParsing: + @pytest.mark.parametrize("value", ["1", "0"]) + def test_isnull_accepts_numeric_booleans( + self, + admin_client: APIClient, + value: str, + ) -> None: + """ + GIVEN: + - A document with a correspondent and one without + WHEN: + - A generated isnull filter is given 1 or 0, as the UI sends + THEN: + - Only the matching document is returned + """ + with_correspondent = DocumentFactory.create( + correspondent=CorrespondentFactory.create(), + ) + without_correspondent = DocumentFactory.create() + + response = admin_client.get(f"/api/documents/?correspondent__isnull={value}") + + assert response.status_code == status.HTTP_200_OK + expected = without_correspondent if value == "1" else with_correspondent + assert [r["id"] for r in response.json()["results"]] == [expected.pk] + + def test_datetime_filter_rejects_locale_formats( + self, + admin_client: APIClient, + ) -> None: + """ + GIVEN: + - An authenticated client + WHEN: + - A datetime filter is given a day first or month first date + THEN: + - The response is a 400, only ISO 8601 is accepted + """ + response = admin_client.get("/api/documents/?added__gt=01/02/2024 10:00") + + assert response.status_code == status.HTTP_400_BAD_REQUEST + + +class TestBulkSelectionRejectsInvalidFilters: + @pytest.mark.parametrize( + "filters", + [{"id__in": str(HUGE)}, {"created__year": "abc"}], + ) + def test_documents_are_not_selected( + self, + admin_client: APIClient, + filters: dict[str, str], + ) -> None: + """ + GIVEN: + - Documents exist + WHEN: + - A bulk delete of all documents is requested with a filter that is invalid + THEN: + - The response is a 400 and nothing is queued + """ + DocumentFactory.create() + + with mock.patch("documents.views.execute_bulk_operation") as execute: + # A real id, so a request that is wrongly accepted fails the assertions + # below instead of failing to render a mock as JSON + execute.apply_async.return_value.id = "task-id" + response = admin_client.post( + "/api/documents/delete/", + {"all": True, "filters": filters}, + format="json", + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + execute.apply_async.assert_not_called() + assert Document.objects.count() == 1 + + @pytest.mark.parametrize( + "filters", + [{"id__in": str(HUGE)}, {"id": "abc"}], + ) + def test_objects_are_not_selected( + self, + admin_client: APIClient, + filters: dict[str, str], + ) -> None: + """ + GIVEN: + - Tags exist + WHEN: + - A bulk delete of all tags is requested with a filter that is invalid + THEN: + - The response is a 400 and no tag is deleted + """ + TagFactory.create() + + response = admin_client.post( + "/api/bulk_edit_objects/", + { + "object_type": "tags", + "operation": "delete", + "all": True, + "filters": filters, + }, + format="json", + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert Tag.objects.count() == 1 + + class TestSetPermissionsIdBounds: @pytest.mark.parametrize("grantee", ["users", "groups"]) @pytest.mark.parametrize("bad_id", [HUGE, -HUGE, "abc", None]) diff --git a/src/documents/views.py b/src/documents/views.py index 329c1f127..de162b36b 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -3073,11 +3073,15 @@ class DocumentSelectionMixin: root_document__isnull=True, ) # orm-filtered docs - filtered_documents = DocumentFilterSet( + # An invalid filter is dropped by .qs, which would select every document + filterset = DocumentFilterSet( data=orm_filters, queryset=permitted_documents, user=user, - ).qs.distinct() + ) + if not filterset.is_valid(): + raise ValidationError({"filters": filterset.errors}) + filtered_documents = filterset.qs.distinct() # tantivy-filtered docs (if search params provided) search_filtered_ids = self._get_search_document_ids( user=user, @@ -5338,10 +5342,14 @@ class BulkEditObjectsView(PassUserMixin): user_permitted_objects = object_class.objects.filter( id__in=permitted_object_ids(user, object_class, perm_codename), ) - objs = filterset_class( + # An invalid filter is dropped by .qs, which would select every object + filterset = filterset_class( data=filters, queryset=user_permitted_objects, - ).qs + ) + if not filterset.is_valid(): + raise ValidationError({"filters": filterset.errors}) + objs = filterset.qs if object_type == "tags": editable_ids = set(user_permitted_objects.values_list("pk", flat=True)) all_ids = set(objs.values_list("pk", flat=True))