Compare commits

..
7 changed files with 136 additions and 124 deletions

No files matched your search

-1
View File
@@ -87,7 +87,6 @@ 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 "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: Module "sklearn.exceptions" has no attribute "InconsistentVersionWarning" [attr-defined]
src/documents/classifier.py:0: error: Unsupported operand types for >= ("datetime" and "None") [operator]
+11 -73
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
import functools
import hmac
import logging
import pickle
import re
@@ -15,9 +14,6 @@ if TYPE_CHECKING:
from collections.abc import Callable
from collections.abc import Iterator
from datetime import datetime
from types import TracebackType
from typing import BinaryIO
from typing import Self
import tantivy
from numpy import ndarray
@@ -37,9 +33,11 @@ from documents.caching import CLASSIFIER_VERSION_KEY
from documents.models import Document
from documents.models import MatchingModel
from documents.models import Tag
from paperless.signed_pickle import SignedFileWriter
from paperless.signed_pickle import SignedPickleError
from paperless.signed_pickle import signed_pickle_dumps
from paperless.signed_pickle import signed_pickle_loads
from paperless.signed_pickle import verify_signed
logger = logging.getLogger("paperless.classifier")
@@ -77,49 +75,6 @@ RE_WORD = re.compile(r"\b[\w]+\b") # words that may contain digits
_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
def _text_analyzer(language: str) -> tantivy.TextAnalyzer:
"""
@@ -209,8 +164,6 @@ class DocumentClassifier:
# Tantivy text preprocessing
FORMAT_VERSION = 11
HMAC_SIZE = 32 # SHA-256 digest length
def __init__(self) -> None:
# last time a document changed and therefore training might be required
self.last_doc_change_time: datetime | None = None
@@ -230,10 +183,6 @@ class DocumentClassifier:
pickle.dumps(self.data_vectorizer),
).hexdigest()
@staticmethod
def _new_hmac() -> hmac.HMAC:
return hmac.new(settings.SECRET_KEY.encode(), digestmod=sha256)
@staticmethod
def _strip_training_state(classifier: MLPClassifier) -> None:
"""
@@ -248,30 +197,19 @@ class DocumentClassifier:
del classifier._best_coefs
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:
from sklearn.exceptions import InconsistentVersionWarning
raw = Path(settings.MODEL_FILE).read_bytes()
if len(raw) <= self.HMAC_SIZE:
raise ClassifierModelCorruptError
# Slice through a memoryview so the (potentially multi-GB) payload is
# not copied; hmac and pickle both accept buffers directly.
# The whole file is still verified from memory before unpickling, rather
# than streamed from disk, so it cannot change between check and load.
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
# The whole file is verified from memory before unpickling, rather than
# streamed from disk, so it cannot change between check and load.
# verify_signed returns a view of the data without copying the
# (potentially multi-GB) payload.
try:
data = verify_signed(raw)
except SignedPickleError as err:
raise ClassifierModelCorruptError from err
# Catch warnings for processing
with warnings.catch_warnings(record=True) as w:
@@ -315,7 +253,7 @@ class DocumentClassifier:
def save(self) -> None:
# 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).
with _SignedFileWriter(settings.MODEL_FILE, self._new_hmac()) as f:
with SignedFileWriter(settings.MODEL_FILE) as f:
pickle.dump(
(
self.FORMAT_VERSION,
+15 -4
View File
@@ -1,3 +1,5 @@
import hashlib
import hmac
import pickle
import warnings
from datetime import UTC
@@ -31,6 +33,7 @@ from documents.models import Tag
from documents.tests.helpers import dummy_preprocess
from paperless.settings import CLASSIFIER_LANGUAGES
from paperless.signed_pickle import HMAC_SIZE
from paperless.signed_pickle import compute_signature
from paperless.signed_pickle import signed_pickle_dumps
from paperless_testing.dirs import DirectoriesMixin
from paperless_testing.factories import DocumentFactory
@@ -423,7 +426,7 @@ class TestClassifier(DirectoriesMixin, TestCase):
- The ClassifierModelCorruptError is raised
"""
garbage_data = b"this is not valid pickle data"
signature = DocumentClassifier._compute_hmac(garbage_data)
signature = compute_signature(garbage_data)
Path(settings.MODEL_FILE).write_bytes(signature + garbage_data)
with self.assertRaises(ClassifierModelCorruptError):
@@ -944,9 +947,17 @@ class TestClassifierSave:
classifier.save()
raw = model_file.read_bytes()
signature = raw[: DocumentClassifier.HMAC_SIZE]
data = raw[DocumentClassifier.HMAC_SIZE :]
assert signature == DocumentClassifier._compute_hmac(data)
signature = raw[:HMAC_SIZE]
data = raw[HMAC_SIZE:]
# Computed independently so the on-disk format stays what is documented
assert (
signature
== hmac.new(
settings.SECRET_KEY.encode(),
data,
hashlib.sha256,
).digest()
)
# A pickle opens with the PROTO opcode followed by the protocol number
assert data[:2] == bytes([pickle.PROTO[0], pickle.HIGHEST_PROTOCOL])
assert pickle.loads(data)[:3] == (
+84 -12
View File
@@ -3,10 +3,17 @@ from __future__ import annotations
import hmac
import pickle
from hashlib import sha256
from typing import TYPE_CHECKING
from typing import Any
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
@@ -14,26 +21,91 @@ class SignedPickleError(ValueError):
"""Raised when a signed pickle payload cannot be authenticated."""
def _get_signing_key() -> bytes:
return settings.SECRET_KEY.encode()
def new_mac() -> hmac.HMAC:
"""
A new HMAC-SHA256 keyed with the SECRET_KEY, for signing incrementally.
"""
return hmac.new(settings.SECRET_KEY.encode(), digestmod=sha256)
def signed_pickle_dumps(obj: object) -> bytes:
data = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
signature = hmac.new(_get_signing_key(), data, sha256).digest()
return signature + data
def compute_signature(data: bytes | memoryview) -> bytes:
mac = new_mac()
mac.update(data)
return mac.digest()
def signed_pickle_loads(payload: bytes) -> Any:
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)
signature = payload[:HMAC_SIZE]
data = payload[HMAC_SIZE:]
expected = hmac.new(_get_signing_key(), data, sha256).digest()
if not hmac.compare_digest(signature, expected):
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 pickle.loads(data)
return data
def signed_pickle_dumps(obj: object) -> bytes:
data = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
return compute_signature(data) + data
def signed_pickle_loads(payload: bytes) -> Any:
return pickle.loads(verify_signed(payload))
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 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)
+10
View File
@@ -12,6 +12,8 @@ from django.test import override_settings
from paperless.celery import signed_pickle_dumps
from paperless.celery import signed_pickle_loads
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:
@@ -80,6 +82,14 @@ class TestSignedPickleSerializer:
with pytest.raises(ValueError, match="HMAC verification failed"):
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:
"""A payload shorter than HMAC_SIZE is rejected."""
with pytest.raises(ValueError, match="too short"):
-18
View File
@@ -12,11 +12,6 @@ from paperless.utils import ocr_to_dateparser_languages
pytest.param("eng", ["en"], id="single-language"),
pytest.param("fra+ita+lao", ["fr", "it", "lo"], id="multiple-languages"),
pytest.param("fil", ["fil"], id="no-two-letter-equivalent"),
pytest.param(
"afr+vie+kan+chr+mkd", # codespell:ignore
["af", "vi", "kn", "chr", "mk"],
id="previously-unmapped-languages",
),
pytest.param(
"aze_cyrl+srp_latn",
["az-Cyrl", "sr-Latn"],
@@ -54,19 +49,6 @@ def test_ocr_to_dateparser_languages(ocr_language: str, expected: list[str]) ->
assert sorted(ocr_to_dateparser_languages(ocr_language)) == sorted(expected)
def test_ocr_to_dateparser_map_values_supported_by_dateparser() -> None:
from dateparser.languages.loader import LocaleDataLoader
loader = LocaleDataLoader()
unsupported = []
for ocr_code, dateparser_code in utils.OCR_TO_DATEPARSER_LANGUAGES.items():
try:
loader.get_locale_map(locales=[dateparser_code])
except Exception:
unsupported.append((ocr_code, dateparser_code))
assert unsupported == []
def test_ocr_to_dateparser_languages_exception(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
+16 -16
View File
@@ -2,18 +2,19 @@ import logging
logger = logging.getLogger("paperless.utils")
# Translation map from languages supported by Tesseract OCR
# to languages supported by dateparser.
# To add a language, make sure it is supported by both libraries.
# The ISO 639-2 will help you link a 3-char to 2-char language code.
# Links:
# - Tesseract languages: https://tesseract-ocr.github.io/tessdoc/Data-Files-in-different-versions.html
# - Python dateparser languages: https://dateparser.readthedocs.io/en/latest/supported_locales.html
# - ISO 639-2: https://www.loc.gov/standards/iso639-2/php/code_list.php
OCR_TO_DATEPARSER_LANGUAGES = {
# These dateparser languages have no equivalent in any Tesseract release
# (checked against tessdata, tessdata_best and tessdata_fast), so they cannot
# be reached from the OCR language. Set PAPERLESS_DATE_PARSER_LANGUAGES to use them:
"""
Translation map from languages supported by Tesseract OCR
to languages supported by dateparser.
To add a language, make sure it is supported by both libraries.
The ISO 639-2 will help you link a 3-char to 2-char language code.
Links:
- Tesseract languages: https://tesseract-ocr.github.io/tessdoc/Data-Files-in-different-versions.html
- Python dateparser languages: https://dateparser.readthedocs.io/en/latest/supported_locales.html
- ISO 639-2: https://www.loc.gov/standards/iso639-2/php/code_list.php
"""
# TODO check these Dateparser languages as they are not referenced on the ISO639-2 standard,
# so we didn't find the equivalent in Tesseract:
# agq, asa, bez, brx, cgg, ckb, dav, dje, dyo, ebu, guz, jgo, jmc, kde, kea, khq, kln,
# ksb, ksf, ksh, lag, lkt, lrc, luy, mer, mfe, mgh, mgo, mua, mzn, naq, nmg, nnh, nus,
# rof, rwk, saq, sbp, she, ses, shi, teo, twq, tzm, vun, wae, xog, yav, yue
@@ -21,6 +22,7 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"amh": "am",
"ara": "ar",
"asm": "as",
"ast": "ast",
"aze": "az",
"bel": "be",
"bul": "bg",
@@ -29,7 +31,7 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"bre": "br",
"bos": "bs",
"cat": "ca",
"chr": "chr",
"cher": "chr",
"ces": "cs",
"cym": "cy",
"dan": "da",
@@ -63,21 +65,19 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"kat": "ka",
"kaz": "kk",
"khm": "km",
"kan": "kn",
"knda": "kn",
"kor": "ko",
"kir": "ky",
"ltz": "lb",
"lao": "lo",
"lit": "lt",
"lav": "lv",
"mkd": "mk",
"mal": "ml",
"mon": "mn",
"mar": "mr",
"msa": "ms",
"mlt": "mt",
"mya": "my",
"nor": "nb",
"nep": "ne",
"nld": "nl",
"ori": "or",
@@ -106,7 +106,7 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"ukr": "uk",
"urd": "ur",
"uzb": "uz",
"vie": "vi", # codespell:ignore
"via": "vi",
"yid": "yi",
"yor": "yo",
"chi": "zh",