Compare commits

..
20 changed files with 266 additions and 2654 deletions

No files matched your search

+14 -51
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
@@ -66,7 +67,6 @@ from documents.versioning import annotate_effective_content
if TYPE_CHECKING:
from collections.abc import Callable
from collections.abc import Iterable
from datetime import datetime
CHAR_KWARGS = ["istartswith", "iendswith", "icontains", "iexact"]
@@ -105,28 +105,18 @@ logger = logging.getLogger("paperless.api")
# match a row, and handing it to the database raises an error on some backends.
INT64_MIN = -(2**63)
INT64_MAX = 2**63 - 1
# SmallIntegerField and IntegerField columns, the same size on every supported database
INT16_MIN = -(2**15)
INT16_MAX = 2**15 - 1
INT32_MIN = -(2**31)
INT32_MAX = 2**31 - 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:
return INT64_MIN <= value <= INT64_MAX
def in_range_ids(ids: Iterable[int]) -> list[int]:
"""
The ids a row could have. Any other id cannot match, and some databases raise an
error instead of finding nothing when asked for one.
"""
return [i for i in ids if in_id_range(i)]
class BoundedDecimalField(forms.DecimalField):
"""
django-filter only bounds numbers at 1e50, which is far past any integer column
@@ -142,14 +132,7 @@ class BoundedNumberFilter(NumberFilter):
field_class = BoundedDecimalField
class BoundedIntegerField(forms.IntegerField):
def __init__(self, **kwargs: Any) -> None:
kwargs.setdefault("min_value", INT64_MIN)
kwargs.setdefault("max_value", INT64_MAX)
super().__init__(**kwargs)
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):
@@ -169,7 +152,7 @@ class BoundedDateTimeField(forms.DateTimeField):
return value
class BoundedDateTimeFilter(DateTimeFilter):
class BoundedDateTimeFilter(IsoDateTimeFilter):
field_class = BoundedDateTimeField
@@ -204,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_
@@ -332,14 +317,8 @@ class EffectiveContentFilter(Filter):
)
@extend_schema_field(serializers.IntegerField)
@extend_schema_field(serializers.BooleanField)
class SharedByUser(Filter):
"""
Documents owned by the given user id that are shared with someone
"""
field_class = BoundedIntegerField
def filter(self, qs, value):
ctype = ContentType.objects.get_for_model(self.model)
UserObjectPermission = get_user_obj_perms_model()
@@ -408,25 +387,9 @@ class CustomFieldsFilter(Filter):
option_ids = []
if fields_with_matching_selects.count() > 0:
for field in fields_with_matching_selects:
# Extra data saved by older versions may not be an object
options = (
field.extra_data.get("select_options")
if isinstance(field.extra_data, dict)
else None
)
if not isinstance(options, list):
options = []
for option in options:
label = (
option.get("label") if isinstance(option, dict) else None
)
if (
isinstance(label, str)
and label.lower().find(
value.lower(),
)
!= -1
):
options = field.extra_data.get("select_options", [])
for _, option in enumerate(options):
if option.get("label").lower().find(value.lower()) != -1:
option_ids.extend([option.get("id")])
# A document with multiple custom field instances can match more
# than one of these OR-ed branches (or the same branch via
+44 -171
View File
@@ -52,10 +52,8 @@ if settings.AUDIT_LOG_ENABLED:
from documents import bulk_edit
from documents.data_models import DocumentSource
from documents.filters import INT32_MAX
from documents.filters import INT32_MIN
from documents.filters import CustomFieldQueryParser
from documents.filters import in_range_ids
from documents.filters import in_id_range
from documents.models import Correspondent
from documents.models import CustomField
from documents.models import CustomFieldInstance
@@ -233,7 +231,7 @@ class SetPermissionsMixin:
def _validate_user_ids(self, user_ids):
users = User.objects.none()
if user_ids is not None:
users = User.objects.filter(id__in=in_range_ids(user_ids))
users = User.objects.filter(id__in=[i for i in user_ids if in_id_range(i)])
if not users.count() == len(user_ids):
raise serializers.ValidationError(
"Some users in don't exist or were specified twice.",
@@ -243,7 +241,9 @@ class SetPermissionsMixin:
def _validate_group_ids(self, group_ids):
groups = Group.objects.none()
if group_ids is not None:
groups = Group.objects.filter(id__in=in_range_ids(group_ids))
groups = Group.objects.filter(
id__in=[i for i in group_ids if in_id_range(i)],
)
if not groups.count() == len(group_ids):
raise serializers.ValidationError(
"Some groups in don't exist or were specified twice.",
@@ -451,10 +451,6 @@ class OwnedObjectSerializer(
def validate_unique_together(self, validated_data, instance=None) -> None:
# workaround for https://github.com/encode/django-rest-framework/issues/9358
# An update that does not mention the owner keeps the current one, which
# still has to be unique with the new name
if instance is not None and "owner" not in validated_data:
validated_data = {**validated_data, "owner": instance.owner}
if "owner" in validated_data and "name" in self.Meta.fields:
name = validated_data.get("name", instance.name if instance else None)
objects = (
@@ -732,15 +728,6 @@ class CustomFieldSerializer(serializers.ModelSerializer[CustomField]):
]
def validate(self, attrs):
# Extra data is read as an object everywhere, any other JSON would be stored
# to fail on the next read
if attrs.get("extra_data") is not None and not isinstance(
attrs["extra_data"],
dict,
):
raise serializers.ValidationError(
{"extra_data": "Must be an object"},
)
# TODO: remove pending https://github.com/encode/django-rest-framework/issues/7173
name = attrs.get(
"name",
@@ -766,19 +753,14 @@ class CustomFieldSerializer(serializers.ModelSerializer[CustomField]):
self.instance
and self.instance.data_type == CustomField.FieldDataType.SELECT
):
select_options = (
attrs["extra_data"].get("select_options")
if isinstance(attrs.get("extra_data"), dict)
else None
)
if (
not isinstance(select_options, list)
or len(select_options) == 0
"extra_data" not in attrs
or "select_options" not in attrs["extra_data"]
or not isinstance(attrs["extra_data"]["select_options"], list)
or len(attrs["extra_data"]["select_options"]) == 0
or not all(
isinstance(option, dict)
and isinstance(option.get("label", ""), str)
and len(option.get("label", "")) > 0
for option in select_options
len(option.get("label", "")) > 0
for option in attrs["extra_data"]["select_options"]
)
):
raise serializers.ValidationError(
@@ -791,7 +773,7 @@ class CustomFieldSerializer(serializers.ModelSerializer[CustomField]):
elif (
"data_type" in attrs
and attrs["data_type"] == CustomField.FieldDataType.MONETARY
and isinstance(attrs.get("extra_data"), dict)
and "extra_data" in attrs
and "default_currency" in attrs["extra_data"]
and attrs["extra_data"]["default_currency"] is not None
and (
@@ -823,7 +805,7 @@ class ReadWriteSerializerMethodField(serializers.SerializerMethodField):
def validate_documentlink_targets(user, doc_ids):
if Document.objects.filter(id__in=in_range_ids(doc_ids)).count() != len(doc_ids):
if Document.objects.filter(id__in=doc_ids).count() != len(doc_ids):
raise serializers.ValidationError(
"Some documents in value don't exist or were specified twice.",
)
@@ -1490,29 +1472,12 @@ class SavedViewSerializer(OwnedObjectSerializer):
def validate(self, attrs):
attrs = super().validate(attrs)
# On a PATCH the nested rules are validated as partial, but a stored rule
# always needs its type
for rule in attrs.get("filter_rules") or []:
if "rule_type" not in rule:
raise serializers.ValidationError(
{"filter_rules": "Every rule needs a rule_type"},
)
if "display_fields" in attrs and attrs["display_fields"] is not None:
if not isinstance(attrs["display_fields"], list):
raise serializers.ValidationError(
{"display_fields": "Must be a list"},
)
for field in attrs["display_fields"]:
if not isinstance(field, str):
raise serializers.ValidationError(
f"Invalid field: {field}",
)
custom_field = re.fullmatch(
rf"{re.escape(SavedView.DisplayFields.CUSTOM_FIELD[:-2])}(\d+)",
field,
) # i.e. 'custom_field_' followed by an id
if custom_field:
field_id = int(custom_field[1])
if (
SavedView.DisplayFields.CUSTOM_FIELD[:-2] in field
): # i.e. check for 'custom_field_' prefix
field_id = int(re.search(r"\d+", field)[0])
if not CustomField.objects.filter(id=field_id).exists():
raise serializers.ValidationError(
f"Invalid field: {field}",
@@ -1591,9 +1556,7 @@ class DocumentListSerializer(serializers.Serializer[dict[str, list[int]]]):
raise serializers.ValidationError(f"{name} must be a list")
if not all(isinstance(i, int) for i in documents):
raise serializers.ValidationError(f"{name} must be a list of integers")
# An id beyond what a database column holds can't exist, and some backends raise
# an error instead of finding nothing
count = Document.objects.filter(id__in=in_range_ids(documents)).count()
count = Document.objects.filter(id__in=documents).count()
if not count == len(documents):
raise serializers.ValidationError(
f"Some documents in {name} don't exist or were specified twice.",
@@ -1766,10 +1729,6 @@ class EditPdfDocumentsSerializer(DocumentListSerializer, SourceModeValidationMix
raise serializers.ValidationError(
"Edit PDF method only supports one document",
)
if len(documents) == 0:
raise serializers.ValidationError(
"Edit PDF method requires a document",
)
operations = attrs["operations"]
@@ -1921,7 +1880,7 @@ class BulkEditSerializer(
raise serializers.ValidationError(f"{name} must be a list")
if not all(isinstance(i, int) for i in tags):
raise serializers.ValidationError(f"{name} must be a list of integers")
count = Tag.objects.filter(id__in=in_range_ids(tags)).count()
count = Tag.objects.filter(id__in=tags).count()
if not count == len(tags):
raise serializers.ValidationError(
f"Some tags in {name} don't exist or were specified twice.",
@@ -1947,7 +1906,7 @@ class BulkEditSerializer(
raise serializers.ValidationError(
f"{name} must be a list of integers or a dict of id:value pairs",
)
count = CustomField.objects.filter(id__in=in_range_ids(ids)).count()
count = CustomField.objects.filter(id__in=ids).count()
if not count == len(ids):
raise serializers.ValidationError(
f"Some custom fields in {name} don't exist or were specified twice.",
@@ -2313,20 +2272,12 @@ class BulkEditSerializer(
raise serializers.ValidationError(
"Split method only supports one document",
)
if len(attrs["documents"]) == 0:
raise serializers.ValidationError(
"Split method requires a document",
)
self._validate_parameters_split(parameters, attrs["documents"][0])
elif method == bulk_edit.delete_pages:
if len(attrs["documents"]) > 1:
raise serializers.ValidationError(
"Delete pages method only supports one document",
)
if len(attrs["documents"]) == 0:
raise serializers.ValidationError(
"Delete pages method requires a document",
)
self._validate_parameters_delete_pages(parameters)
elif method == bulk_edit.merge:
self._validate_parameters_merge(parameters)
@@ -2335,10 +2286,6 @@ class BulkEditSerializer(
raise serializers.ValidationError(
"Edit PDF method only supports one document",
)
if len(attrs["documents"]) == 0:
raise serializers.ValidationError(
"Edit PDF method requires a document",
)
self._validate_parameters_edit_pdf(parameters, attrs["documents"][0])
elif method == bulk_edit.remove_password:
self.validate_parameters_remove_password(parameters)
@@ -2509,9 +2456,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
"Custom fields must be a list of integers or an object mapping ids to values.",
),
)
if CustomField.objects.filter(id__in=in_range_ids(ids)).count() != len(
set(ids),
):
if CustomField.objects.filter(id__in=ids).count() != len(set(ids)):
raise serializers.ValidationError(
_("Some custom fields don't exist or were specified twice."),
)
@@ -2691,17 +2636,12 @@ class UiSettingsViewSerializer(serializers.ModelSerializer[UiSettings]):
]
def validate_settings(self, settings):
if settings is None:
return settings
if not isinstance(settings, dict):
raise serializers.ValidationError("Settings must be an object")
# we never save update checking backend setting
if "update_checking" in settings:
if not isinstance(settings["update_checking"], dict):
raise serializers.ValidationError(
{"update_checking": "Must be an object"},
)
settings["update_checking"].pop("backend_setting", None)
try:
settings["update_checking"].pop("backend_setting")
except KeyError:
pass
return settings
def create(self, validated_data):
@@ -2918,7 +2858,7 @@ class AcknowledgeTasksViewSerializer(serializers.Serializer[dict[str, Any]]):
if not all(isinstance(i, int) for i in tasks):
raise serializers.ValidationError(f"{name} must be a list of integers")
queryset = self.context.get("queryset", PaperlessTask.objects.all())
count = queryset.filter(id__in=in_range_ids(tasks)).count()
count = queryset.filter(id__in=tasks).count()
if not count == len(tasks):
raise serializers.ValidationError(
f"Some tasks in {name} don't exist or were specified twice.",
@@ -2961,8 +2901,6 @@ class ShareLinkSerializer(OwnedObjectSerializer):
"document_title",
"file_version",
)
# The model field is blank=True but not nullable, so it would be optional
extra_kwargs = {"document": {"required": True}}
def create(self, validated_data):
validated_data["slug"] = get_random_string(50)
@@ -3054,7 +2992,7 @@ class ShareLinkBundleSerializer(OwnedObjectSerializer):
share_link_bundle = super().create(validated_data)
documents = list(
Document.objects.filter(pk__in=in_range_ids(document_ids)).only(
Document.objects.filter(pk__in=document_ids).only(
"pk",
),
)
@@ -3160,7 +3098,7 @@ class BulkEditObjectsSerializer(SerializerWithPerms, SetPermissionsMixin):
if not all(isinstance(i, int) for i in objects):
raise serializers.ValidationError("objects must be a list of integers")
object_class = self.get_object_class(object_type)
count = object_class.objects.filter(id__in=in_range_ids(objects)).count()
count = object_class.objects.filter(id__in=objects).count()
if not count == len(objects):
raise serializers.ValidationError(
"Some ids in objects don't exist or were specified twice.",
@@ -3303,14 +3241,10 @@ class WorkflowTriggerSerializer(serializers.ModelSerializer[WorkflowTrigger]):
]
def create(self, validated_data):
# The id is only meaningful when this is nested in a workflow. On its own
# a client chosen id would collide with, or overwrite, another row
validated_data.pop("id", None)
WorkflowTriggerSerializer.normalize_workflow_trigger_sources(validated_data)
return super().create(validated_data)
def update(self, instance, validated_data):
validated_data.pop("id", None)
WorkflowTriggerSerializer.normalize_workflow_trigger_sources(validated_data)
return super().update(instance, validated_data)
@@ -3352,34 +3286,6 @@ class WorkflowActionWebhookSerializer(
]
def save_action_email_and_webhook(action, email_data, webhook_data) -> None:
"""
Store the nested email and webhook of a workflow action on the action's own rows.
An id in the payload is never used, it could name a row that belongs to another
action. An action with no row of that kind gets a new one. The data must already
be cleaned by the nested serializers, an unknown key would be a model error.
"""
created = False
for data, model, attribute in (
(email_data, WorkflowActionEmail, "email"),
(webhook_data, WorkflowActionWebhook, "webhook"),
):
if data is None:
continue
values = {key: value for key, value in data.items() if key != "id"}
existing = getattr(action, attribute)
if existing is not None:
# Change the loaded row, a response is built from it
for key, value in values.items():
setattr(existing, key, value)
existing.save()
else:
setattr(action, attribute, model.objects.create(**values))
created = True
if created:
action.save()
class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
id = serializers.IntegerField(required=False, allow_null=True)
assign_correspondent = CorrespondentField(allow_null=True, required=False)
@@ -3431,22 +3337,6 @@ class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
"ai_overwrite_existing",
]
def create(self, validated_data):
validated_data.pop("id", None)
email_data = validated_data.pop("email", None)
webhook_data = validated_data.pop("webhook", None)
instance = super().create(validated_data)
save_action_email_and_webhook(instance, email_data, webhook_data)
return instance
def update(self, instance, validated_data):
validated_data.pop("id", None)
email_data = validated_data.pop("email", None)
webhook_data = validated_data.pop("webhook", None)
instance = super().update(instance, validated_data)
save_action_email_and_webhook(instance, email_data, webhook_data)
return instance
def validate(self, attrs):
if "assign_title" in attrs and attrs["assign_title"] is not None:
if len(attrs["assign_title"]) == 0:
@@ -3461,10 +3351,6 @@ class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
)
if attrs.get("assign_custom_fields_values"):
if not isinstance(attrs["assign_custom_fields_values"], dict):
raise serializers.ValidationError(
{"assign_custom_fields_values": "Must be an object"},
)
# Empty strings treated as None to avoid unexpected behavior
attrs["assign_custom_fields_values"] = {
field_id: (None if value == "" else value)
@@ -3527,11 +3413,7 @@ class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
order = serializers.IntegerField(
required=False,
min_value=INT32_MIN,
max_value=INT32_MAX,
)
order = serializers.IntegerField(required=False)
triggers = WorkflowTriggerSerializer(many=True)
actions = WorkflowActionSerializer(many=True)
@@ -3617,10 +3499,6 @@ class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
) -> None:
set_triggers = []
set_actions = []
# Only rows already attached to this workflow may be updated by id, an id
# from anywhere else would take over or overwrite another workflow's row
own_trigger_ids = set(instance.triggers.values_list("pk", flat=True))
own_action_ids = set(instance.actions.values_list("pk", flat=True))
if triggers is not None and triggers is not serializers.empty:
for trigger in triggers:
@@ -3653,10 +3531,8 @@ class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
)
# Convert sources to strings to handle django-multiselectfield v1.0 changes
WorkflowTriggerSerializer.normalize_workflow_trigger_sources(trigger)
trigger_id = trigger.pop("id", None)
trigger_instance, _ = WorkflowTrigger.objects.update_or_create(
# A row that is not already part of this workflow is never reused
id=trigger_id if trigger_id in own_trigger_ids else None,
id=trigger.get("id"),
defaults=trigger,
)
if filter_has_tags is not None:
@@ -3714,24 +3590,30 @@ class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
email_data = action.pop("email", None)
webhook_data = action.pop("webhook", None)
action_id = action.pop("id", None)
action_instance, _ = WorkflowAction.objects.update_or_create(
# A row that is not already part of this workflow is never reused
id=action_id if action_id in own_action_ids else None,
id=action.get("id"),
defaults=action,
)
if email_data is not None:
serializer = WorkflowActionEmailSerializer(data=email_data)
serializer.is_valid(raise_exception=True)
email_data = serializer.validated_data
email, _ = WorkflowActionEmail.objects.update_or_create(
id=email_data.get("id"),
defaults=serializer.validated_data,
)
action_instance.email = email
action_instance.save()
if webhook_data is not None:
serializer = WorkflowActionWebhookSerializer(data=webhook_data)
serializer.is_valid(raise_exception=True)
webhook_data = serializer.validated_data
save_action_email_and_webhook(action_instance, email_data, webhook_data)
webhook, _ = WorkflowActionWebhook.objects.update_or_create(
id=webhook_data.get("id"),
defaults=serializer.validated_data,
)
action_instance.webhook = webhook
action_instance.save()
if assign_tags is not None:
action_instance.assign_tags.set(assign_tags)
@@ -3832,22 +3714,13 @@ class TrashSerializer(SerializerWithPerms):
)
def validate_documents(self, documents: list[int]) -> list[int]:
count = Document.deleted_objects.filter(
id__in=in_range_ids(documents),
).count()
count = Document.deleted_objects.filter(id__in=documents).count()
if not count == len(documents):
raise serializers.ValidationError(
"Some documents in the list have not yet been deleted.",
)
return documents
def validate(self, attrs):
if attrs.get("action") == "restore" and "documents" not in attrs:
raise serializers.ValidationError(
{"documents": "This field is required to restore documents."},
)
return attrs
class StoragePathTestSerializer(SerializerWithPerms):
path = serializers.CharField(
-14
View File
@@ -75,17 +75,3 @@ def searchable_document(_search_index: None) -> "Document":
def mock_zone_ocr_run(mocker: "MockerFixture") -> "MagicMock":
"""Patch the subprocess runner used by zone OCR (tesseract and pdftoppm)."""
return mocker.patch("documents.zone_ocr.subprocess.run")
@pytest.fixture
def config_id(db: None) -> int:
"""
The id of the application configuration row. A migration creates it, but a test
that flushes the database in the same worker removes it, so make sure it exists.
"""
from paperless.models import ApplicationConfiguration
config = ApplicationConfiguration.objects.first()
if config is None:
config = ApplicationConfiguration.objects.create()
return config.pk
@@ -1,114 +0,0 @@
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import CustomField
from paperless_testing.http import send_json
class TestCustomFieldExtraData:
@pytest.mark.parametrize("extra_data", [[1], "text", 5, True])
def test_extra_data_that_is_not_an_object_is_a_400(
self,
admin_client: APIClient,
extra_data: object,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A custom field is created with extra data that is not an object
THEN:
- The response is a 400
"""
response = send_json(
admin_client,
"POST",
"/api/custom_fields/",
{"name": "field", "data_type": "string", "extra_data": extra_data},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "extra_data" in response.data
@pytest.mark.parametrize("extra_data", [None, {}])
def test_null_or_empty_extra_data_is_accepted(
self,
admin_client: APIClient,
extra_data: object,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A string custom field has null or empty extra data
THEN:
- It is created
"""
response = send_json(
admin_client,
"POST",
"/api/custom_fields/",
{"name": "field", "data_type": "string", "extra_data": extra_data},
)
assert response.status_code == status.HTTP_201_CREATED
@pytest.mark.parametrize(
("extra_data", "term"),
[
pytest.param([1], "1", id="list"),
pytest.param(
{"select_options": [1, "x"]},
"select",
id="options-not-objects",
),
pytest.param(
{"select_options": None, "note": "zzz"},
"zzz",
id="options-null",
),
pytest.param(
{"select_options": 5, "note": "zzz"},
"zzz",
id="options-a-number",
),
pytest.param(
{"select_options": [{"label": None, "id": "zzz"}]},
"zzz",
id="label-missing",
),
pytest.param(
{"select_options": [{"label": 5, "id": "zzz"}]},
"zzz",
id="label-not-a-string",
),
],
)
def test_the_deprecated_custom_fields_filter_survives_odd_stored_data(
self,
admin_client: APIClient,
db: None,
extra_data: object,
term: str,
) -> None:
"""
GIVEN:
- A custom field whose stored extra data an older version allowed
WHEN:
- Documents are filtered with the deprecated custom_fields__icontains
THEN:
- The request succeeds
"""
CustomField.objects.create(
name="legacy",
data_type=CustomField.FieldDataType.SELECT,
extra_data=extra_data,
)
response = admin_client.get(
"/api/documents/",
{"custom_fields__icontains": term},
)
assert response.status_code == status.HTTP_200_OK
@@ -1,741 +0,0 @@
import pytest
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import UiSettings
from documents.models import WorkflowAction
from documents.models import WorkflowActionEmail
from paperless_testing.http import send_json
EMAIL = {
"subject": "Subject",
"body": "Body",
"to": "someone@example.com",
"include_document": False,
}
class TestObjectJsonBody:
@pytest.mark.parametrize("body", [[], [1, 2], True, 1, 1.5, None, "text"])
@pytest.mark.parametrize(
("method", "path"),
[
pytest.param("PATCH", "/api/workflow_triggers/1/", id="trigger-patch"),
pytest.param("PATCH", "/api/workflow_actions/1/", id="action-patch"),
pytest.param("POST", "/api/documents/bulk_edit/", id="bulk-edit"),
pytest.param(
"POST",
"/api/processed_mail/bulk_delete/",
id="processed-mail-bulk-delete",
),
pytest.param("POST", "/api/tags/", id="tags-create"),
],
)
def test_body_that_is_not_an_object_is_a_400(
self,
admin_client: APIClient,
method: str,
path: str,
body: object,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A JSON body that is a list or a scalar is sent
THEN:
- The response is a 400, never a server error
"""
response = send_json(admin_client, method, path, body)
assert response.status_code == status.HTTP_400_BAD_REQUEST
class TestNullAndWrongTypeFields:
@pytest.mark.parametrize("password", [["x"], 5, {"a": 1}, True])
def test_password_that_is_not_a_string_is_a_400(
self,
admin_client: APIClient,
admin_user: User,
password: object,
) -> None:
"""
GIVEN:
- A user
WHEN:
- The password is sent as something other than a string
THEN:
- The response is a 400
"""
response = send_json(
admin_client,
"PATCH",
f"/api/users/{admin_user.pk}/",
{"password": password},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "password" in response.data
@pytest.mark.parametrize("ui_settings", [None, {}])
def test_ui_settings_that_are_null_or_empty_are_accepted_and_readable(
self,
admin_client: APIClient,
ui_settings: object,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- UI settings are saved as null or with an unexpected update_checking
THEN:
- The request does not fail with a server error
"""
response = send_json(
admin_client,
"POST",
"/api/ui_settings/",
{"settings": ui_settings},
)
assert response.status_code == status.HTTP_200_OK
# What was saved must also be readable, null used to break the GET afterwards
assert admin_client.get("/api/ui_settings/").status_code == status.HTTP_200_OK
@pytest.mark.parametrize(
"ui_settings",
[[1], "text", 5, {"update_checking": [1]}, {"update_checking": "x"}],
)
def test_ui_settings_of_the_wrong_shape_are_a_400(
self,
admin_client: APIClient,
ui_settings: object,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- UI settings are saved that are not an object, or have a mistyped
update_checking
THEN:
- The response is a 400, not stored to break the next read
"""
response = send_json(
admin_client,
"POST",
"/api/ui_settings/",
{"settings": ui_settings},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@pytest.mark.parametrize(
"stored",
[None, [1], "text", {"update_checking": "x"}, {"update_checking": [1]}],
)
def test_reading_ui_settings_saved_in_an_unexpected_shape_still_works(
self,
admin_client: APIClient,
admin_user: User,
stored: object,
) -> None:
"""
GIVEN:
- UI settings stored in a shape the API no longer accepts, as older
versions allowed it
WHEN:
- The settings are read
THEN:
- The request succeeds
"""
UiSettings.objects.update_or_create(
user=admin_user,
defaults={"settings": stored},
)
response = admin_client.get("/api/ui_settings/")
assert response.status_code == status.HTTP_200_OK
@pytest.mark.parametrize(
"field",
["llm_api_key", "llm_embedding_api_key", "remote_ocr_api_key"],
)
@pytest.mark.parametrize("value", [5, ["a"], {"a": 1}, True])
def test_config_api_key_that_is_not_a_string_is_a_400(
self,
admin_client: APIClient,
config_id: int,
field: str,
value: object,
) -> None:
"""
GIVEN:
- The application configuration
WHEN:
- An obfuscated key field is sent as something other than a string
THEN:
- The response is a 400, not a server error
"""
response = send_json(
admin_client,
"PATCH",
f"/api/config/{config_id}/",
{field: value},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert field in response.data
@pytest.mark.parametrize(
"display_fields",
[["custom_field_abc"], ["custom_field_"], ["xcustom_field_1"]],
)
def test_saved_view_custom_field_name_must_be_well_formed(
self,
admin_client: APIClient,
display_fields: list,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A saved view lists a custom field display name without a numeric id
THEN:
- The response is a 400
"""
response = send_json(
admin_client,
"POST",
"/api/saved_views/",
{
"name": "view",
"show_on_dashboard": False,
"show_in_sidebar": False,
"sort_field": "created",
"filter_rules": [],
"display_fields": display_fields,
},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@pytest.mark.parametrize("display_fields", [5, True, {"a": 1}, "text"])
def test_saved_view_display_fields_must_be_a_list(
self,
admin_client: APIClient,
display_fields: object,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A saved view is created with display fields that are not a list
THEN:
- The response is a 400
"""
response = send_json(
admin_client,
"POST",
"/api/saved_views/",
{
"name": "view",
"show_on_dashboard": False,
"show_in_sidebar": False,
"sort_field": "created",
"filter_rules": [],
"display_fields": display_fields,
},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@pytest.mark.parametrize("display_fields", [[None], [5], [["x"]]])
def test_saved_view_display_field_that_is_not_a_string_is_a_400(
self,
admin_client: APIClient,
display_fields: list,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A saved view is created with display fields that are not strings
THEN:
- The response is a 400
"""
response = send_json(
admin_client,
"POST",
"/api/saved_views/",
{
"name": "view",
"show_on_dashboard": False,
"show_in_sidebar": False,
"sort_field": "created",
"filter_rules": [],
"display_fields": display_fields,
},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@pytest.mark.parametrize(
"extra_data",
[None, {}, {"select_options": None}, {"select_options": [1, 2]}, [1]],
)
def test_select_custom_field_without_valid_options_is_a_400(
self,
admin_client: APIClient,
extra_data: object,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A select custom field is created without usable options
THEN:
- The response is a 400
"""
response = send_json(
admin_client,
"POST",
"/api/custom_fields/",
{"name": "select", "data_type": "select", "extra_data": extra_data},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
def test_monetary_custom_field_with_null_extra_data_is_accepted(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A monetary custom field is created with null extra data
THEN:
- It is created
"""
response = send_json(
admin_client,
"POST",
"/api/custom_fields/",
{"name": "money", "data_type": "monetary", "extra_data": None},
)
assert response.status_code == status.HTTP_201_CREATED
@pytest.mark.parametrize("values", [[1], "text", 5])
def test_workflow_custom_field_values_must_be_an_object(
self,
admin_client: APIClient,
values: object,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A workflow action carries custom field values that are not an object
THEN:
- The response is a 400
"""
response = send_json(
admin_client,
"POST",
"/api/workflows/",
{
"name": "workflow",
"order": 0,
"enabled": True,
"triggers": [{"type": 2, "sources": [1], "matching_algorithm": 0}],
"actions": [{"type": 1, "assign_custom_fields_values": values}],
},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
class TestRequiredFields:
def test_share_link_requires_a_document(self, admin_client: APIClient) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A share link is created without a document
THEN:
- The response is a 400
"""
response = send_json(admin_client, "POST", "/api/share_links/", {})
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "document" in response.data
def test_restoring_from_the_trash_requires_documents(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- The trash is asked to restore without saying which documents
THEN:
- The response is a 400
"""
response = send_json(admin_client, "POST", "/api/trash/", {"action": "restore"})
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "documents" in response.data
@pytest.mark.parametrize("action", ["restore", "empty"])
def test_trash_document_id_beyond_the_database_range_is_a_400(
self,
admin_client: APIClient,
action: str,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- The trash is given a document id no row can have
THEN:
- The response is a 400, as for any document that is not in the trash
"""
response = send_json(
admin_client,
"POST",
"/api/trash/",
{"action": action, "documents": [2**70]},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@pytest.mark.parametrize("method", ["split", "delete_pages", "edit_pdf"])
def test_single_document_bulk_methods_reject_an_empty_selection(
self,
admin_client: APIClient,
method: str,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A method that works on exactly one document gets none
THEN:
- The response is a 400
"""
response = send_json(
admin_client,
"POST",
"/api/documents/bulk_edit/",
{
"documents": [],
"method": method,
"parameters": {
"pages": "1",
"operations": [{"page": 1}],
"split_pages": [[1]],
},
},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
def test_edit_pdf_endpoint_rejects_an_empty_selection(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- The edit_pdf endpoint gets no documents
THEN:
- The response is a 400
"""
response = send_json(
admin_client,
"POST",
"/api/documents/edit_pdf/",
{"documents": [], "operations": [{"page": 1}]},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
class TestSharedByFilter:
@pytest.mark.parametrize("value", ["false", "abc", "1.5", str(2**63)])
def test_non_integer_user_id_is_a_400(
self,
admin_client: APIClient,
value: str,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- shared_by__id is not an integer user id
THEN:
- The response is a 400
"""
response = admin_client.get("/api/documents/", {"shared_by__id": value})
assert response.status_code == status.HTTP_400_BAD_REQUEST
@pytest.mark.parametrize("value", ["", "1"])
def test_empty_or_valid_user_id_works(
self,
admin_client: APIClient,
value: str,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- shared_by__id is empty or a user id
THEN:
- The request succeeds
"""
response = admin_client.get("/api/documents/", {"shared_by__id": value})
assert response.status_code == status.HTTP_200_OK
class TestStandaloneWorkflowActions:
def test_create_with_nested_email(self, admin_client: APIClient) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- An email action is created through the standalone endpoint
THEN:
- The action and its email are both stored
"""
response = send_json(
admin_client,
"POST",
"/api/workflow_actions/",
{"type": WorkflowAction.WorkflowActionType.EMAIL, "email": EMAIL},
)
assert response.status_code == status.HTTP_201_CREATED
action = WorkflowAction.objects.get(pk=response.data["id"])
assert action.email is not None
assert action.email.subject == "Subject"
def test_update_changes_the_existing_email_row(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An email action
WHEN:
- Its email is changed through the standalone endpoint
THEN:
- The existing email row is updated, no new row is made
"""
created = send_json(
admin_client,
"POST",
"/api/workflow_actions/",
{"type": WorkflowAction.WorkflowActionType.EMAIL, "email": EMAIL},
)
action = WorkflowAction.objects.get(pk=created.data["id"])
email_id = action.email_id
response = send_json(
admin_client,
"PATCH",
f"/api/workflow_actions/{action.pk}/",
{"email": {**EMAIL, "subject": "Changed"}},
)
assert response.status_code == status.HTTP_200_OK
# The response must show the saved value, not the row loaded before the update
assert response.data["email"]["subject"] == "Changed"
action.refresh_from_db()
assert action.email_id == email_id
assert WorkflowActionEmail.objects.get(pk=email_id).subject == "Changed"
assert WorkflowActionEmail.objects.count() == 1
def test_null_email_leaves_the_existing_email_alone(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An email action
WHEN:
- It is patched with a null email
THEN:
- The email is kept, null is a no-op as in the nested workflow serializer
"""
created = send_json(
admin_client,
"POST",
"/api/workflow_actions/",
{"type": WorkflowAction.WorkflowActionType.EMAIL, "email": EMAIL},
)
action = WorkflowAction.objects.get(pk=created.data["id"])
response = send_json(
admin_client,
"PATCH",
f"/api/workflow_actions/{action.pk}/",
{"email": None},
)
assert response.status_code == status.HTTP_200_OK
action.refresh_from_db()
assert action.email is not None
assert action.email.subject == "Subject"
def test_an_id_in_the_payload_cannot_reach_another_actions_email(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An email action
WHEN:
- A second action is created with the first action's email id in its payload
THEN:
- The first email is untouched and the second action gets its own row
"""
first = send_json(
admin_client,
"POST",
"/api/workflow_actions/",
{"type": WorkflowAction.WorkflowActionType.EMAIL, "email": EMAIL},
)
first_email = WorkflowAction.objects.get(pk=first.data["id"]).email
second = send_json(
admin_client,
"POST",
"/api/workflow_actions/",
{
"type": WorkflowAction.WorkflowActionType.EMAIL,
"email": {**EMAIL, "id": first_email.pk, "subject": "Hijacked"},
},
)
assert second.status_code == status.HTTP_201_CREATED
first_email.refresh_from_db()
assert first_email.subject == "Subject"
assert WorkflowAction.objects.get(pk=second.data["id"]).email_id != (
first_email.pk
)
BEYOND_THE_DATABASE = 2**70
class TestIdListsBeyondTheDatabaseRange:
@pytest.mark.parametrize(
("path", "body"),
[
pytest.param(
"/api/documents/bulk_edit/",
{"documents": [BEYOND_THE_DATABASE], "method": "delete"},
id="bulk-edit-documents",
),
pytest.param(
"/api/documents/bulk_edit/",
{
"documents": [],
"method": "modify_tags",
"parameters": {"add_tags": [BEYOND_THE_DATABASE]},
},
id="bulk-edit-tags",
),
pytest.param(
"/api/documents/bulk_edit/",
{
"documents": [],
"method": "modify_custom_fields",
"parameters": {
"add_custom_fields": [BEYOND_THE_DATABASE],
"remove_custom_fields": [],
},
},
id="bulk-edit-custom-fields",
),
pytest.param(
"/api/documents/delete/",
{"documents": [BEYOND_THE_DATABASE]},
id="delete",
),
pytest.param(
"/api/documents/reprocess/",
{"documents": [BEYOND_THE_DATABASE]},
id="reprocess",
),
pytest.param(
"/api/documents/rotate/",
{"documents": [BEYOND_THE_DATABASE], "degrees": 90},
id="rotate",
),
pytest.param(
"/api/documents/merge/",
{"documents": [BEYOND_THE_DATABASE, BEYOND_THE_DATABASE + 1]},
id="merge",
),
pytest.param(
"/api/documents/bulk_download/",
{"documents": [BEYOND_THE_DATABASE], "content": "both"},
id="bulk-download",
),
pytest.param(
"/api/documents/selection_data/",
{"documents": [BEYOND_THE_DATABASE]},
id="selection-data",
),
pytest.param(
"/api/share_link_bundles/",
{"document_ids": [BEYOND_THE_DATABASE], "file_version": "archive"},
id="share-link-bundle",
),
pytest.param(
"/api/bulk_edit_objects/",
{
"objects": [BEYOND_THE_DATABASE],
"object_type": "tags",
"operation": "delete",
},
id="bulk-edit-objects",
),
pytest.param(
"/api/tasks/acknowledge/",
{"tasks": [BEYOND_THE_DATABASE]},
id="acknowledge-tasks",
),
pytest.param(
"/api/trash/",
{"action": "restore", "documents": [BEYOND_THE_DATABASE]},
id="trash",
),
],
)
def test_id_no_row_can_have_is_a_400(
self,
admin_client: APIClient,
path: str,
body: dict,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A list of ids includes one larger than a database column can hold
THEN:
- The response is a 400 like any id that does not exist, not a server
error
"""
response = send_json(admin_client, "POST", path, body)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@@ -1,446 +0,0 @@
import pytest
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import Correspondent
from documents.models import WorkflowAction
from documents.models import WorkflowTrigger
from paperless_mail.models import MailAccount
from paperless_testing.http import send_json
ACCOUNT = {
"name": "Email",
"username": "username",
"password": "password",
"imap_server": "server.example.com",
"imap_port": 993,
"imap_security": MailAccount.ImapSecurity.SSL,
"character_set": "UTF-8",
}
TRIGGER = {"type": 2, "sources": [1, 2, 3], "matching_algorithm": 0}
def create_account(client: APIClient) -> int:
response = send_json(client, "POST", "/api/mail_accounts/", ACCOUNT)
assert response.status_code == status.HTTP_201_CREATED
return response.data["id"]
class TestMailBounds:
@pytest.mark.parametrize("port", [-1, 0, 65536, 2**40])
def test_imap_port_outside_the_port_range_is_a_400(
self,
admin_client: APIClient,
port: int,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A mail account is created with a port that cannot exist
THEN:
- The response is a 400
"""
response = send_json(
admin_client,
"POST",
"/api/mail_accounts/",
{**ACCOUNT, "imap_port": port},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "imap_port" in response.data
@pytest.mark.parametrize("port", [1, 993, 65535])
def test_imap_port_inside_the_range_is_accepted(
self,
admin_client: APIClient,
port: int,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A mail account is created with a valid port
THEN:
- It is created
"""
response = send_json(
admin_client,
"POST",
"/api/mail_accounts/",
{**ACCOUNT, "imap_port": port},
)
assert response.status_code == status.HTTP_201_CREATED
@pytest.mark.parametrize("method", ["PATCH", "PUT"])
def test_updating_to_an_impossible_port_is_a_400(
self,
admin_client: APIClient,
method: str,
) -> None:
"""
GIVEN:
- A mail account
WHEN:
- It is updated with a negative port
THEN:
- The response is a 400
"""
account_id = create_account(admin_client)
response = send_json(
admin_client,
method,
f"/api/mail_accounts/{account_id}/",
{**ACCOUNT, "imap_port": -5},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@pytest.mark.parametrize("order", [2**15, -(2**15) - 1, 2**40])
def test_mail_rule_order_beyond_a_smallint_is_a_400(
self,
admin_client: APIClient,
order: int,
) -> None:
"""
GIVEN:
- A mail account
WHEN:
- A rule is created with an order its column cannot hold
THEN:
- The response is a 400
"""
account_id = create_account(admin_client)
response = send_json(
admin_client,
"POST",
"/api/mail_rules/",
{"name": "rule", "account": account_id, "action": 3, "order": order},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "order" in response.data
@pytest.mark.parametrize("order", [2**15 - 1, -(2**15)])
def test_mail_rule_order_at_the_limits_is_accepted(
self,
admin_client: APIClient,
order: int,
) -> None:
"""
GIVEN:
- A mail account
WHEN:
- A rule is created with the largest or smallest order
THEN:
- It is created
"""
account_id = create_account(admin_client)
response = send_json(
admin_client,
"POST",
"/api/mail_rules/",
{"name": "rule", "account": account_id, "action": 3, "order": order},
)
assert response.status_code == status.HTTP_201_CREATED
@pytest.mark.parametrize(
("length", "expected"),
[(256, status.HTTP_201_CREATED), (257, status.HTTP_400_BAD_REQUEST)],
)
def test_mail_rule_action_parameter_must_fit_the_column(
self,
admin_client: APIClient,
length: int,
expected: int,
) -> None:
"""
GIVEN:
- A mail account
WHEN:
- A rule is created with an action parameter at, or past, the column size
THEN:
- It is created, or rejected, accordingly
"""
account_id = create_account(admin_client)
response = send_json(
admin_client,
"POST",
"/api/mail_rules/",
{
"name": "rule",
"account": account_id,
"action": 3,
"action_parameter": "x" * length,
},
)
assert response.status_code == expected
def test_updating_a_mail_rule_to_an_impossible_order_is_a_400(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- A mail rule
WHEN:
- It is patched with an order beyond a smallint
THEN:
- The response is a 400
"""
account_id = create_account(admin_client)
rule = send_json(
admin_client,
"POST",
"/api/mail_rules/",
{"name": "rule", "account": account_id, "action": 3},
)
response = send_json(
admin_client,
"PATCH",
f"/api/mail_rules/{rule.data['id']}/",
{"order": 2**40},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
class TestWorkflowOrder:
@pytest.mark.parametrize(
("order", "expected"),
[
(2**31, status.HTTP_400_BAD_REQUEST),
(-(2**31) - 1, status.HTTP_400_BAD_REQUEST),
(2**40, status.HTTP_400_BAD_REQUEST),
(2**31 - 1, status.HTTP_201_CREATED),
(-(2**31), status.HTTP_201_CREATED),
],
)
def test_workflow_order_must_fit_the_column(
self,
admin_client: APIClient,
order: int,
expected: int,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A workflow is created with an order beyond a 32 bit integer, or exactly
at its limits
THEN:
- It is rejected, or created, accordingly
"""
response = send_json(
admin_client,
"POST",
"/api/workflows/",
{
"name": "workflow",
"order": order,
"enabled": True,
"triggers": [TRIGGER],
"actions": [{"type": 1, "assign_title": "title"}],
},
)
assert response.status_code == expected
class TestStandaloneWorkflowRowIds:
def test_trigger_created_with_an_existing_id_gets_its_own(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An existing workflow trigger
WHEN:
- A new trigger is created with that trigger's id in the payload
THEN:
- A new row is created and the existing one is untouched
"""
existing = WorkflowTrigger.objects.create(
type=2,
sources="1",
matching_algorithm=0,
)
response = send_json(
admin_client,
"POST",
"/api/workflow_triggers/",
{**TRIGGER, "id": existing.pk},
)
assert response.status_code == status.HTTP_201_CREATED
assert response.data["id"] != existing.pk
assert WorkflowTrigger.objects.count() == 2
def test_action_created_with_an_existing_id_gets_its_own(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An existing workflow action
WHEN:
- A new action is created with that action's id in the payload
THEN:
- A new row is created and the existing one is untouched
"""
existing = WorkflowAction.objects.create(type=1, assign_title="original")
response = send_json(
admin_client,
"POST",
"/api/workflow_actions/",
{"type": 1, "assign_title": "new", "id": existing.pk},
)
assert response.status_code == status.HTTP_201_CREATED
assert response.data["id"] != existing.pk
existing.refresh_from_db()
assert existing.assign_title == "original"
def test_put_cannot_overwrite_another_trigger_through_the_body_id(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- Two workflow triggers
WHEN:
- One is replaced with a body that carries the other's id
THEN:
- Only the trigger named in the URL changes
"""
target = WorkflowTrigger.objects.create(
type=2,
sources="1",
matching_algorithm=0,
)
other = WorkflowTrigger.objects.create(
type=2,
sources="1",
matching_algorithm=0,
filter_filename="keep",
)
response = send_json(
admin_client,
"PUT",
f"/api/workflow_triggers/{target.pk}/",
{**TRIGGER, "filter_filename": "changed", "id": other.pk},
)
assert response.status_code == status.HTTP_200_OK
target.refresh_from_db()
other.refresh_from_db()
assert target.filter_filename == "changed"
assert other.filter_filename == "keep"
class TestUniqueNameOnUpdate:
@pytest.mark.parametrize("owner_kind", ["owned", "unowned"])
def test_patching_to_an_existing_name_is_a_400(
self,
admin_client: APIClient,
admin_user: User,
owner_kind: str,
) -> None:
"""
GIVEN:
- Two correspondents with the same owner, or none
WHEN:
- One is patched to the other's name without mentioning the owner
THEN:
- The response is a 400, as it is when creating a duplicate
"""
owner = admin_user if owner_kind == "owned" else None
Correspondent.objects.create(name="taken", owner=owner)
other = Correspondent.objects.create(name="free", owner=owner)
response = send_json(
admin_client,
"PATCH",
f"/api/correspondents/{other.pk}/",
{"name": "taken"},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
other.refresh_from_db()
assert other.name == "free"
@pytest.mark.parametrize("owner_kind", ["owned", "unowned"])
def test_renaming_to_a_free_name_or_keeping_the_name_still_works(
self,
admin_client: APIClient,
admin_user: User,
owner_kind: str,
) -> None:
"""
GIVEN:
- A correspondent
WHEN:
- It is renamed to a free name, then saved again under that name
THEN:
- Both requests succeed
"""
correspondent = Correspondent.objects.create(
name="before",
owner=admin_user if owner_kind == "owned" else None,
)
first = send_json(
admin_client,
"PATCH",
f"/api/correspondents/{correspondent.pk}/",
{"name": "after"},
)
second = send_json(
admin_client,
"PATCH",
f"/api/correspondents/{correspondent.pk}/",
{"name": "after"},
)
assert first.status_code == status.HTTP_200_OK
assert second.status_code == status.HTTP_200_OK
def test_the_same_name_under_a_different_owner_is_allowed(
self,
admin_client: APIClient,
admin_user: User,
regular_user: User,
) -> None:
"""
GIVEN:
- Correspondents with the same name but different owners are allowed
WHEN:
- One correspondent is renamed to a name another owner already uses
THEN:
- The request succeeds
"""
Correspondent.objects.create(name="shared name", owner=regular_user)
mine = Correspondent.objects.create(name="mine", owner=admin_user)
response = send_json(
admin_client,
"PATCH",
f"/api/correspondents/{mine.pk}/",
{"name": "shared name"},
)
assert response.status_code == status.HTTP_200_OK
@@ -1,139 +0,0 @@
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from paperless_mail.models import MailAccount
from paperless_testing.http import send_json
ACCOUNT = {
"name": "Email",
"username": "username",
"password": "password",
"imap_server": "server.example.com",
"imap_port": 143,
"imap_security": MailAccount.ImapSecurity.STARTTLS,
"character_set": "UTF-8",
}
class TestStarttlsOnTheSslPort:
def test_creating_a_starttls_account_on_port_993_is_a_400(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A mail account is created with STARTTLS on port 993
THEN:
- The response is a 400 naming the port, that pair can never connect
"""
response = send_json(
admin_client,
"POST",
"/api/mail_accounts/",
{**ACCOUNT, "imap_port": 993},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "imap_port" in response.data
@pytest.mark.parametrize(
("security", "port"),
[
(MailAccount.ImapSecurity.STARTTLS, 143),
(MailAccount.ImapSecurity.SSL, 993),
(MailAccount.ImapSecurity.NONE, 143),
],
)
def test_other_combinations_are_accepted(
self,
admin_client: APIClient,
security: int,
port: int,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- A mail account is created with a sensible security and port pair
THEN:
- It is created
"""
response = send_json(
admin_client,
"POST",
"/api/mail_accounts/",
{**ACCOUNT, "imap_security": security, "imap_port": port},
)
assert response.status_code == status.HTTP_201_CREATED
def test_the_account_test_endpoint_reports_it_as_a_400(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- The account test is run with STARTTLS on port 993
THEN:
- The response is a 400, the mailbox class refuses that pair with an
error that used to escape as a 500
"""
response = send_json(
admin_client,
"POST",
"/api/mail_accounts/test/",
{**ACCOUNT, "imap_port": 993},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
def test_a_patch_that_creates_the_pair_is_a_400(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- A STARTTLS account on port 143, and an SSL account on port 993
WHEN:
- Only the port of the first, or only the security of the second, is patched
THEN:
- Both requests are a 400, the stored half of the pair counts
"""
starttls = send_json(
admin_client,
"POST",
"/api/mail_accounts/",
ACCOUNT,
).data["id"]
ssl = send_json(
admin_client,
"POST",
"/api/mail_accounts/",
{
**ACCOUNT,
"name": "Other",
"imap_port": 993,
"imap_security": MailAccount.ImapSecurity.SSL,
},
).data["id"]
port_patch = send_json(
admin_client,
"PATCH",
f"/api/mail_accounts/{starttls}/",
{"imap_port": 993},
)
security_patch = send_json(
admin_client,
"PATCH",
f"/api/mail_accounts/{ssl}/",
{"imap_security": MailAccount.ImapSecurity.STARTTLS},
)
assert port_patch.status_code == status.HTTP_400_BAD_REQUEST
assert security_patch.status_code == status.HTTP_400_BAD_REQUEST
@@ -1,405 +0,0 @@
import imaplib
import shutil
import socket
import ssl
import pytest
from django.contrib.auth.models import User
from django.core import mail
from django.core.files.uploadedfile import SimpleUploadedFile
from pytest_django.fixtures import Settings
from pytest_mock import MockerFixture
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import Document
from documents.models import SavedView
from paperless_mail.mail import MailError
from paperless_testing.dirs import PaperlessDirs
from paperless_testing.factories import DocumentFactory
from paperless_testing.factories import UserFactory
from paperless_testing.http import send_json
from paperless_testing.permissions import grant_global
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
EMAIL = {
"addresses": "hello@paperless-ngx.com",
"subject": "subject",
"message": "message",
"use_archive_version": False,
}
MAIL_ACCOUNT = {
"imap_server": "server.example.com",
"imap_port": 993,
"imap_security": 2,
"username": "admin",
"password": "secret",
}
class TestEmailSingleDocument:
def _document_with_file(self, paperless_dirs: PaperlessDirs) -> Document:
document = DocumentFactory.create(
filename="test.pdf",
mime_type="application/pdf",
)
shutil.copy(SIMPLE_DIGITAL_PDF, document.source_path)
return document
def test_json_body_sends_the_email(
self,
admin_client: APIClient,
paperless_dirs: PaperlessDirs,
) -> None:
"""
GIVEN:
- A document with a file
WHEN:
- The per document email endpoint gets a JSON body
THEN:
- The email is sent, a JSON body used to crash on a QueryDict only call
"""
document = self._document_with_file(paperless_dirs)
response = send_json(
admin_client,
"POST",
f"/api/documents/{document.pk}/email/",
EMAIL,
)
assert response.status_code == status.HTTP_200_OK
assert len(mail.outbox) == 1
def test_form_body_still_sends_the_email(
self,
admin_client: APIClient,
paperless_dirs: PaperlessDirs,
) -> None:
"""
GIVEN:
- A document with a file
WHEN:
- The endpoint gets a form encoded body
THEN:
- The email is sent
"""
document = self._document_with_file(paperless_dirs)
response = admin_client.post(
f"/api/documents/{document.pk}/email/",
EMAIL,
format="multipart",
)
assert response.status_code == status.HTTP_200_OK
assert len(mail.outbox) == 1
def test_json_body_is_still_validated(self, admin_client: APIClient) -> None:
"""
GIVEN:
- A document
WHEN:
- A JSON body without addresses is sent
THEN:
- The response is a 400 from the serializer, not a server error
"""
document = DocumentFactory.create()
response = send_json(
admin_client,
"POST",
f"/api/documents/{document.pk}/email/",
{"subject": "only a subject"},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "addresses" in response.data
class TestMailAccountTest:
def test_form_encoded_body_is_accepted(
self,
admin_client: APIClient,
mocker: MockerFixture,
) -> None:
"""
GIVEN:
- A mailbox that connects
WHEN:
- The account test gets a form encoded body, which is a read only QueryDict
THEN:
- The request succeeds, the view must not write into the request data
"""
mocker.patch("paperless_mail.views.get_mailbox")
mocker.patch("paperless_mail.views.mailbox_login")
response = admin_client.post(
"/api/mail_accounts/test/",
MAIL_ACCOUNT,
format="multipart",
)
assert response.status_code == status.HTTP_200_OK
assert response.data == {"success": True}
def test_write_only_serializer_fields_are_not_passed_to_the_model(
self,
admin_client: APIClient,
mocker: MockerFixture,
) -> None:
"""
GIVEN:
- A mailbox that connects
WHEN:
- The account test body carries set_permissions, which is not a model field
THEN:
- The request succeeds
"""
mocker.patch("paperless_mail.views.get_mailbox")
mocker.patch("paperless_mail.views.mailbox_login")
response = send_json(
admin_client,
"POST",
"/api/mail_accounts/test/",
{
**MAIL_ACCOUNT,
"set_permissions": {"view": {"users": [], "groups": []}},
},
)
assert response.status_code == status.HTTP_200_OK
def test_multipart_body_with_a_large_file_is_accepted(
self,
admin_client: APIClient,
mocker: MockerFixture,
settings: Settings,
) -> None:
"""
GIVEN:
- A mailbox that connects, and uploads that spill to a temporary file
WHEN:
- The account test gets a multipart body that carries a large file
THEN:
- The request succeeds, copying the request data would try to deep copy
the temporary file and fail
"""
settings.FILE_UPLOAD_MAX_MEMORY_SIZE = 10
mocker.patch("paperless_mail.views.get_mailbox")
mocker.patch("paperless_mail.views.mailbox_login")
response = admin_client.post(
"/api/mail_accounts/test/",
{
**MAIL_ACCOUNT,
"attachment": SimpleUploadedFile("junk.bin", b"0" * 1000),
},
format="multipart",
)
assert response.status_code == status.HTTP_200_OK
@pytest.mark.parametrize(
"error",
[
pytest.param(ConnectionRefusedError, id="refused"),
pytest.param(socket.gaierror, id="unknown-host"),
pytest.param(TimeoutError, id="timeout"),
pytest.param(ssl.SSLError, id="tls"),
pytest.param(imaplib.IMAP4.error, id="imap-error"),
pytest.param(UnicodeError, id="bad-host-name"),
pytest.param(MailError, id="mail-error"),
],
)
def test_connection_failures_are_reported_as_a_400(
self,
admin_client: APIClient,
mocker: MockerFixture,
error: type[Exception],
) -> None:
"""
GIVEN:
- A mailbox that cannot be reached
WHEN:
- The account test is run
THEN:
- The response is a 400 saying the server cannot be reached, that is the
answer this endpoint exists to give
"""
mocker.patch("paperless_mail.views.get_mailbox", side_effect=error("boom"))
response = send_json(
admin_client,
"POST",
"/api/mail_accounts/test/",
MAIL_ACCOUNT,
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.content == b"Unable to connect to server"
class TestDeactivateTotp:
def test_unknown_user_is_a_404_for_a_superuser(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- A superuser
WHEN:
- TOTP is deactivated for a user id that does not exist
THEN:
- The response is a 404
"""
response = admin_client.post("/api/users/999999/deactivate_totp/")
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_non_numeric_user_id_is_a_404_for_a_superuser(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- A superuser
WHEN:
- The user id is not a number
THEN:
- The response is a 404, not a server error
"""
response = admin_client.post("/api/users/abc/deactivate_totp/")
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_status_does_not_reveal_whether_another_user_exists(
self,
rest_api_client: APIClient,
regular_user: User,
) -> None:
"""
GIVEN:
- A regular user allowed to use the users API, and another user
WHEN:
- They deactivate TOTP for another existing user, and for one that does not
exist
THEN:
- Both answers are a 403, so the status cannot be used to find user ids
"""
grant_global(regular_user, "add_user", "change_user")
other = UserFactory.create(username="other")
rest_api_client.force_authenticate(user=regular_user)
existing = rest_api_client.post(f"/api/users/{other.pk}/deactivate_totp/")
missing = rest_api_client.post("/api/users/999999/deactivate_totp/")
assert existing.status_code == status.HTTP_403_FORBIDDEN
assert missing.status_code == status.HTTP_403_FORBIDDEN
def test_a_user_can_reach_their_own_record(
self,
rest_api_client: APIClient,
regular_user: User,
) -> None:
"""
GIVEN:
- A regular user with no authenticator
WHEN:
- They deactivate TOTP for themselves
THEN:
- The lookup succeeds and the answer is that no TOTP was found
"""
grant_global(regular_user, "add_user", "change_user")
rest_api_client.force_authenticate(user=regular_user)
response = rest_api_client.post(
f"/api/users/{regular_user.pk}/deactivate_totp/",
)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response.content == b"TOTP not found"
class TestSavedViewPartialRules:
def test_patch_with_a_rule_missing_its_type_is_a_400(
self,
admin_client: APIClient,
admin_user: User,
) -> None:
"""
GIVEN:
- A saved view
WHEN:
- It is patched with a filter rule that has no rule_type
THEN:
- The response is a 400, not a database error
"""
view = SavedView.objects.create(
name="view",
owner=admin_user,
sort_field="created",
)
response = send_json(
admin_client,
"PATCH",
f"/api/saved_views/{view.pk}/",
{"filter_rules": [{"value": "1"}]},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "filter_rules" in response.data
class TestConfigFormBody:
@pytest.mark.parametrize(
"body",
["language=", "llm_api_key=", "language=&llm_api_key="],
)
def test_form_encoded_empty_values_are_accepted(
self,
admin_client: APIClient,
config_id: int,
body: str,
) -> None:
"""
GIVEN:
- The application configuration
WHEN:
- A form encoded body with empty values is patched in
THEN:
- The request succeeds, the serializer used to write into the read only
QueryDict
"""
response = admin_client.patch(
f"/api/config/{config_id}/",
data=body,
content_type="application/x-www-form-urlencoded",
)
assert response.status_code == status.HTTP_200_OK
def test_form_encoded_empty_json_field_is_a_clean_400(
self,
admin_client: APIClient,
config_id: int,
) -> None:
"""
GIVEN:
- The application configuration
WHEN:
- An empty value for a JSON field arrives in a form encoded body
THEN:
- The response is a 400 naming the field, not a server error
"""
response = admin_client.patch(
f"/api/config/{config_id}/",
data="user_args=",
content_type="application/x-www-form-urlencoded",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "user_args" in response.data
@@ -1,299 +0,0 @@
import json
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import WorkflowAction
from documents.models import WorkflowActionEmail
from documents.models import WorkflowTrigger
from paperless_testing.http import send_json
EMAIL = {
"subject": "original",
"body": "body",
"to": "someone@example.com",
"include_document": False,
}
def workflow_body(name: str, *, trigger: dict, action: dict) -> dict:
return {
"name": name,
"order": 0,
"enabled": True,
"triggers": [
{"type": 2, "sources": [1], "matching_algorithm": 0, **trigger},
],
"actions": [{"type": 3, "email": EMAIL, **action}],
}
def make_workflow(client: APIClient, name: str) -> dict:
response = send_json(
client,
"POST",
"/api/workflows/",
workflow_body(name, trigger={}, action={}),
)
assert response.status_code == status.HTTP_201_CREATED
return response.data
class TestWorkflowRowOwnership:
def test_update_cannot_take_over_another_workflows_action(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- Two workflows, each with an email action
WHEN:
- The first is updated with the id of the second one's action and a changed
email
THEN:
- The second workflow's action and email are untouched, the first gets its
own action
"""
first = make_workflow(admin_client, "first")
second = make_workflow(admin_client, "second")
foreign_action = second["actions"][0]
foreign_email_id = foreign_action["email"]["id"]
response = send_json(
admin_client,
"PUT",
f"/api/workflows/{first['id']}/",
workflow_body(
"first",
trigger={"id": first["triggers"][0]["id"]},
action={
"id": foreign_action["id"],
"email": {**EMAIL, "subject": "taken over"},
},
),
)
assert response.status_code == status.HTTP_200_OK
assert response.data["actions"][0]["id"] != foreign_action["id"]
assert WorkflowActionEmail.objects.get(pk=foreign_email_id).subject == (
"original"
)
second_actions = list(
WorkflowAction.objects.filter(workflows__pk=second["id"]),
)
assert [a.pk for a in second_actions] == [foreign_action["id"]]
def test_update_cannot_take_over_another_workflows_trigger(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- Two workflows
WHEN:
- The first is updated with the id of the second one's trigger and a
different filter
THEN:
- The second workflow's trigger is untouched
"""
first = make_workflow(admin_client, "first")
second = make_workflow(admin_client, "second")
foreign_trigger_id = second["triggers"][0]["id"]
response = send_json(
admin_client,
"PUT",
f"/api/workflows/{first['id']}/",
workflow_body(
"first",
trigger={"id": foreign_trigger_id, "filter_filename": "taken"},
action={"id": first["actions"][0]["id"]},
),
)
assert response.status_code == status.HTTP_200_OK
assert response.data["triggers"][0]["id"] != foreign_trigger_id
assert WorkflowTrigger.objects.get(pk=foreign_trigger_id).filter_filename != (
"taken"
)
assert list(
WorkflowTrigger.objects.filter(workflows__pk=second["id"]).values_list(
"pk",
flat=True,
),
) == [foreign_trigger_id]
def test_nested_email_id_of_another_action_is_ignored(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- Two workflows with email actions
WHEN:
- The first is updated, keeping its own action, with the second action's
email id in the nested email
THEN:
- The other email is untouched and the action's own email is the one
changed
"""
first = make_workflow(admin_client, "first")
second = make_workflow(admin_client, "second")
own_action = first["actions"][0]
own_email_id = own_action["email"]["id"]
foreign_email_id = second["actions"][0]["email"]["id"]
response = send_json(
admin_client,
"PUT",
f"/api/workflows/{first['id']}/",
workflow_body(
"first",
trigger={"id": first["triggers"][0]["id"]},
action={
"id": own_action["id"],
"email": {**EMAIL, "id": foreign_email_id, "subject": "mine"},
},
),
)
assert response.status_code == status.HTTP_200_OK
assert WorkflowActionEmail.objects.get(pk=foreign_email_id).subject == (
"original"
)
assert response.data["actions"][0]["email"]["id"] == own_email_id
assert WorkflowActionEmail.objects.get(pk=own_email_id).subject == "mine"
def test_nested_email_id_beyond_the_database_range_is_ignored(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- A workflow with an email action
WHEN:
- It is updated with a nested email id larger than a column can hold
THEN:
- The request succeeds and the action keeps its own email row
"""
workflow = make_workflow(admin_client, "workflow")
action = workflow["actions"][0]
response = send_json(
admin_client,
"PUT",
f"/api/workflows/{workflow['id']}/",
workflow_body(
"workflow",
trigger={"id": workflow["triggers"][0]["id"]},
action={
"id": action["id"],
"email": {**EMAIL, "id": 2**63},
},
),
)
assert response.status_code == status.HTTP_200_OK
assert response.data["actions"][0]["email"]["id"] == action["email"]["id"]
def test_create_ignores_ids_of_existing_rows(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- An existing workflow
WHEN:
- A new workflow is created that carries that workflow's trigger and
action ids
THEN:
- New rows are created and the existing ones are untouched
"""
existing = make_workflow(admin_client, "existing")
response = send_json(
admin_client,
"POST",
"/api/workflows/",
workflow_body(
"new",
trigger={
"id": existing["triggers"][0]["id"],
"filter_filename": "taken",
},
action={"id": existing["actions"][0]["id"]},
),
)
assert response.status_code == status.HTTP_201_CREATED
assert response.data["triggers"][0]["id"] != existing["triggers"][0]["id"]
assert response.data["actions"][0]["id"] != existing["actions"][0]["id"]
assert WorkflowTrigger.objects.get(
pk=existing["triggers"][0]["id"],
).filter_filename != ("taken")
def test_editing_a_workflow_keeps_its_row_ids(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- A workflow read back from the API, as the UI does before an edit
WHEN:
- It is sent back with a changed name and email subject
THEN:
- Its trigger, action and email keep their ids and no rows are added
"""
workflow = make_workflow(admin_client, "workflow")
body = admin_client.get(f"/api/workflows/{workflow['id']}/").data
body = json.loads(json.dumps(body))
body["name"] = "renamed"
body["actions"][0]["email"]["subject"] = "edited"
response = send_json(
admin_client,
"PUT",
f"/api/workflows/{workflow['id']}/",
body,
)
assert response.status_code == status.HTTP_200_OK
assert response.data["triggers"][0]["id"] == workflow["triggers"][0]["id"]
assert response.data["actions"][0]["id"] == workflow["actions"][0]["id"]
assert (
response.data["actions"][0]["email"]["id"]
== (workflow["actions"][0]["email"]["id"])
)
assert response.data["actions"][0]["email"]["subject"] == "edited"
assert WorkflowAction.objects.count() == 1
assert WorkflowActionEmail.objects.count() == 1
assert WorkflowTrigger.objects.count() == 1
def test_a_new_action_in_an_update_is_added_beside_the_existing_one(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- A workflow with one action
WHEN:
- It is updated with that action plus a new one without an id
THEN:
- The first action keeps its id and a second one is created
"""
workflow = make_workflow(admin_client, "workflow")
body = json.loads(
json.dumps(admin_client.get(f"/api/workflows/{workflow['id']}/").data),
)
body["actions"].append({"type": 1, "assign_title": "added"})
response = send_json(
admin_client,
"PUT",
f"/api/workflows/{workflow['id']}/",
body,
)
assert response.status_code == status.HTTP_200_OK
assert len(response.data["actions"]) == 2
assert response.data["actions"][0]["id"] == workflow["actions"][0]["id"]
@@ -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])
+23 -26
View File
@@ -3,7 +3,6 @@ import logging
import os
import platform
import re
import sys
import tempfile
import zipfile
from collections import Counter
@@ -150,7 +149,6 @@ from documents.filters import StoragePathFilterSet
from documents.filters import TagFilterSet
from documents.filters import TitleContentFilter
from documents.filters import WorkflowFilterSet
from documents.filters import in_range_ids
from documents.mail import EmailAttachment
from documents.mail import send_email
from documents.matching import match_correspondents
@@ -266,7 +264,6 @@ from documents.versioning import resolve_effective_document
from documents.versioning import resolve_requested_version_for_root
from documents.versioning import versions_newest_first
from paperless import version
from paperless.api_parsers import ObjectJSONParser
from paperless.celery import app as celery_app
from paperless.config import AIConfig
from paperless.config import GeneralConfig
@@ -2120,9 +2117,8 @@ class DocumentViewSet(
)
# TODO: deprecated, remove with drop of support for API v9
def email_document(self, request, pk=None):
# A JSON body is a plain dict and a form body a QueryDict, copy into a dict
request_data = dict(request.data.items())
request_data["documents"] = [pk]
request_data = request.data.copy()
request_data.setlist("documents", [pk])
return self.email_documents(request, data=request_data)
@action(
@@ -2966,8 +2962,6 @@ class LogViewSet(ViewSet):
raise ValidationError({"limit": "Must be a positive integer"})
if limit < 1:
raise ValidationError({"limit": "Must be a positive integer"})
# A limit past what a deque can hold is the same as no limit at all
limit = min(limit, sys.maxsize)
else:
limit = None
@@ -3079,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,
@@ -3138,7 +3136,7 @@ def queue_bulk_operation(
class DocumentOperationPermissionMixin(PassUserMixin, DocumentSelectionMixin):
permission_classes = (IsAuthenticated,)
parser_classes = (ObjectJSONParser,)
parser_classes = (parsers.JSONParser,)
def _queue_bulk_operation(self, method, documents, parameters, from_webui):
return queue_bulk_operation(
@@ -3640,7 +3638,7 @@ class PostDocumentView(GenericAPIView[Any]):
class SelectionDataView(DocumentSelectionMixin, GenericAPIView[Any]):
permission_classes = (IsAuthenticated, ViewDocumentsPermissions)
serializer_class = DocumentSelectionSerializer
parser_classes = (parsers.MultiPartParser, ObjectJSONParser)
parser_classes = (parsers.MultiPartParser, parsers.JSONParser)
def post(self, request, format=None):
serializer = self.get_serializer(data=request.data)
@@ -3825,9 +3823,6 @@ class GlobalSearchView(PassUserMixin):
return HttpResponseBadRequest(
f"Query must be at most {_MAX_QUERY_LENGTH} characters",
)
if "\x00" in query:
# Postgres cannot store or compare text containing a null byte
return HttpResponseBadRequest("Query must not contain null characters")
db_only = request.query_params.get("db_only", False)
@@ -4181,7 +4176,7 @@ class StatisticsView(GenericAPIView[Any]):
class BulkDownloadView(DocumentSelectionMixin, GenericAPIView[Any]):
permission_classes = (IsAuthenticated, ViewDocumentsPermissions)
serializer_class = BulkDownloadSerializer
parser_classes = (ObjectJSONParser,)
parser_classes = (parsers.JSONParser,)
def post(self, request, format=None):
serializer = self.get_serializer(data=request.data)
@@ -4331,10 +4326,8 @@ class UiSettingsView(GenericAPIView[Any]):
user = User.objects.select_related("ui_settings").get(pk=request.user.id)
ui_settings = {}
if hasattr(user, "ui_settings"):
# Saved as null or, before it was validated, as something else
stored = user.ui_settings.settings
ui_settings = stored if isinstance(stored, dict) else {}
if isinstance(ui_settings.get("update_checking"), dict):
ui_settings = user.ui_settings.settings
if "update_checking" in ui_settings:
ui_settings["update_checking"]["backend_setting"] = (
settings.ENABLE_UPDATE_CHECK
)
@@ -5064,9 +5057,9 @@ class ShareLinkBundleViewSet(PassUserMixin, ModelViewSet[ShareLinkBundle]):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
document_ids = serializer.validated_data["document_ids"]
documents_qs = Document.objects.filter(
pk__in=in_range_ids(document_ids),
).select_related("owner")
documents_qs = Document.objects.filter(pk__in=document_ids).select_related(
"owner",
)
found_ids = set(documents_qs.values_list("pk", flat=True))
missing = sorted(set(document_ids) - found_ids)
if missing:
@@ -5318,7 +5311,7 @@ def serve_file(
class BulkEditObjectsView(PassUserMixin):
permission_classes = (IsAuthenticated,)
serializer_class = BulkEditObjectsSerializer
parser_classes = (ObjectJSONParser,)
parser_classes = (parsers.JSONParser,)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
@@ -5349,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))
-16
View File
@@ -1,16 +0,0 @@
from rest_framework.exceptions import ParseError
from rest_framework.parsers import JSONParser
class ObjectJSONParser(JSONParser):
"""
DRF accepts any JSON document as a request body. The views and serializers here
read the body as a mapping, so a top level list or scalar (or null) would end in
a server error. Reject it as the malformed request it is.
"""
def parse(self, stream, media_type=None, parser_context=None):
data = super().parse(stream, media_type, parser_context)
if not isinstance(data, dict):
raise ParseError("The request body must be a JSON object.")
return data
-2
View File
@@ -20,6 +20,4 @@ class ObfuscatedPasswordField(serializers.CharField):
return OBFUSCATED_PASSWORD_MASK
def to_internal_value(self, data):
if not isinstance(data, str):
self.fail("invalid")
return data
+3 -25
View File
@@ -15,7 +15,6 @@ from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.files.uploadedfile import UploadedFile
from django.http import QueryDict
from PIL import Image
from rest_framework import serializers
from rest_framework.authtoken.serializers import AuthTokenSerializer
@@ -78,21 +77,9 @@ class PaperlessAuthTokenSerializer(AuthTokenSerializer):
return attrs
class CodenameRelatedField(serializers.SlugRelatedField):
"""
Looks a permission up by its codename. A codename with a null byte cannot exist, and
Postgres raises an error, instead of finding nothing, if asked for one.
"""
def to_internal_value(self, data):
if isinstance(data, str) and "\x00" in data:
self.fail("does_not_exist", slug_name=self.slug_field, value=repr(data))
return super().to_internal_value(data)
class UserSerializer(PasswordValidationMixin, serializers.ModelSerializer[User]):
password = ObfuscatedPasswordField(required=False)
user_permissions = CodenameRelatedField(
user_permissions = serializers.SlugRelatedField(
many=True,
queryset=Permission.objects.exclude(content_type__app_label="admin"),
slug_field="codename",
@@ -159,7 +146,7 @@ class UserSerializer(PasswordValidationMixin, serializers.ModelSerializer[User])
class GroupSerializer(serializers.ModelSerializer[Group]):
permissions = CodenameRelatedField(
permissions = serializers.SlugRelatedField(
many=True,
queryset=Permission.objects.exclude(content_type__app_label="admin"),
slug_field="codename",
@@ -285,9 +272,6 @@ class ApplicationConfigurationSerializer(
return value
def run_validation(self, data):
# A form encoded body arrives as an immutable QueryDict
if isinstance(data, QueryDict) and not data._mutable:
data = data.copy()
# Empty strings treated as None to avoid unexpected behavior
if "user_args" in data and data["user_args"] == "":
data["user_args"] = None
@@ -298,8 +282,7 @@ class ApplicationConfigurationSerializer(
if "llm_output_language" in data and data["llm_output_language"] == "":
data["llm_output_language"] = None
for field in self.OBFUSCATED_FIELDS:
# Anything that is not a string is left for the field to reject
if field in data and isinstance(data[field], str):
if field in data and data[field] is not None:
if data[field] == "":
data[field] = None
# Not a real value, don't overwrite the stored one
@@ -382,8 +365,3 @@ class ApplicationConfigurationSerializer(
class Meta:
model = ApplicationConfiguration
fields = "__all__"
class TOTPActivationSerializer(serializers.Serializer[dict[str, str]]):
secret = serializers.CharField()
code = serializers.CharField()
-5
View File
@@ -169,11 +169,6 @@ REST_FRAMEWORK = {
"rest_framework.authentication.TokenAuthentication",
"rest_framework.authentication.SessionAuthentication",
],
"DEFAULT_PARSER_CLASSES": [
"paperless.api_parsers.ObjectJSONParser",
"rest_framework.parsers.FormParser",
"rest_framework.parsers.MultiPartParser",
],
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.AcceptHeaderVersioning",
"DEFAULT_VERSION": "10", # match src-ui/src/environments/environment.prod.ts
# Make sure these are ordered and that the most recent version appears
@@ -1,122 +0,0 @@
from pathlib import Path
import pytest
from pytest_django.fixtures import DjangoAssertNumQueries
from pytest_django.fixtures import Settings
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.test import APIClient
from paperless.serialisers import GroupSerializer
from paperless.serialisers import UserSerializer
class TestNullByteInput:
@pytest.mark.parametrize("db_only", ["true", "false"])
def test_global_search_rejects_null_byte(
self,
admin_client: APIClient,
db_only: str,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- The global search query contains a null byte
THEN:
- The response is a 400, the query never reaches the database
"""
response = admin_client.get(
"/api/search/",
{"query": "invoice\x00number", "db_only": db_only},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@pytest.mark.parametrize(
("serializer", "field"),
[
pytest.param(GroupSerializer, "permissions", id="group"),
pytest.param(UserSerializer, "user_permissions", id="user"),
],
)
def test_codename_with_null_byte_is_rejected_without_a_query(
self,
db: None,
django_assert_num_queries: DjangoAssertNumQueries,
serializer: type,
field: str,
) -> None:
"""
GIVEN:
- A permission codename field
WHEN:
- A value containing a null byte is validated
THEN:
- It is rejected without querying, Postgres raises an error for it
where SQLite does not
"""
codename_field = serializer().fields[field].child_relation
with django_assert_num_queries(0), pytest.raises(ValidationError):
codename_field.to_internal_value("view_document\x00")
class TestLogLimit:
def test_limit_larger_than_any_file_returns_everything(
self,
admin_client: APIClient,
settings: Settings,
tmp_path: Path,
) -> None:
"""
GIVEN:
- A log file
WHEN:
- The limit is larger than a platform integer can hold
THEN:
- The whole file is returned, as for any limit above its length
"""
settings.LOGGING_DIR = tmp_path
(tmp_path / "paperless.log").write_text("one\ntwo\nthree\n")
response = admin_client.get("/api/logs/paperless/", {"limit": 2**70})
assert response.status_code == status.HTTP_200_OK
assert response.data == ["one", "two", "three"]
class TestTotpView:
def test_options_does_not_fail(self, admin_client: APIClient) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- OPTIONS is sent to the TOTP endpoint
THEN:
- The request succeeds, DRF's metadata needs a serializer on the view
"""
response = admin_client.options("/api/profile/totp/")
assert response.status_code == status.HTTP_200_OK
@pytest.mark.parametrize(
"body",
[{}, {"secret": "abc"}, {"code": "123456"}, {"secret": None, "code": None}],
)
def test_activation_with_missing_fields_is_a_400(
self,
admin_client: APIClient,
body: dict,
) -> None:
"""
GIVEN:
- An authenticated client
WHEN:
- TOTP is activated without both the secret and the code
THEN:
- The response is a 400, not a server error
"""
response = admin_client.post("/api/profile/totp/", body, format="json")
assert response.status_code == status.HTTP_400_BAD_REQUEST
+5 -17
View File
@@ -34,7 +34,6 @@ from rest_framework.exceptions import ValidationError
from rest_framework.fields import BooleanField
from rest_framework.filters import OrderingFilter
from rest_framework.generics import GenericAPIView
from rest_framework.generics import get_object_or_404
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
@@ -54,7 +53,6 @@ from paperless.serialisers import ApplicationConfigurationSerializer
from paperless.serialisers import GroupSerializer
from paperless.serialisers import PaperlessAuthTokenSerializer
from paperless.serialisers import ProfileSerializer
from paperless.serialisers import TOTPActivationSerializer
from paperless.serialisers import UserSerializer
@@ -218,17 +216,11 @@ class UserViewSet(ModelViewSet[User]):
@action(detail=True, methods=["post"])
def deactivate_totp(self, request, pk=None):
request_user = request.user
# Decide on permission before looking the user up, so the response does not
# reveal whether another user's id exists
try:
is_self = int(pk) == request_user.pk
except (TypeError, ValueError):
is_self = False
if not request_user.is_superuser and not is_self:
user = User.objects.get(pk=pk)
if not request_user.is_superuser and request_user != user:
return HttpResponseForbidden(
"You do not have permission to deactivate TOTP for this user",
)
user = get_object_or_404(User, pk=pk)
authenticator = Authenticator.objects.filter(
user=user,
type=Authenticator.Type.TOTP,
@@ -336,7 +328,6 @@ class TOTPView(GenericAPIView[Any]):
"""
permission_classes = [IsAuthenticated]
serializer_class = TOTPActivationSerializer
def get(self, request, *args, **kwargs):
"""
@@ -359,18 +350,15 @@ class TOTPView(GenericAPIView[Any]):
"""
Validates a TOTP code and activates the TOTP authenticator
"""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
secret = serializer.validated_data["secret"]
valid = totp_auth.validate_totp_code(
secret,
serializer.validated_data["code"],
request.data["secret"],
request.data["code"],
)
recovery_codes = None
if valid:
auth = totp_auth.TOTP.activate(
request.user,
secret,
request.data["secret"],
).instance
signals.authenticator_added.send(
sender=Authenticator,
+2 -29
View File
@@ -2,8 +2,6 @@ from django.utils.translation import gettext as _
from rest_framework import serializers
from rest_framework.exceptions import PermissionDenied
from documents.filters import INT16_MAX
from documents.filters import INT16_MIN
from documents.permissions import has_perms_owner_aware
from documents.permissions import restrict_queryset_to_visible
from documents.serialisers import CorrespondentField
@@ -19,12 +17,7 @@ from paperless_mail.models import ProcessedMail
class MailAccountSerializer(OwnedObjectSerializer):
password = ObfuscatedPasswordField()
imap_port = serializers.IntegerField(
required=True,
allow_null=False,
min_value=1,
max_value=65535,
)
imap_port = serializers.IntegerField(required=True, allow_null=False)
class Meta:
model = MailAccount
@@ -46,21 +39,6 @@ class MailAccountSerializer(OwnedObjectSerializer):
"expiration",
]
def validate(self, attrs):
attrs = super().validate(attrs)
# On an update the other half of the pair is the stored one
security = attrs.get(
"imap_security",
getattr(self.instance, "imap_security", None),
)
port = attrs.get("imap_port", getattr(self.instance, "imap_port", None))
if security == MailAccount.ImapSecurity.STARTTLS and port == 993:
# Connecting would fail every time, port 993 speaks SSL from the start
raise serializers.ValidationError(
{"imap_port": "Port 993 requires SSL, it cannot be used with STARTTLS"},
)
return attrs
def update(self, instance, validated_data):
if "password" in validated_data and is_obfuscated_password(
validated_data["password"],
@@ -92,16 +70,11 @@ class MailRuleSerializer(OwnedObjectSerializer):
allow_null=True,
required=False,
default="",
max_length=256,
)
assign_correspondent = CorrespondentField(allow_null=True, required=False)
assign_tags = TagsField(many=True, allow_null=True, required=False)
assign_document_type = DocumentTypeField(allow_null=True, required=False)
order = serializers.IntegerField(
required=False,
min_value=INT16_MIN,
max_value=INT16_MAX,
)
order = serializers.IntegerField(required=False)
class Meta:
model = MailRule
+5 -19
View File
@@ -1,5 +1,4 @@
import datetime
import imaplib
import logging
from datetime import timedelta
from http import HTTPStatus
@@ -100,11 +99,8 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]):
@action(methods=["post"], detail=False)
def test(self, request):
logger = logging.getLogger("paperless_mail")
# request.data is read only for a form encoded body, and QueryDict.copy would
# deep copy any uploaded file, so build a plain dict
data = dict(request.data.items())
data["name"] = datetime.datetime.now().isoformat()
serializer = self.get_serializer(data=data)
request.data["name"] = datetime.datetime.now().isoformat()
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
existing_account = None
account_id = request.data.get("id")
@@ -140,15 +136,7 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]):
serializer.validated_data["refresh_token"] = existing_account.refresh_token
serializer.validated_data["expiration"] = existing_account.expiration
# The serializer also carries write only fields that are not model fields
model_fields = {field.name for field in MailAccount._meta.concrete_fields}
account = MailAccount(
**{
key: value
for key, value in serializer.validated_data.items()
if key in model_fields
},
)
account = MailAccount(**serializer.validated_data)
try:
with get_mailbox(
account.imap_server,
@@ -174,11 +162,9 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]):
mailbox_login(M, account)
return Response({"success": True})
except (MailError, OSError, imaplib.IMAP4.error, UnicodeError) as exc:
# A refused connection, an unknown host, a timeout, a TLS failure or a bad
# host name is exactly what this endpoint exists to report
except MailError:
logger.error(
f"Mail account connectivity test failed: {type(exc).__name__}: {exc}",
"Mail account connectivity test failed",
)
return HttpResponseBadRequest("Unable to connect to server")
-13
View File
@@ -1,12 +1,9 @@
from __future__ import annotations
import json
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from django.http import HttpResponse
from django.http import StreamingHttpResponse
from rest_framework.test import APIClient
def read_streaming_response(response: StreamingHttpResponse) -> bytes:
@@ -14,13 +11,3 @@ def read_streaming_response(response: StreamingHttpResponse) -> bytes:
content = b"".join(response.streaming_content)
response.close()
return content
def send_json(client: APIClient, method: str, path: str, body: object) -> HttpResponse:
"""Send a request with a JSON body, any method, whatever the body is."""
return client.generic(
method,
path,
data=json.dumps(body),
content_type="application/json",
)