Compare commits

..
5 changed files with 79 additions and 19 deletions

No files matched your search

+8 -3
View File
@@ -106,6 +106,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]):
@@ -2306,8 +2310,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 (
@@ -2323,7 +2328,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:
+21 -10
View File
@@ -6,6 +6,7 @@ import zipfile
from collections.abc import Callable from collections.abc import Callable
from pathlib import Path from pathlib import Path
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
from tempfile import mkstemp
from celery import Task from celery import Task
from celery import shared_task from celery import shared_task
@@ -896,25 +897,26 @@ def build_share_link_bundle(bundle_id: int) -> None:
documents = list(bundle.documents.all().order_by("pk")) documents = list(bundle.documents.all().order_by("pk"))
_, temp_zip_path_str = mkstemp(suffix=".zip", dir=settings.SCRATCH_DIR)
temp_zip_path = Path(temp_zip_path_str)
try: try:
strategy_class = ( strategy_class = (
ArchiveOnlyStrategy ArchiveOnlyStrategy
if bundle.file_version == ShareLink.FileVersion.ARCHIVE if bundle.file_version == ShareLink.FileVersion.ARCHIVE
else OriginalsOnlyStrategy else OriginalsOnlyStrategy
) )
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
strategy = strategy_class(zipf)
for document in documents:
strategy.add_document(document)
output_dir = settings.SHARE_LINK_BUNDLE_DIR output_dir = settings.SHARE_LINK_BUNDLE_DIR
output_dir.mkdir(parents=True, exist_ok=True) output_dir.mkdir(parents=True, exist_ok=True)
final_path = (output_dir / f"{bundle.slug}.zip").resolve() final_path = (output_dir / f"{bundle.slug}.zip").resolve()
if final_path.exists():
with TemporaryDirectory(dir=settings.SCRATCH_DIR) as tmp_dir: final_path.unlink()
temp_zip_path = Path(tmp_dir) / "bundle.zip" shutil.move(temp_zip_path, final_path)
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
strategy = strategy_class(zipf)
for document in documents:
strategy.add_document(document)
final_path.unlink(missing_ok=True)
shutil.move(temp_zip_path, final_path)
bundle.file_path = f"{bundle.slug}.zip" bundle.file_path = f"{bundle.slug}.zip"
bundle.size_bytes = final_path.stat().st_size bundle.size_bytes = final_path.stat().st_size
@@ -945,7 +947,16 @@ def build_share_link_bundle(bundle_id: int) -> None:
"timestamp": timezone.now().isoformat(), "timestamp": timezone.now().isoformat(),
} }
bundle.save(update_fields=["status", "last_error"]) bundle.save(update_fields=["status", "last_error"])
try:
temp_zip_path.unlink()
except OSError:
pass
raise raise
finally:
try:
temp_zip_path.unlink(missing_ok=True)
except OSError:
pass
@shared_task @shared_task
+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()),
+10 -2
View File
@@ -434,9 +434,13 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
"documents.tasks.OriginalsOnlyStrategy.add_document", "documents.tasks.OriginalsOnlyStrategy.add_document",
side_effect=RuntimeError("zip failure"), side_effect=RuntimeError("zip failure"),
), ),
self.assertRaises(RuntimeError), mock.patch("pathlib.Path.unlink") as unlink_mock,
): ):
build_share_link_bundle(bundle.pk) unlink_mock.side_effect = [OSError("unlink"), OSError("unlink-finally")] + [
None,
] * 5
with self.assertRaises(RuntimeError):
build_share_link_bundle(bundle.pk)
bundle.refresh_from_db() bundle.refresh_from_db()
self.assertEqual(bundle.status, ShareLinkBundle.Status.FAILED) self.assertEqual(bundle.status, ShareLinkBundle.Status.FAILED)
@@ -444,6 +448,10 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
assert isinstance(bundle.last_error, dict) assert isinstance(bundle.last_error, dict)
self.assertEqual(bundle.last_error.get("message"), "zip failure") self.assertEqual(bundle.last_error.get("message"), "zip failure")
self.assertEqual(bundle.last_error.get("exception_type"), "RuntimeError") self.assertEqual(bundle.last_error.get("exception_type"), "RuntimeError")
scratch_zips = list(Path(settings.SCRATCH_DIR).glob("*.zip"))
self.assertTrue(scratch_zips)
for path in scratch_zips:
path.unlink(missing_ok=True)
def test_build_share_link_bundle_missing_bundle_noop(self) -> None: def test_build_share_link_bundle_missing_bundle_noop(self) -> None:
# Should not raise when bundle does not exist # Should not raise when bundle does not exist
+8 -4
View File
@@ -2189,7 +2189,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()))
@@ -2200,7 +2200,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))
@@ -3338,7 +3340,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")
@@ -3358,7 +3360,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))