mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-27 23:45:14 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9feb7aaa14 |
No files matched your search
@@ -87,6 +87,7 @@ src/documents/classifier.py:0: error: Incompatible types in assignment (expressi
|
|||||||
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
||||||
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
||||||
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "str", variable has type "None") [assignment]
|
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "str", variable has type "None") [assignment]
|
||||||
|
src/documents/classifier.py:0: error: Item "None" of "str | None" has no attribute "encode" [union-attr]
|
||||||
src/documents/classifier.py:0: error: List comprehension has incompatible type List[int]; expected List[list[int]] [misc]
|
src/documents/classifier.py:0: error: List comprehension has incompatible type List[int]; expected List[list[int]] [misc]
|
||||||
src/documents/classifier.py:0: error: Module "sklearn.exceptions" has no attribute "InconsistentVersionWarning" [attr-defined]
|
src/documents/classifier.py:0: error: Module "sklearn.exceptions" has no attribute "InconsistentVersionWarning" [attr-defined]
|
||||||
src/documents/classifier.py:0: error: Unsupported operand types for >= ("datetime" and "None") [operator]
|
src/documents/classifier.py:0: error: Unsupported operand types for >= ("datetime" and "None") [operator]
|
||||||
|
|||||||
+73
-11
@@ -1,6 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import functools
|
import functools
|
||||||
|
import hmac
|
||||||
import logging
|
import logging
|
||||||
import pickle
|
import pickle
|
||||||
import re
|
import re
|
||||||
@@ -14,6 +15,9 @@ if TYPE_CHECKING:
|
|||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from types import TracebackType
|
||||||
|
from typing import BinaryIO
|
||||||
|
from typing import Self
|
||||||
|
|
||||||
import tantivy
|
import tantivy
|
||||||
from numpy import ndarray
|
from numpy import ndarray
|
||||||
@@ -33,11 +37,9 @@ from documents.caching import CLASSIFIER_VERSION_KEY
|
|||||||
from documents.models import Document
|
from documents.models import Document
|
||||||
from documents.models import MatchingModel
|
from documents.models import MatchingModel
|
||||||
from documents.models import Tag
|
from documents.models import Tag
|
||||||
from paperless.signed_pickle import SignedFileWriter
|
|
||||||
from paperless.signed_pickle import SignedPickleError
|
from paperless.signed_pickle import SignedPickleError
|
||||||
from paperless.signed_pickle import signed_pickle_dumps
|
from paperless.signed_pickle import signed_pickle_dumps
|
||||||
from paperless.signed_pickle import signed_pickle_loads
|
from paperless.signed_pickle import signed_pickle_loads
|
||||||
from paperless.signed_pickle import verify_signed
|
|
||||||
|
|
||||||
logger = logging.getLogger("paperless.classifier")
|
logger = logging.getLogger("paperless.classifier")
|
||||||
|
|
||||||
@@ -75,6 +77,49 @@ RE_WORD = re.compile(r"\b[\w]+\b") # words that may contain digits
|
|||||||
_CONTENT_CHUNK_SIZE = 1000
|
_CONTENT_CHUNK_SIZE = 1000
|
||||||
|
|
||||||
|
|
||||||
|
class _SignedFileWriter:
|
||||||
|
"""
|
||||||
|
Atomically writes a file made of an HMAC signature followed by the data,
|
||||||
|
signing the data as it streams to disk rather than holding it in memory.
|
||||||
|
|
||||||
|
The signature is only known once everything is written, so its space is
|
||||||
|
reserved at the start of the file and filled in on exit. The target is only
|
||||||
|
replaced once the file is complete; on error the partial file is removed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, target: Path, mac: hmac.HMAC) -> None:
|
||||||
|
self._target = target
|
||||||
|
self._temp = target.with_name(f"{target.name}.part")
|
||||||
|
self._mac = mac
|
||||||
|
self._file: BinaryIO
|
||||||
|
|
||||||
|
def __enter__(self) -> Self:
|
||||||
|
self._file = self._temp.open("wb")
|
||||||
|
self._file.write(bytes(self._mac.digest_size))
|
||||||
|
return self
|
||||||
|
|
||||||
|
def write(self, data: bytes | memoryview) -> int:
|
||||||
|
self._mac.update(data)
|
||||||
|
return self._file.write(data)
|
||||||
|
|
||||||
|
def __exit__(
|
||||||
|
self,
|
||||||
|
exc_type: type[BaseException] | None,
|
||||||
|
exc_value: BaseException | None,
|
||||||
|
traceback: TracebackType | None,
|
||||||
|
) -> None:
|
||||||
|
try:
|
||||||
|
with self._file:
|
||||||
|
if exc_type is None:
|
||||||
|
self._file.seek(0)
|
||||||
|
self._file.write(self._mac.digest())
|
||||||
|
if exc_type is None:
|
||||||
|
self._temp.rename(self._target)
|
||||||
|
finally:
|
||||||
|
# A no-op after a successful rename, otherwise removes the partial file
|
||||||
|
self._temp.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
@functools.cache
|
@functools.cache
|
||||||
def _text_analyzer(language: str) -> tantivy.TextAnalyzer:
|
def _text_analyzer(language: str) -> tantivy.TextAnalyzer:
|
||||||
"""
|
"""
|
||||||
@@ -164,6 +209,8 @@ class DocumentClassifier:
|
|||||||
# Tantivy text preprocessing
|
# Tantivy text preprocessing
|
||||||
FORMAT_VERSION = 11
|
FORMAT_VERSION = 11
|
||||||
|
|
||||||
|
HMAC_SIZE = 32 # SHA-256 digest length
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
# last time a document changed and therefore training might be required
|
# last time a document changed and therefore training might be required
|
||||||
self.last_doc_change_time: datetime | None = None
|
self.last_doc_change_time: datetime | None = None
|
||||||
@@ -183,6 +230,10 @@ class DocumentClassifier:
|
|||||||
pickle.dumps(self.data_vectorizer),
|
pickle.dumps(self.data_vectorizer),
|
||||||
).hexdigest()
|
).hexdigest()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _new_hmac() -> hmac.HMAC:
|
||||||
|
return hmac.new(settings.SECRET_KEY.encode(), digestmod=sha256)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _strip_training_state(classifier: MLPClassifier) -> None:
|
def _strip_training_state(classifier: MLPClassifier) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -197,19 +248,30 @@ class DocumentClassifier:
|
|||||||
del classifier._best_coefs
|
del classifier._best_coefs
|
||||||
del classifier._best_intercepts
|
del classifier._best_intercepts
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _compute_hmac(data: bytes | memoryview) -> bytes:
|
||||||
|
mac = DocumentClassifier._new_hmac()
|
||||||
|
mac.update(data)
|
||||||
|
return mac.digest()
|
||||||
|
|
||||||
def load(self) -> None:
|
def load(self) -> None:
|
||||||
from sklearn.exceptions import InconsistentVersionWarning
|
from sklearn.exceptions import InconsistentVersionWarning
|
||||||
|
|
||||||
raw = Path(settings.MODEL_FILE).read_bytes()
|
raw = Path(settings.MODEL_FILE).read_bytes()
|
||||||
|
|
||||||
# The whole file is verified from memory before unpickling, rather than
|
if len(raw) <= self.HMAC_SIZE:
|
||||||
# streamed from disk, so it cannot change between check and load.
|
raise ClassifierModelCorruptError
|
||||||
# verify_signed returns a view of the data without copying the
|
|
||||||
# (potentially multi-GB) payload.
|
# Slice through a memoryview so the (potentially multi-GB) payload is
|
||||||
try:
|
# not copied; hmac and pickle both accept buffers directly.
|
||||||
data = verify_signed(raw)
|
# The whole file is still verified from memory before unpickling, rather
|
||||||
except SignedPickleError as err:
|
# than streamed from disk, so it cannot change between check and load.
|
||||||
raise ClassifierModelCorruptError from err
|
view = memoryview(raw)
|
||||||
|
signature = view[: self.HMAC_SIZE]
|
||||||
|
data = view[self.HMAC_SIZE :]
|
||||||
|
|
||||||
|
if not hmac.compare_digest(signature, self._compute_hmac(data)):
|
||||||
|
raise ClassifierModelCorruptError
|
||||||
|
|
||||||
# Catch warnings for processing
|
# Catch warnings for processing
|
||||||
with warnings.catch_warnings(record=True) as w:
|
with warnings.catch_warnings(record=True) as w:
|
||||||
@@ -253,7 +315,7 @@ class DocumentClassifier:
|
|||||||
def save(self) -> None:
|
def save(self) -> None:
|
||||||
# Stream to disk instead of building the payload in memory. Protocol 5+
|
# Stream to disk instead of building the payload in memory. Protocol 5+
|
||||||
# pickles numpy arrays without copying them (the default is 4 before 3.14).
|
# pickles numpy arrays without copying them (the default is 4 before 3.14).
|
||||||
with SignedFileWriter(settings.MODEL_FILE) as f:
|
with _SignedFileWriter(settings.MODEL_FILE, self._new_hmac()) as f:
|
||||||
pickle.dump(
|
pickle.dump(
|
||||||
(
|
(
|
||||||
self.FORMAT_VERSION,
|
self.FORMAT_VERSION,
|
||||||
|
|||||||
+10
-21
@@ -6,7 +6,6 @@ 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
|
||||||
@@ -897,26 +896,25 @@ 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():
|
|
||||||
final_path.unlink()
|
with TemporaryDirectory(dir=settings.SCRATCH_DIR) as tmp_dir:
|
||||||
shutil.move(temp_zip_path, final_path)
|
temp_zip_path = Path(tmp_dir) / "bundle.zip"
|
||||||
|
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
|
||||||
@@ -947,16 +945,7 @@ 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
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import hashlib
|
|
||||||
import hmac
|
|
||||||
import pickle
|
import pickle
|
||||||
import warnings
|
import warnings
|
||||||
from datetime import UTC
|
from datetime import UTC
|
||||||
@@ -33,7 +31,6 @@ from documents.models import Tag
|
|||||||
from documents.tests.helpers import dummy_preprocess
|
from documents.tests.helpers import dummy_preprocess
|
||||||
from paperless.settings import CLASSIFIER_LANGUAGES
|
from paperless.settings import CLASSIFIER_LANGUAGES
|
||||||
from paperless.signed_pickle import HMAC_SIZE
|
from paperless.signed_pickle import HMAC_SIZE
|
||||||
from paperless.signed_pickle import compute_signature
|
|
||||||
from paperless.signed_pickle import signed_pickle_dumps
|
from paperless.signed_pickle import signed_pickle_dumps
|
||||||
from paperless_testing.dirs import DirectoriesMixin
|
from paperless_testing.dirs import DirectoriesMixin
|
||||||
from paperless_testing.factories import DocumentFactory
|
from paperless_testing.factories import DocumentFactory
|
||||||
@@ -426,7 +423,7 @@ class TestClassifier(DirectoriesMixin, TestCase):
|
|||||||
- The ClassifierModelCorruptError is raised
|
- The ClassifierModelCorruptError is raised
|
||||||
"""
|
"""
|
||||||
garbage_data = b"this is not valid pickle data"
|
garbage_data = b"this is not valid pickle data"
|
||||||
signature = compute_signature(garbage_data)
|
signature = DocumentClassifier._compute_hmac(garbage_data)
|
||||||
Path(settings.MODEL_FILE).write_bytes(signature + garbage_data)
|
Path(settings.MODEL_FILE).write_bytes(signature + garbage_data)
|
||||||
|
|
||||||
with self.assertRaises(ClassifierModelCorruptError):
|
with self.assertRaises(ClassifierModelCorruptError):
|
||||||
@@ -947,17 +944,9 @@ class TestClassifierSave:
|
|||||||
classifier.save()
|
classifier.save()
|
||||||
|
|
||||||
raw = model_file.read_bytes()
|
raw = model_file.read_bytes()
|
||||||
signature = raw[:HMAC_SIZE]
|
signature = raw[: DocumentClassifier.HMAC_SIZE]
|
||||||
data = raw[HMAC_SIZE:]
|
data = raw[DocumentClassifier.HMAC_SIZE :]
|
||||||
# Computed independently so the on-disk format stays what is documented
|
assert signature == DocumentClassifier._compute_hmac(data)
|
||||||
assert (
|
|
||||||
signature
|
|
||||||
== hmac.new(
|
|
||||||
settings.SECRET_KEY.encode(),
|
|
||||||
data,
|
|
||||||
hashlib.sha256,
|
|
||||||
).digest()
|
|
||||||
)
|
|
||||||
# A pickle opens with the PROTO opcode followed by the protocol number
|
# A pickle opens with the PROTO opcode followed by the protocol number
|
||||||
assert data[:2] == bytes([pickle.PROTO[0], pickle.HIGHEST_PROTOCOL])
|
assert data[:2] == bytes([pickle.PROTO[0], pickle.HIGHEST_PROTOCOL])
|
||||||
assert pickle.loads(data)[:3] == (
|
assert pickle.loads(data)[:3] == (
|
||||||
|
|||||||
@@ -434,13 +434,9 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
|
|||||||
"documents.tasks.OriginalsOnlyStrategy.add_document",
|
"documents.tasks.OriginalsOnlyStrategy.add_document",
|
||||||
side_effect=RuntimeError("zip failure"),
|
side_effect=RuntimeError("zip failure"),
|
||||||
),
|
),
|
||||||
mock.patch("pathlib.Path.unlink") as unlink_mock,
|
self.assertRaises(RuntimeError),
|
||||||
):
|
):
|
||||||
unlink_mock.side_effect = [OSError("unlink"), OSError("unlink-finally")] + [
|
build_share_link_bundle(bundle.pk)
|
||||||
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)
|
||||||
@@ -448,10 +444,6 @@ 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
|
||||||
|
|||||||
@@ -3,17 +3,10 @@ from __future__ import annotations
|
|||||||
import hmac
|
import hmac
|
||||||
import pickle
|
import pickle
|
||||||
from hashlib import sha256
|
from hashlib import sha256
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from pathlib import Path
|
|
||||||
from types import TracebackType
|
|
||||||
from typing import BinaryIO
|
|
||||||
from typing import Self
|
|
||||||
|
|
||||||
HMAC_SIZE = sha256().digest_size
|
HMAC_SIZE = sha256().digest_size
|
||||||
|
|
||||||
|
|
||||||
@@ -21,91 +14,26 @@ class SignedPickleError(ValueError):
|
|||||||
"""Raised when a signed pickle payload cannot be authenticated."""
|
"""Raised when a signed pickle payload cannot be authenticated."""
|
||||||
|
|
||||||
|
|
||||||
def new_mac() -> hmac.HMAC:
|
def _get_signing_key() -> bytes:
|
||||||
"""
|
return settings.SECRET_KEY.encode()
|
||||||
A new HMAC-SHA256 keyed with the SECRET_KEY, for signing incrementally.
|
|
||||||
"""
|
|
||||||
return hmac.new(settings.SECRET_KEY.encode(), digestmod=sha256)
|
|
||||||
|
|
||||||
|
|
||||||
def compute_signature(data: bytes | memoryview) -> bytes:
|
|
||||||
mac = new_mac()
|
|
||||||
mac.update(data)
|
|
||||||
return mac.digest()
|
|
||||||
|
|
||||||
|
|
||||||
def verify_signed(payload: bytes | memoryview) -> memoryview:
|
|
||||||
"""
|
|
||||||
Verifies a payload made of an HMAC signature followed by the data, returning
|
|
||||||
a view of the data.
|
|
||||||
|
|
||||||
The data is sliced through a memoryview, so a (potentially multi-GB) payload
|
|
||||||
is not copied. The view is only returned once the whole payload has been
|
|
||||||
verified, and callers should unpickle from it rather than from the source,
|
|
||||||
so what is loaded is exactly what was checked.
|
|
||||||
"""
|
|
||||||
if len(payload) <= HMAC_SIZE:
|
|
||||||
msg = "Signed-pickle payload too short"
|
|
||||||
raise SignedPickleError(msg)
|
|
||||||
|
|
||||||
view = memoryview(payload)
|
|
||||||
signature = view[:HMAC_SIZE]
|
|
||||||
data = view[HMAC_SIZE:]
|
|
||||||
if not hmac.compare_digest(signature, compute_signature(data)):
|
|
||||||
msg = "Signed-pickle HMAC verification failed; payload may have been tampered with"
|
|
||||||
raise SignedPickleError(msg)
|
|
||||||
|
|
||||||
return data
|
|
||||||
|
|
||||||
|
|
||||||
def signed_pickle_dumps(obj: object) -> bytes:
|
def signed_pickle_dumps(obj: object) -> bytes:
|
||||||
data = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
|
data = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
|
||||||
return compute_signature(data) + data
|
signature = hmac.new(_get_signing_key(), data, sha256).digest()
|
||||||
|
return signature + data
|
||||||
|
|
||||||
|
|
||||||
def signed_pickle_loads(payload: bytes) -> Any:
|
def signed_pickle_loads(payload: bytes) -> Any:
|
||||||
return pickle.loads(verify_signed(payload))
|
if len(payload) <= HMAC_SIZE:
|
||||||
|
msg = "Signed-pickle payload too short"
|
||||||
|
raise SignedPickleError(msg)
|
||||||
|
|
||||||
|
signature = payload[:HMAC_SIZE]
|
||||||
|
data = payload[HMAC_SIZE:]
|
||||||
|
expected = hmac.new(_get_signing_key(), data, sha256).digest()
|
||||||
|
if not hmac.compare_digest(signature, expected):
|
||||||
|
msg = "Signed-pickle HMAC verification failed; payload may have been tampered with"
|
||||||
|
raise SignedPickleError(msg)
|
||||||
|
|
||||||
class SignedFileWriter:
|
return pickle.loads(data)
|
||||||
"""
|
|
||||||
Atomically writes a file made of an HMAC signature followed by the data,
|
|
||||||
signing the data as it streams to disk rather than holding it in memory.
|
|
||||||
The result can be read back with verify_signed.
|
|
||||||
|
|
||||||
The signature is only known once everything is written, so its space is
|
|
||||||
reserved at the start of the file and filled in on exit. The target is only
|
|
||||||
replaced once the file is complete; on error the partial file is removed.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, target: Path) -> None:
|
|
||||||
self._target = target
|
|
||||||
self._temp = target.with_name(f"{target.name}.part")
|
|
||||||
self._mac = new_mac()
|
|
||||||
self._file: BinaryIO
|
|
||||||
|
|
||||||
def __enter__(self) -> Self:
|
|
||||||
self._file = self._temp.open("wb")
|
|
||||||
self._file.write(bytes(HMAC_SIZE))
|
|
||||||
return self
|
|
||||||
|
|
||||||
def write(self, data: bytes | memoryview) -> int:
|
|
||||||
self._mac.update(data)
|
|
||||||
return self._file.write(data)
|
|
||||||
|
|
||||||
def __exit__(
|
|
||||||
self,
|
|
||||||
exc_type: type[BaseException] | None,
|
|
||||||
exc_value: BaseException | None,
|
|
||||||
traceback: TracebackType | None,
|
|
||||||
) -> None:
|
|
||||||
try:
|
|
||||||
with self._file:
|
|
||||||
if exc_type is None:
|
|
||||||
self._file.seek(0)
|
|
||||||
self._file.write(self._mac.digest())
|
|
||||||
if exc_type is None:
|
|
||||||
self._temp.rename(self._target)
|
|
||||||
finally:
|
|
||||||
# A no-op after a successful rename, otherwise removes the partial file
|
|
||||||
self._temp.unlink(missing_ok=True)
|
|
||||||
@@ -12,8 +12,6 @@ from django.test import override_settings
|
|||||||
from paperless.celery import signed_pickle_dumps
|
from paperless.celery import signed_pickle_dumps
|
||||||
from paperless.celery import signed_pickle_loads
|
from paperless.celery import signed_pickle_loads
|
||||||
from paperless.signed_pickle import HMAC_SIZE
|
from paperless.signed_pickle import HMAC_SIZE
|
||||||
from paperless.signed_pickle import compute_signature
|
|
||||||
from paperless.signed_pickle import verify_signed
|
|
||||||
|
|
||||||
|
|
||||||
def test_tasks_registered_without_system_checks() -> None:
|
def test_tasks_registered_without_system_checks() -> None:
|
||||||
@@ -82,14 +80,6 @@ class TestSignedPickleSerializer:
|
|||||||
with pytest.raises(ValueError, match="HMAC verification failed"):
|
with pytest.raises(ValueError, match="HMAC verification failed"):
|
||||||
signed_pickle_loads(bytes(tampered))
|
signed_pickle_loads(bytes(tampered))
|
||||||
|
|
||||||
def test_verified_data_is_a_view_not_a_copy(self) -> None:
|
|
||||||
"""Verified data is a view of the payload, so large payloads aren't copied."""
|
|
||||||
data = b"x" * 1024
|
|
||||||
payload = compute_signature(data) + data
|
|
||||||
verified = verify_signed(payload)
|
|
||||||
assert verified.obj is payload
|
|
||||||
assert bytes(verified) == data
|
|
||||||
|
|
||||||
def test_truncated_payload_rejected(self) -> None:
|
def test_truncated_payload_rejected(self) -> None:
|
||||||
"""A payload shorter than HMAC_SIZE is rejected."""
|
"""A payload shorter than HMAC_SIZE is rejected."""
|
||||||
with pytest.raises(ValueError, match="too short"):
|
with pytest.raises(ValueError, match="too short"):
|
||||||
|
|||||||
Reference in new issue
Block a user