Compare commits

...
14 changed files with 1397 additions and 81 deletions

No files matched your search

+4 -4
View File
@@ -11,6 +11,7 @@ from typing import Final
import magic
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import transaction
from django.db.models import Max
from django.db.models import Q
@@ -1273,10 +1274,9 @@ class AsnCheckPlugin(
return
# Validate the range is above zero and less than uint32_t max
# otherwise, Whoosh can't handle it in the index
if (
self.metadata.asn < Document.ARCHIVE_SERIAL_NUMBER_MIN
or self.metadata.asn > Document.ARCHIVE_SERIAL_NUMBER_MAX
):
try:
Document.validate_archive_serial_number(self.metadata.asn)
except DjangoValidationError:
self._fail(
ConsumerStatusShortMessage.ASN_RANGE,
f"Not consuming {self.filename}: "
+9
View File
@@ -422,6 +422,15 @@ class Document(SoftDeleteModel, ModelWithOwner): # type: ignore[django-manager-
res += f" {self.title}"
return res
@classmethod
def validate_archive_serial_number(cls, value: int) -> None:
"""
Run every validator of the ASN field. Besides the fixed range above, Django
adds the range of the column for the database in use (a signed 32 bit
integer on PostgreSQL), which a serializer built from the field does not apply
"""
cls._meta.get_field("archive_serial_number").run_validators(value)
def get_effective_barcodes(self) -> list["DocumentBarcode"]:
"""
Returns the stored barcodes for the document, like
+88
View File
@@ -2,6 +2,8 @@ from drf_spectacular.extensions import OpenApiAuthenticationExtension
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter
from drf_spectacular.utils import extend_schema
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
class AngularApiAuthenticationOverrideScheme(OpenApiAuthenticationExtension):
@@ -42,3 +44,89 @@ def generate_object_with_permissions_schema(serializer_class):
)
for operation in ["list", "retrieve"]
}
HTTP_METHODS = {"get", "put", "post", "patch", "delete"}
def add_common_error_responses(result, generator, request, public):
"""
Document the errors nearly every operation can answer, so they do not have to be
declared on each view: a 400 when validation of the input fails, and a 404 when
the object named in the path, or the requested page of a list, does not exist.
Responses a view declares itself are kept as they are.
"""
for item in result.get("paths", {}).values():
for method, operation in item.items():
if method not in HTTP_METHODS:
continue
parameters = [*item.get("parameters", []), *operation.get("parameters", [])]
has_path_parameter = any(p.get("in") == "path" for p in parameters)
has_input = (
"requestBody" in operation
or has_path_parameter
or any(p.get("in") == "query" for p in parameters)
)
paginated = any(
p.get("in") == "query" and p.get("name") == "page" for p in parameters
)
responses = operation.setdefault("responses", {})
if has_input:
responses.setdefault("400", {"description": "Invalid input"})
if has_path_parameter or paginated:
responses.setdefault(
"404",
{"description": "The object or page does not exist"},
)
return result
# Fields of the objects with an owner that a response only carries sometimes: the
# permissions or the flags that replace them (see OwnedObjectSerializer), and counts a
# queryset annotates, which a response to a create or an update does not have.
CONDITIONAL_RESPONSE_FIELDS = (
"permissions",
"user_can_change",
"is_shared_by_requester",
"document_count",
"last_correspondence",
)
# Components without an owner that still carry an annotated count
COMPONENTS_WITH_ANNOTATED_COUNTS = {"CustomField"}
def make_conditional_fields_optional(result, generator, request, public):
"""
drf-spectacular lists every read only field as required in a response. For the
objects built on OwnedObjectSerializer that is wrong for the fields above, so they
are taken out of the required list of those components.
"""
for name, component in result.get("components", {}).get("schemas", {}).items():
properties = component.get("properties", {})
required = component.get("required")
owned = {"permissions", "user_can_change"} & set(properties)
if not required or not (owned or name in COMPONENTS_WITH_ANNOTATED_COUNTS):
continue
remaining = [
name for name in required if name not in CONDITIONAL_RESPONSE_FIELDS
]
if remaining:
component["required"] = remaining
else:
del component["required"]
return result
@extend_schema_field({"type": "integer", "format": "int64"})
class Int64Field(serializers.IntegerField):
"""An integer that does not fit 32 bits, for example a size in bytes."""
@extend_schema_field({"type": "string", "format": "date", "nullable": True})
class NullableDateField(serializers.DateField):
"""
A date the schema documents as nullable. allow_null would also make a response
carry an explicit null where the field is left out today.
"""
+32 -16
View File
@@ -20,6 +20,7 @@ from django.core.validators import EmailValidator
from django.core.validators import MaxLengthValidator
from django.core.validators import MaxValueValidator
from django.core.validators import MinValueValidator
from django.core.validators import RegexValidator
from django.core.validators import integer_validator
from django.db import transaction
from django.db.models import Count
@@ -93,6 +94,7 @@ from documents.permissions import permitted_object_ids
from documents.permissions import restrict_queryset_to_visible
from documents.permissions import set_permissions_for_objects
from documents.regex import validate_regex_pattern
from documents.schema import NullableDateField
from documents.templating.filepath import validate_filepath_template_and_render
from documents.templating.utils import convert_format_str_to_template_format
from documents.templating.workflows import validate_workflow_template
@@ -517,7 +519,7 @@ class OwnedObjectListSerializer(serializers.ListSerializer[Any]):
class CorrespondentSerializer(MatchingModelSerializer, OwnedObjectSerializer):
last_correspondence = serializers.DateField(read_only=True, required=False)
last_correspondence = NullableDateField(read_only=True, required=False)
class Meta:
model = Correspondent
@@ -580,11 +582,8 @@ class TagSerializer(MatchingModelSerializer, OwnedObjectSerializer):
)
@extend_schema_field(
field=serializers.ListSerializer(
child=serializers.PrimaryKeyRelatedField(
queryset=Tag.objects.all(),
),
),
# The children are nested tags, not ids
field={"type": "array", "items": {"$ref": "#/components/schemas/Tag"}},
)
def get_children(self, obj):
children_map = self.context.get("children_map")
@@ -651,12 +650,14 @@ class TagSerializer(MatchingModelSerializer, OwnedObjectSerializer):
"parent",
"children",
)
def validate_color(self, color):
regex = r"#[0-9a-fA-F]{6}"
if not re.match(regex, color):
raise serializers.ValidationError(_("Invalid color."))
return color
# A validator, so the schema publishes it as a pattern
extra_kwargs = {
"color": {
"validators": [
RegexValidator(r"^#[0-9a-fA-F]{6}$", message=_("Invalid color.")),
],
},
}
def validate(self, attrs):
# Validate when changing parent
@@ -1029,7 +1030,7 @@ class DocumentSerializer(
notes = NotesSerializer(many=True, required=False, read_only=True)
root_document: RelatedField[Document, Document, Any] | ManyRelatedField = (
serializers.PrimaryKeyRelatedField(read_only=True)
serializers.PrimaryKeyRelatedField(read_only=True, allow_null=True)
)
versions = SerializerMethodField()
@@ -1152,6 +1153,11 @@ class DocumentSerializer(
data["created"] = parsed.astimezone().date()
return super().to_internal_value(data)
def validate_archive_serial_number(self, value):
if value is not None:
Document.validate_archive_serial_number(value)
return value
def validate(self, attrs):
if (
"archive_serial_number" in attrs
@@ -1490,6 +1496,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(
@@ -1846,14 +1859,13 @@ class RunZoneOcrResponseSerializer(serializers.Serializer[dict[str, Any]]):
read_only=True,
help_text="OK when the run was queued, skipped when it was not.",
)
# Not read only: spectacular lists every read only field of a response as required
task_id = serializers.CharField(
read_only=True,
required=False,
help_text="The queued task. Absent when the run was skipped.",
)
reason = serializers.ChoiceField(
choices=[reason.value for reason in ZoneOcrSkipReason],
read_only=True,
required=False,
help_text="Present only when the run was skipped.",
)
@@ -1862,7 +1874,10 @@ class RunZoneOcrResponseSerializer(serializers.Serializer[dict[str, Any]]):
class OcrErrorSerializer(serializers.Serializer[dict[str, Any]]):
"""The body of an error response from the OCR template actions."""
error = serializers.CharField(read_only=True)
# Not read only: spectacular lists every read only field of a response as required.
# A 404 from a missing document has a detail instead of an error.
error = serializers.CharField(required=False)
detail = serializers.CharField(required=False)
class RunZoneOcrDocumentsSerializer(DocumentSelectionSerializer, RunZoneOcrSerializer):
@@ -2400,6 +2415,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
required=False,
min_value=Document.ARCHIVE_SERIAL_NUMBER_MIN,
max_value=Document.ARCHIVE_SERIAL_NUMBER_MAX,
validators=[Document.validate_archive_serial_number],
)
# Accept either a list of custom field ids or a dict mapping id -> value
@@ -0,0 +1,97 @@
from collections.abc import Generator
import pytest
from django.core.exceptions import ValidationError
from django.db import connection
from pytest_mock import MockerFixture
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import Document
from paperless_testing.factories import DocumentFactory
SIGNED_INT32_RANGE = (-(2**31), 2**31 - 1)
@pytest.fixture
def signed_int32_column(mocker: MockerFixture) -> Generator[None, None, None]:
"""
Make the database report a signed 32 bit integer range for the column, as
PostgreSQL does. Django caches the validators of a field, so the cache is
dropped before and after.
"""
field = Document._meta.get_field("archive_serial_number")
field.__dict__.pop("validators", None)
mocker.patch.object(
connection.ops,
"integer_field_range",
return_value=SIGNED_INT32_RANGE,
)
yield
field.__dict__.pop("validators", None)
class TestArchiveSerialNumberRange:
@pytest.mark.usefixtures("signed_int32_column")
@pytest.mark.parametrize("value", [2**31, 3_000_000_000, 0xFF_FF_FF_FF])
def test_value_beyond_the_column_is_rejected(self, value: int) -> None:
"""
GIVEN:
- A database whose integer column stops at 2**31 - 1
WHEN:
- An ASN inside the fixed range but beyond the column is validated
THEN:
- It is rejected, the database would have raised an error
"""
with pytest.raises(ValidationError):
Document.validate_archive_serial_number(value)
@pytest.mark.usefixtures("signed_int32_column")
@pytest.mark.parametrize("value", [0, 1, 2**31 - 1])
def test_value_within_the_column_is_accepted(self, value: int) -> None:
"""
GIVEN:
- A database whose integer column stops at 2**31 - 1
WHEN:
- An ASN inside the column is validated
THEN:
- It is accepted
"""
Document.validate_archive_serial_number(value)
@pytest.mark.parametrize("value", [-1, 0xFF_FF_FF_FF + 1])
def test_value_outside_the_fixed_range_is_rejected(self, value: int) -> None:
"""
GIVEN:
- The fixed ASN range
WHEN:
- A value outside of it is validated
THEN:
- It is rejected whatever the database
"""
with pytest.raises(ValidationError):
Document.validate_archive_serial_number(value)
@pytest.mark.usefixtures("signed_int32_column")
def test_api_answers_400_for_a_value_beyond_the_column(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- A document and a database whose integer column stops at 2**31 - 1
WHEN:
- The document is patched with a larger ASN
THEN:
- The response is a 400 naming the field, not a database error
"""
document = DocumentFactory.create()
response = admin_client.patch(
f"/api/documents/{document.pk}/",
{"archive_serial_number": 3_000_000_000},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "archive_serial_number" in response.data
@@ -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
@@ -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
+465
View File
@@ -5,6 +5,7 @@ from django.core.management import call_command
from django.core.management.base import CommandError
from drf_spectacular.generators import SchemaGenerator
from rest_framework import status
from rest_framework.test import APIClient
from rest_framework.test import APITestCase
@@ -341,6 +342,276 @@ class TestDocumentListObjectFilterSchema:
assert param["explode"] is False
class TestCommonErrorResponsesSchema:
def test_detail_operations_document_400_and_404(
self,
api_schema: dict[str, Any],
) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The detail operations of a resource are read
THEN:
- A 400 and a 404 are documented, no view declares them itself
"""
operation = api_schema["paths"]["/api/tags/{id}/"]["patch"]
assert "400" in operation["responses"]
assert "404" in operation["responses"]
def test_paginated_list_documents_404_for_a_missing_page(
self,
api_schema: dict[str, Any],
) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- A paginated list operation is read
THEN:
- A 404 is documented, an out of range page answers one
"""
responses = api_schema["paths"]["/api/tags/"]["get"]["responses"]
assert "404" in responses
def test_operation_without_input_has_no_400(
self,
api_schema: dict[str, Any],
) -> None:
"""
GIVEN:
- An operation with no parameters and no body
WHEN:
- Its responses are read
THEN:
- No 400 is added, there is no input to reject
"""
responses = api_schema["paths"]["/api/status/"]["get"]["responses"]
assert "400" not in responses
assert "404" not in responses
def test_responses_declared_by_a_view_are_kept(
self,
api_schema: dict[str, Any],
) -> None:
"""
GIVEN:
- An operation whose view documents its own 400
WHEN:
- Its responses are read
THEN:
- The description of the view is kept
"""
responses = api_schema["paths"]["/api/oauth/callback/"]["get"]["responses"]
assert responses["400"]["description"] != "Invalid input"
class TestDocumentFileContentTypesSchema:
@pytest.mark.parametrize(
("path", "content_type"),
[
("/api/documents/{id}/download/", "*/*"),
("/api/documents/{id}/preview/", "*/*"),
("/api/documents/{id}/thumb/", "image/webp"),
],
)
def test_file_endpoints_declare_the_real_content_type(
self,
api_schema: dict[str, Any],
path: str,
content_type: str,
) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The 200 response of a document file endpoint is read
THEN:
- It declares the content type it is served with, not JSON
"""
content = api_schema["paths"][path]["get"]["responses"]["200"]["content"]
assert list(content) == [content_type]
class TestConditionalResponseFieldsSchema:
@pytest.mark.parametrize(
"component",
["Tag", "Correspondent", "DocumentType", "StoragePath", "Document"],
)
def test_fields_present_only_sometimes_are_not_required(
self,
api_schema: dict[str, Any],
component: str,
) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The response component of an owned object is read
THEN:
- Permissions, the permission flags and the annotated counts are not
required, a create or update response and a response without full_perms
do not carry them
"""
schema = api_schema["components"]["schemas"][component]
required = set(schema.get("required", []))
assert required.isdisjoint(
{
"permissions",
"user_can_change",
"is_shared_by_requester",
"document_count",
"last_correspondence",
},
)
assert "id" in required
def test_fields_of_other_components_stay_required(
self,
api_schema: dict[str, Any],
) -> None:
"""
GIVEN:
- A response component that is not an owned object but has a count
WHEN:
- Its required fields are read
THEN:
- The count is still required, it is always present
"""
schema = api_schema["components"]["schemas"]["ShareLinkBundle"]
assert "document_count" in schema["required"]
class TestSystemStatusSchema:
def test_status_fields_match_the_response(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The system status response is read
THEN:
- The index, classifier and sanity check fields are inside tasks, as the
view returns them, and storage sizes are 64 bit
"""
schemas = api_schema["components"]["schemas"]
status_schema = schemas["SystemStatus"]
tasks = schemas["Tasks"]["properties"]
assert set(status_schema["properties"]) == {
"pngx_version",
"server_os",
"install_type",
"storage",
"database",
"tasks",
}
assert {
"index_status",
"classifier_last_trained",
"sanity_check_error",
"llmindex_status",
} <= set(tasks)
assert schemas["Storage"]["properties"]["total"]["format"] == "int64"
class TestUiSettingsSchema:
def test_get_response_has_user_settings_and_permissions(
self,
api_schema: dict[str, Any],
) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The response of GET /api/ui_settings/ is read
THEN:
- It has the user, settings and permissions the view returns, and no
request body
"""
operation = api_schema["paths"]["/api/ui_settings/"]["get"]
response = operation["responses"]["200"]["content"]["application/json"]
assert "requestBody" not in operation
assert response["schema"]["$ref"].endswith("/UiSettingsResponse")
properties = api_schema["components"]["schemas"]["UiSettingsResponse"][
"properties"
]
assert set(properties) == {"user", "settings", "permissions"}
class TestRunZoneOcrResponseSchema:
def test_task_id_and_reason_are_optional(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The response of run-zone-ocr is read
THEN:
- Only the result is required, task_id is absent when the run was
skipped and the reason is absent when it was queued
"""
schema = api_schema["components"]["schemas"]["RunZoneOcrResponse"]
assert schema["required"] == ["result"]
class TestDocumentShareLinksSchema:
def test_response_is_a_list_of_share_links(
self,
api_schema: dict[str, Any],
) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The response of the share links of a document is read
THEN:
- It is the share link serializer, which allows a null expiration
"""
operation = api_schema["paths"]["/api/documents/{id}/share_links/"]["get"]
items = operation["responses"]["200"]["content"]["application/json"]["schema"][
"items"
]
assert items["$ref"].endswith("/ShareLink")
class TestTagChildrenAndHistorySchema:
def test_tag_children_are_nested_tags(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The children of a tag are read
THEN:
- They are tags, the API nests the objects and does not return ids
"""
children = api_schema["components"]["schemas"]["Tag"]["properties"]["children"]
assert children["items"] == {"$ref": "#/components/schemas/Tag"}
def test_history_is_an_unpaginated_list(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The history response of a document is read
THEN:
- It is a plain array of log entries, the view does not paginate
"""
operation = api_schema["paths"]["/api/documents/{id}/history/"]["get"]
schema = operation["responses"]["200"]["content"]["application/json"]["schema"]
assert schema["type"] == "array"
class TestOauthCallbackSchema:
@pytest.mark.parametrize("name", ["code", "state"])
def test_empty_code_and_state_are_not_schema_valid(
@@ -363,6 +634,200 @@ class TestOauthCallbackSchema:
assert param["schema"]["minLength"] == 1
class TestRemainingResponseShapesSchema:
def test_logs_limit_must_be_positive(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The limit parameter of the log endpoint is read
THEN:
- It has a minimum of 1, the view rejects anything lower
"""
params = api_schema["paths"]["/api/logs/{id}/"]["get"]["parameters"]
limit = next(p for p in params if p["name"] == "limit")
assert limit["schema"]["minimum"] == 1
@pytest.mark.parametrize("name", ["since", "until"])
def test_release_notes_versions_have_a_pattern(
self,
api_schema: dict[str, Any],
name: str,
) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The version parameters of the release notes are read
THEN:
- They are patterned like a version, anything else answers a 400
"""
params = api_schema["paths"]["/api/release_notes/"]["get"]["parameters"]
param = next(p for p in params if p["name"] == name)
assert "pattern" in param["schema"]
def test_deactivate_totp_404_is_html(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The 404 of deactivate_totp is read
THEN:
- It is text, the view answers with a plain not found response
"""
responses = api_schema["paths"]["/api/users/{id}/deactivate_totp/"]["post"][
"responses"
]
assert list(responses["404"]["content"]) == ["text/html"]
def test_ocr_error_body_has_no_required_fields(
self,
api_schema: dict[str, Any],
) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The error body of the OCR actions is read
THEN:
- Neither error nor detail is required, a missing document answers with
a detail and the actions answer with an error
"""
schema = api_schema["components"]["schemas"]["OcrError"]
assert "required" not in schema
assert {"error", "detail"} <= set(schema["properties"])
def test_nullable_response_fields(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The root document of a document and the last correspondence of a
correspondent are read
THEN:
- Both are nullable, a root document has no root and a correspondent
may have no documents
"""
schemas = api_schema["components"]["schemas"]
assert schemas["Document"]["properties"]["root_document"]["nullable"] is True
assert (
schemas["Correspondent"]["properties"]["last_correspondence"]["nullable"]
is True
)
def test_custom_field_count_is_optional(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The custom field response is read
THEN:
- document_count is not required, a create response does not have it
"""
required = api_schema["components"]["schemas"]["CustomField"]["required"]
assert "document_count" not in required
class TestSearchAndMailTestSchema:
def test_autocomplete_term_is_required(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The term parameter of autocomplete is read
THEN:
- It is required, the view answers 400 without it
"""
params = api_schema["paths"]["/api/search/autocomplete/"]["get"]["parameters"]
term = next(p for p in params if p["name"] == "term")
assert term["required"] is True
def test_global_search_query_has_a_minimum_length(
self,
api_schema: dict[str, Any],
) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The query parameter of the global search is read
THEN:
- It has a minimum length of 3, the view answers 400 to a shorter one
"""
params = api_schema["paths"]["/api/search/"]["get"]["parameters"]
query = next(p for p in params if p["name"] == "query")
assert query["schema"]["minLength"] == 3
def test_mail_account_test_400_is_html(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The 400 of the mail account test is read
THEN:
- It is text, the view answers with a plain bad request response
"""
responses = api_schema["paths"]["/api/mail_accounts/test/"]["post"]["responses"]
assert list(responses["400"]["content"]) == ["text/html"]
class TestTagColorSchema:
def test_color_has_a_hex_pattern(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The color of a tag request is read
THEN:
- It has a hex pattern, the serializer rejects anything else
"""
color = api_schema["components"]["schemas"]["TagRequest"]["properties"]["color"]
assert color["pattern"] == "^#[0-9a-fA-F]{6}$"
@pytest.mark.parametrize(
("color", "expected"),
[
("#a6cee3", 201),
("#A6CEE3", 201),
("a6cee3", 400),
("#a6cee", 400),
("#a6ceez", 400),
("#a6cee3x", 400),
],
)
def test_color_validation_is_unchanged(
self,
admin_client: APIClient,
color: str,
expected: int,
) -> None:
"""
GIVEN:
- A tag request
WHEN:
- It is created with a valid or an invalid color
THEN:
- Only a # followed by six hex digits is accepted
"""
response = admin_client.post(
"/api/tags/",
{"name": "colored", "color": color},
format="json",
)
assert response.status_code == expected
class TestOcrPageImageSchema:
def test_page_image_is_declared_as_png(self, api_schema: dict[str, Any]) -> None:
"""
+104 -52
View File
@@ -198,6 +198,7 @@ from documents.permissions import set_permissions_for_objects
from documents.permissions import user_is_unrestricted
from documents.plugins.date_parsing import get_date_parser
from documents.regex import safe_regex_fullmatch
from documents.schema import Int64Field
from documents.schema import generate_object_with_permissions_schema
from documents.search import SearchHit
from documents.serialisers import AcknowledgeTasksViewSerializer
@@ -766,7 +767,8 @@ class EmailDocumentDetailSchema(EmailSerializer):
location=OpenApiParameter.QUERY,
),
],
responses={200: OpenApiTypes.BINARY},
# The file is served with its own mime type
responses={(200, "*/*"): OpenApiTypes.BINARY},
),
history=extend_schema(
description="View the document history",
@@ -785,6 +787,7 @@ class EmailDocumentDetailSchema(EmailSerializer):
"id": serializers.IntegerField(),
"username": serializers.CharField(),
},
allow_null=True,
),
},
),
@@ -933,11 +936,11 @@ class EmailDocumentDetailSchema(EmailSerializer):
),
thumb=extend_schema(
description="View the document thumbnail",
responses={200: OpenApiTypes.BINARY},
responses={(200, "image/webp"): OpenApiTypes.BINARY},
),
preview=extend_schema(
description="View the document preview",
responses={200: OpenApiTypes.BINARY},
responses={(200, "*/*"): OpenApiTypes.BINARY},
),
share_links=extend_schema(
operation_id="document_share_links",
@@ -950,18 +953,7 @@ class EmailDocumentDetailSchema(EmailSerializer):
),
],
responses={
200: {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {"type": "integer"},
"created": {"type": "string", "format": "date-time"},
"expiration": {"type": "string", "format": "date-time"},
"slug": {"type": "string"},
},
},
},
200: ShareLinkSerializer(many=True),
400: None,
403: None,
404: None,
@@ -2010,7 +2002,12 @@ class DocumentViewSet(
},
)
@action(methods=["get"], detail=True, filter_backends=[])
@action(
methods=["get"],
detail=True,
filter_backends=[],
pagination_class=None,
)
def share_links(self, request, pk=None):
currentUser = request.user
try:
@@ -2046,7 +2043,13 @@ class DocumentViewSet(
serializer = ShareLinkSerializer(links, many=True)
return Response(serializer.data)
@action(methods=["get"], detail=True, name="Audit Trail", filter_backends=[])
@action(
methods=["get"],
detail=True,
name="Audit Trail",
filter_backends=[],
pagination_class=None,
)
def history(self, request, pk=None):
if not settings.AUDIT_LOG_ENABLED:
return HttpResponseBadRequest("Audit log is disabled")
@@ -2120,8 +2123,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(
@@ -2925,7 +2929,7 @@ LOG_FILES = {
),
OpenApiParameter(
name="limit",
type=OpenApiTypes.INT,
type={"type": "integer", "minimum": 1},
location=OpenApiParameter.QUERY,
description="Return only the last N entries from the log file",
required=False,
@@ -3724,7 +3728,7 @@ class SelectionDataView(DocumentSelectionMixin, GenericAPIView[Any]):
parameters=[
OpenApiParameter(
name="term",
required=False,
required=True,
type=str,
description="Term to search for",
),
@@ -3775,7 +3779,8 @@ class SearchAutoCompleteView(GenericAPIView[Any]):
OpenApiParameter(
name="query",
required=True,
type=str,
# Shorter queries are answered with a 400
type={"type": "string", "minLength": 3},
description="Query to search for",
),
OpenApiParameter(
@@ -4318,6 +4323,46 @@ class StoragePathViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Storag
return Response(result)
@extend_schema_view(
get=extend_schema(
description="The UI settings of the current user, merged with the settings of the server and the current user and permissions",
request=None,
responses={
(200, "application/json"): inline_serializer(
name="UiSettingsResponse",
fields={
"user": inline_serializer(
name="UiSettingsUser",
fields={
"id": serializers.IntegerField(),
"username": serializers.CharField(),
"is_staff": serializers.BooleanField(),
"is_superuser": serializers.BooleanField(),
"groups": serializers.ListField(
child=serializers.IntegerField(),
),
"first_name": serializers.CharField(required=False),
"last_name": serializers.CharField(required=False),
},
),
"settings": serializers.DictField(),
"permissions": serializers.ListField(
child=serializers.CharField(),
),
},
),
},
),
post=extend_schema(
description="Save the UI settings of the current user",
responses={
(200, "application/json"): inline_serializer(
name="UiSettingsSaveResult",
fields={"success": serializers.BooleanField()},
),
},
),
)
class UiSettingsView(GenericAPIView[Any]):
queryset = UiSettings.objects.all()
permission_classes = (IsAuthenticated, PaperlessObjectPermissions)
@@ -4601,6 +4646,11 @@ class RemoteVersionView(GenericAPIView[Any]):
)
VERSION_PATTERN = (
r"^v?[0-9]+(\.[0-9]+){0,3}((a|b|rc)[0-9]+)?(\.post[0-9]+)?(\.dev[0-9]+)?$"
)
@extend_schema_view(
get=extend_schema(
description=(
@@ -4611,13 +4661,15 @@ class RemoteVersionView(GenericAPIView[Any]):
parameters=[
OpenApiParameter(
name="since",
type=OpenApiTypes.STR,
# A version number, anything else is answered with a 400
type={"type": "string", "pattern": VERSION_PATTERN},
location=OpenApiParameter.QUERY,
required=False,
),
OpenApiParameter(
name="until",
type=OpenApiTypes.STR,
# A version number, anything else is answered with a 400
type={"type": "string", "pattern": VERSION_PATTERN},
location=OpenApiParameter.QUERY,
required=False,
),
@@ -5548,8 +5600,8 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
"storage": inline_serializer(
name="Storage",
fields={
"total": serializers.IntegerField(),
"available": serializers.IntegerField(),
"total": Int64Field(),
"available": Int64Field(),
},
),
"database": inline_serializer(
@@ -5558,7 +5610,7 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
"type": serializers.CharField(),
"url": serializers.CharField(),
"status": serializers.CharField(),
"error": serializers.CharField(),
"error": serializers.CharField(allow_null=True),
"migration_status": inline_serializer(
name="MigrationStatus",
fields={
@@ -5577,8 +5629,32 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
fields={
"redis_url": serializers.CharField(),
"redis_status": serializers.CharField(),
"redis_error": serializers.CharField(),
"redis_error": serializers.CharField(allow_null=True),
"celery_status": serializers.CharField(),
"celery_url": serializers.CharField(allow_null=True),
"celery_error": serializers.CharField(allow_null=True),
"index_status": serializers.CharField(),
"index_last_modified": serializers.DateTimeField(
allow_null=True,
),
"index_error": serializers.CharField(allow_null=True),
"classifier_status": serializers.CharField(),
"classifier_last_trained": serializers.DateTimeField(
allow_null=True,
),
"classifier_error": serializers.CharField(allow_null=True),
"sanity_check_status": serializers.CharField(),
"sanity_check_last_run": serializers.DateTimeField(
allow_null=True,
),
"sanity_check_error": serializers.CharField(
allow_null=True,
),
"llmindex_status": serializers.CharField(),
"llmindex_last_modified": serializers.DateTimeField(
allow_null=True,
),
"llmindex_error": serializers.CharField(allow_null=True),
"summary": inline_serializer(
name="TasksSummaryOverview",
fields={
@@ -5591,30 +5667,6 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
),
},
),
"index": inline_serializer(
name="Index",
fields={
"status": serializers.CharField(),
"error": serializers.CharField(),
"last_modified": serializers.DateTimeField(),
},
),
"classifier": inline_serializer(
name="Classifier",
fields={
"status": serializers.CharField(),
"error": serializers.CharField(),
"last_trained": serializers.DateTimeField(),
},
),
"sanity_check": inline_serializer(
name="SanityCheck",
fields={
"status": serializers.CharField(),
"error": serializers.CharField(),
"last_run": serializers.DateTimeField(),
},
),
},
),
},
+4
View File
@@ -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
+5
View File
@@ -237,6 +237,11 @@ SPECTACULAR_SETTINGS = {
"NoteFormatEnum": "documents.models.Note.Format",
},
"SCHEMA_PATH_PREFIX_INSERT": FORCE_SCRIPT_NAME or "",
"POSTPROCESSING_HOOKS": [
"drf_spectacular.hooks.postprocess_schema_enums",
"documents.schema.add_common_error_responses",
"documents.schema.make_conditional_fields_optional",
],
}
WSGI_APPLICATION = "paperless.wsgi.application"
+10 -3
View File
@@ -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
@@ -211,17 +212,23 @@ class UserViewSet(ModelViewSet[User]):
request=None,
responses={
200: OpenApiTypes.BOOL,
404: OpenApiTypes.STR,
(404, "text/html"): OpenApiTypes.STR,
},
)
@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,
+15
View File
@@ -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"],
+20 -6
View File
@@ -1,4 +1,5 @@
import datetime
import imaplib
import logging
from datetime import timedelta
from http import HTTPStatus
@@ -66,7 +67,7 @@ class DeleteProcessedMailPermissions(BasePermission):
name="MailAccountTestResponse",
fields={"success": serializers.BooleanField()},
),
400: OpenApiTypes.STR,
(400, "text/html"): OpenApiTypes.STR,
},
),
process=extend_schema(
@@ -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")