mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-30 00:33:19 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b150c1292 | ||
|
|
f895fd369e |
No files matched your search
@@ -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}: "
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
"""
|
||||
@@ -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
|
||||
@@ -1853,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.",
|
||||
)
|
||||
@@ -1869,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):
|
||||
@@ -2407,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
|
||||
@@ -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:
|
||||
"""
|
||||
|
||||
+101
-50
@@ -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")
|
||||
@@ -2926,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,
|
||||
@@ -3725,7 +3728,7 @@ class SelectionDataView(DocumentSelectionMixin, GenericAPIView[Any]):
|
||||
parameters=[
|
||||
OpenApiParameter(
|
||||
name="term",
|
||||
required=False,
|
||||
required=True,
|
||||
type=str,
|
||||
description="Term to search for",
|
||||
),
|
||||
@@ -3776,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(
|
||||
@@ -4319,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)
|
||||
@@ -4602,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=(
|
||||
@@ -4612,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,
|
||||
),
|
||||
@@ -5549,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(
|
||||
@@ -5559,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={
|
||||
@@ -5578,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={
|
||||
@@ -5592,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(),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -212,7 +212,7 @@ class UserViewSet(ModelViewSet[User]):
|
||||
request=None,
|
||||
responses={
|
||||
200: OpenApiTypes.BOOL,
|
||||
404: OpenApiTypes.STR,
|
||||
(404, "text/html"): OpenApiTypes.STR,
|
||||
},
|
||||
)
|
||||
@action(detail=True, methods=["post"])
|
||||
|
||||
@@ -67,7 +67,7 @@ class DeleteProcessedMailPermissions(BasePermission):
|
||||
name="MailAccountTestResponse",
|
||||
fields={"success": serializers.BooleanField()},
|
||||
),
|
||||
400: OpenApiTypes.STR,
|
||||
(400, "text/html"): OpenApiTypes.STR,
|
||||
},
|
||||
),
|
||||
process=extend_schema(
|
||||
|
||||
Reference in new issue
Block a user