Compare commits

...
7 changed files with 86 additions and 27 deletions

No files matched your search

+7 -2
View File
@@ -74,6 +74,10 @@ _LOCK_BACKOFF_CAP: Final[float] = 10.0 # seconds
T = TypeVar("T") T = TypeVar("T")
# Upper bound on autocomplete suggestions. tantivy sizes its collector from the
# requested limit, so an unbounded value aborts the whole process on allocation.
MAX_AUTOCOMPLETE_LIMIT = 1000
class ViewerGrant(NamedTuple): class ViewerGrant(NamedTuple):
"""Direct user and group view grants for a single document. """Direct user and group view grants for a single document.
@@ -998,7 +1002,8 @@ class TantivyBackend:
Args: Args:
term: Prefix to match against autocomplete words term: Prefix to match against autocomplete words
limit: Maximum number of suggestions to return limit: Maximum number of suggestions to return, capped at
MAX_AUTOCOMPLETE_LIMIT
user: User for permission filtering (None for no filtering) user: User for permission filtering (None for no filtering)
Returns: Returns:
@@ -1021,7 +1026,7 @@ class TantivyBackend:
"autocomplete_word", "autocomplete_word",
normalized_term, normalized_term,
permission_query, permission_query,
limit, min(limit, MAX_AUTOCOMPLETE_LIMIT),
) )
return [x[0] for x in matches] return [x[0] for x in matches]
+8 -3
View File
@@ -112,6 +112,10 @@ if TYPE_CHECKING:
logger = logging.getLogger("paperless.serializers") logger = logging.getLogger("paperless.serializers")
# How much of an upload is read to detect its type. libmagic examines at most
# 7 MiB (its default bytes_max), so this is more than it will ever look at.
_MIME_SNIFF_BYTES = 8 * 1024 * 1024
# https://www.django-rest-framework.org/api-guide/serializers/#example # https://www.django-rest-framework.org/api-guide/serializers/#example
class DynamicFieldsModelSerializer(serializers.ModelSerializer[Any]): class DynamicFieldsModelSerializer(serializers.ModelSerializer[Any]):
@@ -2363,8 +2367,9 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
) )
def validate_document(self, document): def validate_document(self, document):
document_data = document.file.read() # libmagic only examines a bounded prefix, so an upload of any size is
mime_type = magic.from_buffer(document_data, mime=True) # never read into memory just to detect its type
mime_type = magic.from_buffer(document.read(_MIME_SNIFF_BYTES), mime=True)
if not is_mime_type_supported(mime_type): if not is_mime_type_supported(mime_type):
if ( if (
@@ -2380,7 +2385,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
_("File type %(type)s not supported") % {"type": mime_type}, _("File type %(type)s not supported") % {"type": mime_type},
) )
return document.name, document_data return document.name, document
def validate_correspondent(self, correspondent): def validate_correspondent(self, correspondent):
if correspondent: if correspondent:
@@ -1069,6 +1069,13 @@ class TestAutocomplete:
results = backend.autocomplete("micro", limit=10) results = backend.autocomplete("micro", limit=10)
assert "microsoft" in results assert "microsoft" in results
def test_huge_limit_is_clamped(self, backend: TantivyBackend) -> None:
"""An oversized limit must be capped, not handed to tantivy as-is."""
doc = DocumentFactory.create(title="Microsoft invoice", content="payment")
backend.add_or_update(doc)
assert "microsoft" in backend.autocomplete("micro", limit=10**15)
def test_results_ordered_by_document_frequency( def test_results_ordered_by_document_frequency(
self, self,
backend: TantivyBackend, backend: TantivyBackend,
+32
View File
@@ -2089,6 +2089,38 @@ class TestDocumentApi(DirectoriesMixin, ConsumeTaskMixin, APITestCase):
self.assertIsNone(overrides.document_type_id) self.assertIsNone(overrides.document_type_id)
self.assertIsNone(overrides.tag_ids) self.assertIsNone(overrides.tag_ids)
def test_upload_type_is_detected_from_a_prefix(self) -> None:
"""
GIVEN:
- An upload larger than the prefix read to detect its type
WHEN:
- The document is posted
THEN:
- The type is detected from the prefix and the upload is accepted
- The file handed to the consumer holds the whole upload
"""
self.consume_file_mock.return_value = celery.result.AsyncResult(
id=str(uuid.uuid4()),
)
content = SIMPLE_DIGITAL_PDF.read_bytes()
with (
mock.patch("documents.serialisers._MIME_SNIFF_BYTES", 1024),
SimpleUploadedFile(
"simple.pdf",
content,
content_type="application/pdf",
) as f,
):
response = self.client.post(
"/api/documents/post_document/",
{"document": f},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
input_doc, _ = self.assert_queue_consumption_task_call_args()
self.assertEqual(input_doc.original_file.read_bytes(), content)
def test_upload_with_path_traversal_filename_is_reduced_to_basename(self) -> None: def test_upload_with_path_traversal_filename_is_reduced_to_basename(self) -> None:
self.consume_file_mock.return_value = celery.result.AsyncResult( self.consume_file_mock.return_value = celery.result.AsyncResult(
id=str(uuid.uuid4()), id=str(uuid.uuid4()),
+3
View File
@@ -996,6 +996,9 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
response = self.client.get("/api/search/autocomplete/?term=test&limit=-1") response = self.client.get("/api/search/autocomplete/?term=test&limit=-1")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
response = self.client.get("/api/search/autocomplete/?term=test&limit=null")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
response = self.client.get("/api/search/autocomplete/") response = self.client.get("/api/search/autocomplete/")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+11 -4
View File
@@ -2205,7 +2205,7 @@ class DocumentViewSet(
raise Http404 raise Http404
try: try:
doc_name, doc_data = serializer.validated_data.get("document") doc_name, doc_file = serializer.validated_data.get("document")
version_label = serializer.validated_data.get("version_label") version_label = serializer.validated_data.get("version_label")
t = int(mktime(datetime.now().timetuple())) t = int(mktime(datetime.now().timetuple()))
@@ -2216,7 +2216,9 @@ class DocumentViewSet(
pathvalidate.sanitize_filename(doc_name), pathvalidate.sanitize_filename(doc_name),
) )
temp_file_path.write_bytes(doc_data) with temp_file_path.open("wb") as scratch_file:
for chunk in doc_file.chunks():
scratch_file.write(chunk)
os.utime(temp_file_path, times=(t, t)) os.utime(temp_file_path, times=(t, t))
@@ -3498,7 +3500,7 @@ class PostDocumentView(GenericAPIView[Any]):
serializer = self.get_serializer(data=request.data) serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True) serializer.is_valid(raise_exception=True)
doc_name, doc_data = serializer.validated_data.get("document") doc_name, doc_file = serializer.validated_data.get("document")
doc_name = normalize("NFC", doc_name) doc_name = normalize("NFC", doc_name)
correspondent_id = serializer.validated_data.get("correspondent") correspondent_id = serializer.validated_data.get("correspondent")
document_type_id = serializer.validated_data.get("document_type") document_type_id = serializer.validated_data.get("document_type")
@@ -3518,7 +3520,9 @@ class PostDocumentView(GenericAPIView[Any]):
pathvalidate.sanitize_filename(doc_name), pathvalidate.sanitize_filename(doc_name),
) )
temp_file_path.write_bytes(doc_data) with temp_file_path.open("wb") as scratch_file:
for chunk in doc_file.chunks():
scratch_file.write(chunk)
os.utime(temp_file_path, times=(t, t)) os.utime(temp_file_path, times=(t, t))
@@ -3733,7 +3737,10 @@ class SearchAutoCompleteView(GenericAPIView[Any]):
return HttpResponseBadRequest("Term required") return HttpResponseBadRequest("Term required")
if "limit" in request.query_params: if "limit" in request.query_params:
try:
limit = int(request.query_params["limit"]) limit = int(request.query_params["limit"])
except ValueError:
return HttpResponseBadRequest("Invalid limit")
if limit <= 0: if limit <= 0:
return HttpResponseBadRequest("Invalid limit") return HttpResponseBadRequest("Invalid limit")
else: else:
+18 -18
View File
@@ -2,7 +2,7 @@ msgid ""
msgstr "" msgstr ""
"Project-Id-Version: paperless-ngx\n" "Project-Id-Version: paperless-ngx\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-11-27 02:54+0000\n" "POT-Creation-Date: 2026-11-28 23:01+0000\n"
"PO-Revision-Date: 2022-02-17 04:17\n" "PO-Revision-Date: 2022-02-17 04:17\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: English\n" "Language-Team: English\n"
@@ -1879,49 +1879,49 @@ msgstr ""
msgid "OCR template zones" msgid "OCR template zones"
msgstr "" msgstr ""
#: documents/serialisers.py:491 documents/serialisers.py:815 #: documents/serialisers.py:495 documents/serialisers.py:819
#: documents/serialisers.py:2913 documents/views.py:372 documents/views.py:638 #: documents/serialisers.py:2918 documents/views.py:372 documents/views.py:638
#: documents/views.py:2868 paperless_mail/serialisers.py:145 #: documents/views.py:2870 paperless_mail/serialisers.py:145
msgid "Insufficient permissions." msgid "Insufficient permissions."
msgstr "" msgstr ""
#: documents/serialisers.py:647 #: documents/serialisers.py:651
msgid "Invalid color." msgid "Invalid color."
msgstr "" msgstr ""
#: documents/serialisers.py:2380 #: documents/serialisers.py:2385
#, python-format #, python-format
msgid "File type %(type)s not supported" msgid "File type %(type)s not supported"
msgstr "" msgstr ""
#: documents/serialisers.py:2424 #: documents/serialisers.py:2429
#, python-format #, python-format
msgid "Custom field id must be an integer: %(id)s" msgid "Custom field id must be an integer: %(id)s"
msgstr "" msgstr ""
#: documents/serialisers.py:2431 #: documents/serialisers.py:2436
#, python-format #, python-format
msgid "Custom field with id %(id)s does not exist" msgid "Custom field with id %(id)s does not exist"
msgstr "" msgstr ""
#: documents/serialisers.py:2448 documents/serialisers.py:2458 #: documents/serialisers.py:2453 documents/serialisers.py:2463
msgid "" msgid ""
"Custom fields must be a list of integers or an object mapping ids to values." "Custom fields must be a list of integers or an object mapping ids to values."
msgstr "" msgstr ""
#: documents/serialisers.py:2453 #: documents/serialisers.py:2458
msgid "Some custom fields don't exist or were specified twice." msgid "Some custom fields don't exist or were specified twice."
msgstr "" msgstr ""
#: documents/serialisers.py:2600 #: documents/serialisers.py:2605
msgid "Invalid variable detected." msgid "Invalid variable detected."
msgstr "" msgstr ""
#: documents/serialisers.py:2969 #: documents/serialisers.py:2974
msgid "Duplicate document identifiers are not allowed." msgid "Duplicate document identifiers are not allowed."
msgstr "" msgstr ""
#: documents/serialisers.py:2999 documents/views.py:5001 #: documents/serialisers.py:3004 documents/views.py:5008
#, python-format #, python-format
msgid "Documents not found: %(ids)s" msgid "Documents not found: %(ids)s"
msgstr "" msgstr ""
@@ -2192,7 +2192,7 @@ msgstr ""
msgid "Specify only one of text, title_search, query, or more_like_id." msgid "Specify only one of text, title_search, query, or more_like_id."
msgstr "" msgstr ""
#: documents/views.py:365 documents/views.py:2865 #: documents/views.py:365 documents/views.py:2867
msgid "Invalid more_like_id" msgid "Invalid more_like_id"
msgstr "" msgstr ""
@@ -2208,20 +2208,20 @@ msgstr ""
msgid "AI backend rejected the request. Check logs for details." msgid "AI backend rejected the request. Check logs for details."
msgstr "" msgstr ""
#: documents/views.py:5017 #: documents/views.py:5024
#, python-format #, python-format
msgid "Insufficient permissions to share document %(id)s." msgid "Insufficient permissions to share document %(id)s."
msgstr "" msgstr ""
#: documents/views.py:5064 #: documents/views.py:5071
msgid "Bundle is already being processed." msgid "Bundle is already being processed."
msgstr "" msgstr ""
#: documents/views.py:5130 #: documents/views.py:5137
msgid "The share link bundle is still being prepared. Please try again later." msgid "The share link bundle is still being prepared. Please try again later."
msgstr "" msgstr ""
#: documents/views.py:5144 #: documents/views.py:5151
msgid "The share link bundle is unavailable." msgid "The share link bundle is unavailable."
msgstr "" msgstr ""