Compare commits

...
3 changed files with 192 additions and 8 deletions

No files matched your search

+10 -4
View File
@@ -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_
@@ -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])
+12 -4
View File
@@ -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))