mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-27 07:25:16 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
37bc1f55c4 |
No files matched your search
@@ -106,6 +106,10 @@ if TYPE_CHECKING:
|
||||
|
||||
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
|
||||
class DynamicFieldsModelSerializer(serializers.ModelSerializer[Any]):
|
||||
@@ -2306,8 +2310,9 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
)
|
||||
|
||||
def validate_document(self, document):
|
||||
document_data = document.file.read()
|
||||
mime_type = magic.from_buffer(document_data, mime=True)
|
||||
# libmagic only examines a bounded prefix, so an upload of any size is
|
||||
# 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 (
|
||||
@@ -2323,7 +2328,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
_("File type %(type)s not supported") % {"type": mime_type},
|
||||
)
|
||||
|
||||
return document.name, document_data
|
||||
return document.name, document
|
||||
|
||||
def validate_correspondent(self, correspondent):
|
||||
if correspondent:
|
||||
|
||||
@@ -2089,6 +2089,38 @@ class TestDocumentApi(DirectoriesMixin, ConsumeTaskMixin, APITestCase):
|
||||
self.assertIsNone(overrides.document_type_id)
|
||||
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:
|
||||
self.consume_file_mock.return_value = celery.result.AsyncResult(
|
||||
id=str(uuid.uuid4()),
|
||||
|
||||
@@ -2189,7 +2189,7 @@ class DocumentViewSet(
|
||||
raise Http404
|
||||
|
||||
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")
|
||||
|
||||
t = int(mktime(datetime.now().timetuple()))
|
||||
@@ -2200,7 +2200,9 @@ class DocumentViewSet(
|
||||
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))
|
||||
|
||||
@@ -3338,7 +3340,7 @@ class PostDocumentView(GenericAPIView[Any]):
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
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)
|
||||
correspondent_id = serializer.validated_data.get("correspondent")
|
||||
document_type_id = serializer.validated_data.get("document_type")
|
||||
@@ -3358,7 +3360,9 @@ class PostDocumentView(GenericAPIView[Any]):
|
||||
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))
|
||||
|
||||
|
||||
@@ -1256,36 +1256,3 @@ class TestIndexPageSize:
|
||||
|
||||
assert page_size_of(legacy_page_size_db) == DB_PAGE_SIZE
|
||||
assert DocumentChunksTable.count(store.client) == 2
|
||||
|
||||
|
||||
def test_open_connection_closes_connection_when_setup_fails(
|
||||
tmp_path: Path,
|
||||
mocker: MockerFixture,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN a table setup step that fails after the connection was opened
|
||||
WHEN the store is created
|
||||
THEN the setup error propagates
|
||||
AND the connection that was opened is closed, not leaked
|
||||
"""
|
||||
opened: list[sqlite3.Connection] = []
|
||||
real_connect = sqlite3.connect
|
||||
|
||||
def recording_connect(*args, **kwargs) -> sqlite3.Connection:
|
||||
conn = real_connect(*args, **kwargs)
|
||||
opened.append(conn)
|
||||
return conn
|
||||
|
||||
mocker.patch("paperless_ai.vector_store.sqlite3.connect", recording_connect)
|
||||
mocker.patch.object(
|
||||
DocumentMetaTable,
|
||||
"create",
|
||||
side_effect=RuntimeError("setup failed"),
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="setup failed"):
|
||||
PaperlessSqliteVecVectorStore(uri=str(tmp_path))
|
||||
|
||||
assert len(opened) == 1
|
||||
with pytest.raises(sqlite3.ProgrammingError):
|
||||
opened[0].execute("SELECT 1")
|
||||
@@ -4,7 +4,6 @@ import sqlite3
|
||||
import struct
|
||||
from collections.abc import Iterator
|
||||
from collections.abc import Sequence
|
||||
from contextlib import ExitStack
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from types import TracebackType
|
||||
@@ -213,38 +212,33 @@ class PaperlessSqliteVecVectorStore(BasePydanticVectorStore):
|
||||
|
||||
@staticmethod
|
||||
def _open_connection(db_path: str) -> sqlite3.Connection:
|
||||
with ExitStack() as stack:
|
||||
conn = sqlite3.connect(
|
||||
db_path,
|
||||
timeout=30,
|
||||
isolation_level=None, # autocommit; explicit transactions below
|
||||
)
|
||||
# Closes the connection (and its WAL/SHM handles) if any setup step
|
||||
# below raises. pop_all() disarms it once setup has succeeded.
|
||||
stack.callback(conn.close)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.enable_load_extension(True) # noqa: FBT003
|
||||
sqlite_vec.load(conn)
|
||||
conn.enable_load_extension(False) # noqa: FBT003
|
||||
conn.execute(f"PRAGMA page_size={DB_PAGE_SIZE}")
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA synchronous=NORMAL")
|
||||
IndexMetaTable.create(conn)
|
||||
# vec0 metadata columns only get an efficient lookup path inside a
|
||||
# KNN (MATCH) query; a plain `WHERE document_id = ?` is a full table
|
||||
# scan regardless of index size. This plain, indexed table is how
|
||||
# delete()/upsert_document() find a document's chunk ids without
|
||||
# that scan.
|
||||
DocumentChunksTable.create(conn)
|
||||
# modified used to be a vec0 metadata column, but vec0 only inlines
|
||||
# TEXT metadata up to 12 bytes -- an ISO timestamp is always longer,
|
||||
# so every read recompiled and stepped a fresh SQL statement per row.
|
||||
# It was never filtered on inside a KNN query either, so it never
|
||||
# needed to be a vec0 column at all. One row per document here (not
|
||||
# per chunk, like document_chunks), since every chunk of a document
|
||||
# shares the same modified value -- see get_modified_times().
|
||||
DocumentMetaTable.create(conn)
|
||||
stack.pop_all()
|
||||
conn = sqlite3.connect(
|
||||
db_path,
|
||||
timeout=30,
|
||||
isolation_level=None, # autocommit; explicit transactions below
|
||||
)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.enable_load_extension(True) # noqa: FBT003
|
||||
sqlite_vec.load(conn)
|
||||
conn.enable_load_extension(False) # noqa: FBT003
|
||||
conn.execute(f"PRAGMA page_size={DB_PAGE_SIZE}")
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA synchronous=NORMAL")
|
||||
IndexMetaTable.create(conn)
|
||||
# vec0 metadata columns only get an efficient lookup path inside a
|
||||
# KNN (MATCH) query; a plain `WHERE document_id = ?` is a full table
|
||||
# scan regardless of index size. This plain, indexed table is how
|
||||
# delete()/upsert_document() find a document's chunk ids without
|
||||
# that scan.
|
||||
DocumentChunksTable.create(conn)
|
||||
# modified used to be a vec0 metadata column, but vec0 only inlines
|
||||
# TEXT metadata up to 12 bytes -- an ISO timestamp is always longer,
|
||||
# so every read recompiled and stepped a fresh SQL statement per row.
|
||||
# It was never filtered on inside a KNN query either, so it never
|
||||
# needed to be a vec0 column at all. One row per document here (not
|
||||
# per chunk, like document_chunks), since every chunk of a document
|
||||
# shares the same modified value -- see get_modified_times().
|
||||
DocumentMetaTable.create(conn)
|
||||
return conn
|
||||
|
||||
@property
|
||||
|
||||
Reference in new issue
Block a user