From 416161dd1e8397fefcf6ffd9b3cc8d6e15c02542 Mon Sep 17 00:00:00 2001 From: Trenton H <797416+stumpylog@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:08:43 -0800 Subject: [PATCH] Fix: handle form and JSON request data correctly in email, mail test, config and saved view requests, and report mail connection failures as a 400 --- src/documents/serialisers.py | 7 + .../tests/test_api_mail_account_security.py | 139 ++++++ .../tests/test_api_request_data_handling.py | 405 ++++++++++++++++++ src/documents/views.py | 5 +- src/paperless/serialisers.py | 4 + src/paperless/views.py | 11 +- src/paperless_mail/serialisers.py | 15 + src/paperless_mail/views.py | 24 +- 8 files changed, 601 insertions(+), 9 deletions(-) create mode 100644 src/documents/tests/test_api_mail_account_security.py create mode 100644 src/documents/tests/test_api_request_data_handling.py diff --git a/src/documents/serialisers.py b/src/documents/serialisers.py index 4a56d2fa9..e4bfbee9e 100644 --- a/src/documents/serialisers.py +++ b/src/documents/serialisers.py @@ -1490,6 +1490,13 @@ 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( diff --git a/src/documents/tests/test_api_mail_account_security.py b/src/documents/tests/test_api_mail_account_security.py new file mode 100644 index 000000000..c3d34238e --- /dev/null +++ b/src/documents/tests/test_api_mail_account_security.py @@ -0,0 +1,139 @@ +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 diff --git a/src/documents/tests/test_api_request_data_handling.py b/src/documents/tests/test_api_request_data_handling.py new file mode 100644 index 000000000..463089ac2 --- /dev/null +++ b/src/documents/tests/test_api_request_data_handling.py @@ -0,0 +1,405 @@ +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 diff --git a/src/documents/views.py b/src/documents/views.py index b9234bd61..d71668cf2 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -2120,8 +2120,9 @@ class DocumentViewSet( ) # TODO: deprecated, remove with drop of support for API v9 def email_document(self, request, pk=None): - request_data = request.data.copy() - request_data.setlist("documents", [pk]) + # 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] return self.email_documents(request, data=request_data) @action( diff --git a/src/paperless/serialisers.py b/src/paperless/serialisers.py index cac2984a5..a9de6f329 100644 --- a/src/paperless/serialisers.py +++ b/src/paperless/serialisers.py @@ -15,6 +15,7 @@ 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 @@ -284,6 +285,9 @@ 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 diff --git a/src/paperless/views.py b/src/paperless/views.py index 27276468e..f20b55266 100644 --- a/src/paperless/views.py +++ b/src/paperless/views.py @@ -34,6 +34,7 @@ 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 @@ -217,11 +218,17 @@ class UserViewSet(ModelViewSet[User]): @action(detail=True, methods=["post"]) def deactivate_totp(self, request, pk=None): request_user = request.user - user = User.objects.get(pk=pk) - if not request_user.is_superuser and request_user != 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: 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, diff --git a/src/paperless_mail/serialisers.py b/src/paperless_mail/serialisers.py index d1dd66389..e396347e6 100644 --- a/src/paperless_mail/serialisers.py +++ b/src/paperless_mail/serialisers.py @@ -46,6 +46,21 @@ 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"], diff --git a/src/paperless_mail/views.py b/src/paperless_mail/views.py index 190828f2f..7300abcb0 100644 --- a/src/paperless_mail/views.py +++ b/src/paperless_mail/views.py @@ -1,4 +1,5 @@ import datetime +import imaplib import logging from datetime import timedelta from http import HTTPStatus @@ -99,8 +100,11 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]): @action(methods=["post"], detail=False) def test(self, request): logger = logging.getLogger("paperless_mail") - request.data["name"] = datetime.datetime.now().isoformat() - serializer = self.get_serializer(data=request.data) + # 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) serializer.is_valid(raise_exception=True) existing_account = None account_id = request.data.get("id") @@ -136,7 +140,15 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]): serializer.validated_data["refresh_token"] = existing_account.refresh_token serializer.validated_data["expiration"] = existing_account.expiration - account = MailAccount(**serializer.validated_data) + # 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 + }, + ) try: with get_mailbox( account.imap_server, @@ -162,9 +174,11 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]): mailbox_login(M, account) return Response({"success": True}) - except MailError: + 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 logger.error( - "Mail account connectivity test failed", + f"Mail account connectivity test failed: {type(exc).__name__}: {exc}", ) return HttpResponseBadRequest("Unable to connect to server")