mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-12-01 17:10:24 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e0a4e5bdb |
No files matched your search
@@ -35,7 +35,7 @@ services:
|
||||
- "3143:3143" # IMAP
|
||||
restart: unless-stopped
|
||||
nginx:
|
||||
image: docker.io/nginx:1.31.9-alpine
|
||||
image: docker.io/nginx:1.31.7-alpine
|
||||
hostname: nginx
|
||||
container_name: nginx
|
||||
ports:
|
||||
|
||||
@@ -73,10 +73,9 @@ def get_suggestion_cache(document_id: int) -> SuggestionCacheData | None:
|
||||
|
||||
doc_key = get_suggestion_cache_key(document_id)
|
||||
cache_hits = cache.get_many([CLASSIFIER_VERSION_KEY, CLASSIFIER_HASH_KEY, doc_key])
|
||||
# The document suggestions are in the cache. get_many keeps an entry the cache
|
||||
# serializer rejected as None, rather than leaving the key out.
|
||||
doc_suggestions: SuggestionCacheData | None = cache_hits.get(doc_key)
|
||||
if doc_suggestions is not None:
|
||||
# The document suggestions are in the cache
|
||||
if doc_key in cache_hits:
|
||||
doc_suggestions: SuggestionCacheData = cache_hits[doc_key]
|
||||
# The classifier format is the same
|
||||
# The classifier hash is the same
|
||||
# Then the suggestions can be used
|
||||
|
||||
@@ -1330,6 +1330,11 @@ class SavedViewFilterRuleSerializer(serializers.ModelSerializer[SavedViewFilterR
|
||||
|
||||
class SavedViewSerializer(OwnedObjectSerializer):
|
||||
filter_rules = SavedViewFilterRuleSerializer(many=True)
|
||||
display_fields = serializers.ListField(
|
||||
child=serializers.CharField(),
|
||||
required=False,
|
||||
allow_null=True,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = SavedView
|
||||
@@ -1471,11 +1476,13 @@ class SavedViewSerializer(OwnedObjectSerializer):
|
||||
attrs = super().validate(attrs)
|
||||
if "display_fields" in attrs and attrs["display_fields"] is not None:
|
||||
for field in attrs["display_fields"]:
|
||||
if (
|
||||
SavedView.DisplayFields.CUSTOM_FIELD[:-2] in field
|
||||
): # i.e. check for 'custom_field_' prefix
|
||||
field_id = int(re.search(r"\d+", field)[0])
|
||||
if not CustomField.objects.filter(id=field_id).exists():
|
||||
# i.e. 'custom_field_' followed by the id of a custom field
|
||||
custom_field = re.fullmatch(
|
||||
rf"{re.escape(SavedView.DisplayFields.CUSTOM_FIELD[:-2])}(\d+)",
|
||||
field,
|
||||
)
|
||||
if custom_field:
|
||||
if not CustomField.objects.filter(id=custom_field[1]).exists():
|
||||
raise serializers.ValidationError(
|
||||
f"Invalid field: {field}",
|
||||
)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import pytest
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import CustomField
|
||||
from documents.models import SavedView
|
||||
|
||||
|
||||
class TestSavedViewDisplayFields:
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[
|
||||
pytest.param(["custom_field_abc"], id="no-id"),
|
||||
pytest.param(["custom_field_"], id="empty-id"),
|
||||
pytest.param(["xcustom_field_{id}"], id="prefixed"),
|
||||
pytest.param(["custom_field_{id}x"], id="suffixed"),
|
||||
pytest.param([1], id="not-a-string"),
|
||||
],
|
||||
)
|
||||
def test_malformed_display_fields_are_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
value: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A saved view and a custom field
|
||||
WHEN:
|
||||
- Its display fields are patched to something that names no field
|
||||
THEN:
|
||||
- The response is a 400 and the stored display fields are unchanged
|
||||
"""
|
||||
custom_field = CustomField.objects.create(
|
||||
name="cf",
|
||||
data_type=CustomField.FieldDataType.STRING,
|
||||
)
|
||||
view = SavedView.objects.create(
|
||||
name="view",
|
||||
owner=admin_user,
|
||||
sort_field="created",
|
||||
display_fields=["title"],
|
||||
)
|
||||
if isinstance(value, list):
|
||||
value = [
|
||||
item.format(id=custom_field.pk) if isinstance(item, str) else item
|
||||
for item in value
|
||||
]
|
||||
|
||||
response = admin_client.patch(
|
||||
f"/api/saved_views/{view.pk}/",
|
||||
{"display_fields": value},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
view.refresh_from_db()
|
||||
assert view.display_fields == ["title"]
|
||||
|
||||
def test_a_custom_field_display_name_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
) -> None:
|
||||
custom_field = CustomField.objects.create(
|
||||
name="cf",
|
||||
data_type=CustomField.FieldDataType.STRING,
|
||||
)
|
||||
view = SavedView.objects.create(
|
||||
name="view",
|
||||
owner=admin_user,
|
||||
sort_field="created",
|
||||
)
|
||||
|
||||
response = admin_client.patch(
|
||||
f"/api/saved_views/{view.pk}/",
|
||||
{"display_fields": ["title", f"custom_field_{custom_field.pk}"]},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
@@ -1,30 +0,0 @@
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from documents.caching import CLASSIFIER_VERSION_KEY
|
||||
from documents.caching import get_suggestion_cache
|
||||
from documents.caching import get_suggestion_cache_key
|
||||
from documents.classifier import DocumentClassifier
|
||||
|
||||
|
||||
class TestGetSuggestionCache:
|
||||
def test_rejected_entry_is_a_cache_miss(self, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document suggestion entry the cache serializer rejected, which
|
||||
get_many reports as None
|
||||
- A classifier version entry matching the current format
|
||||
WHEN:
|
||||
- The suggestion cache is read
|
||||
THEN:
|
||||
- It is treated as a cache miss
|
||||
"""
|
||||
doc_key = get_suggestion_cache_key(1)
|
||||
mocker.patch(
|
||||
"documents.caching.cache.get_many",
|
||||
return_value={
|
||||
CLASSIFIER_VERSION_KEY: DocumentClassifier.FORMAT_VERSION,
|
||||
doc_key: None,
|
||||
},
|
||||
)
|
||||
|
||||
assert get_suggestion_cache(1) is None
|
||||
@@ -1,40 +0,0 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from paperless.signed_pickle import SignedPickleError
|
||||
from paperless.signed_pickle import signed_pickle_dumps
|
||||
from paperless.signed_pickle import signed_pickle_loads
|
||||
|
||||
logger = logging.getLogger("paperless.cache")
|
||||
|
||||
|
||||
class SignedRedisSerializer:
|
||||
"""
|
||||
Cache serializer for Django's RedisCache which HMAC-signs every pickled value.
|
||||
|
||||
Django's default serializer unpickles whatever it finds under a key, so anything
|
||||
able to write to the Redis instance could get code run in the web server, for
|
||||
example through a session entry. Values are signed with SECRET_KEY on write and
|
||||
verified before unpickling on read, the same protection the Celery messages on
|
||||
the same broker have.
|
||||
|
||||
An entry that fails verification is dropped and reported as a cache miss.
|
||||
"""
|
||||
|
||||
def dumps(self, obj: Any) -> bytes | int:
|
||||
# Like Django's own serializer, keep plain integers unpickled so incr() and
|
||||
# decr() stay atomic. Using type() rather than isinstance() excludes bool.
|
||||
if type(obj) is int:
|
||||
return obj
|
||||
return signed_pickle_dumps(obj)
|
||||
|
||||
def loads(self, data: bytes) -> Any:
|
||||
try:
|
||||
return int(data)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
return signed_pickle_loads(data)
|
||||
except SignedPickleError:
|
||||
logger.warning("Ignoring cache entry with an invalid signature")
|
||||
return None
|
||||
@@ -807,23 +807,17 @@ _CACHE_BACKEND = os.environ.get(
|
||||
)
|
||||
|
||||
|
||||
# Entries are HMAC-signed so values planted in Redis are never unpickled
|
||||
_CACHE_OPTIONS = {"serializer": "paperless.cache.SignedRedisSerializer"}
|
||||
|
||||
|
||||
def _parse_caches():
|
||||
return {
|
||||
"default": {
|
||||
"BACKEND": _CACHE_BACKEND,
|
||||
"LOCATION": _CHANNELS_REDIS_URL,
|
||||
"KEY_PREFIX": _REDIS_KEY_PREFIX,
|
||||
"OPTIONS": _CACHE_OPTIONS,
|
||||
},
|
||||
"read-cache": {
|
||||
"BACKEND": _CACHE_BACKEND,
|
||||
"LOCATION": cachalot_settings["CACHALOT_REDIS_URL"],
|
||||
"KEY_PREFIX": _REDIS_KEY_PREFIX,
|
||||
"OPTIONS": _CACHE_OPTIONS,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
import pickle
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from django.conf import settings
|
||||
|
||||
from paperless.cache import SignedRedisSerializer
|
||||
from paperless.signed_pickle import compute_signature
|
||||
|
||||
|
||||
class _Evil:
|
||||
def __init__(self, marker: Path) -> None:
|
||||
self.marker = marker
|
||||
|
||||
def __reduce__(self) -> tuple[Any, tuple[str]]:
|
||||
return (self.marker.write_text, ("pwned",))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def serializer() -> SignedRedisSerializer:
|
||||
return SignedRedisSerializer()
|
||||
|
||||
|
||||
class TestSignedRedisSerializer:
|
||||
def test_round_trip(self, serializer: SignedRedisSerializer) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A nested value
|
||||
WHEN:
|
||||
- It is serialized and then deserialized
|
||||
THEN:
|
||||
- The original value is returned
|
||||
"""
|
||||
value = {"a": [1, 2, 3], "b": ("x", None)}
|
||||
|
||||
assert serializer.loads(serializer.dumps(value)) == value
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "stored_type"),
|
||||
[
|
||||
pytest.param(7, int, id="int"),
|
||||
pytest.param(True, bytes, id="bool"),
|
||||
],
|
||||
)
|
||||
def test_only_plain_integers_are_stored_raw(
|
||||
self,
|
||||
serializer: SignedRedisSerializer,
|
||||
value: object,
|
||||
stored_type: type,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A plain integer or a bool
|
||||
WHEN:
|
||||
- The value is serialized
|
||||
THEN:
|
||||
- Only the integer is stored unpickled, so incr/decr stay atomic
|
||||
"""
|
||||
assert type(serializer.dumps(value)) is stored_type
|
||||
|
||||
def test_raw_integer_is_loaded(self, serializer: SignedRedisSerializer) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An integer as stored by Redis incr/decr
|
||||
WHEN:
|
||||
- It is deserialized
|
||||
THEN:
|
||||
- The integer is returned without signature verification
|
||||
"""
|
||||
assert serializer.loads(b"7") == 7
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"forge",
|
||||
[
|
||||
pytest.param(lambda data: data, id="unsigned"),
|
||||
pytest.param(
|
||||
lambda data: compute_signature(b"other data") + data,
|
||||
id="signature-for-other-data",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_forged_pickle_is_not_loaded(
|
||||
self,
|
||||
serializer: SignedRedisSerializer,
|
||||
tmp_path: Path,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
forge: Callable[[bytes], bytes],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A malicious pickle without a valid signature
|
||||
WHEN:
|
||||
- It is deserialized
|
||||
THEN:
|
||||
- It is treated as a cache miss, never executed, and a warning is logged
|
||||
"""
|
||||
marker = tmp_path / "marker"
|
||||
payload = forge(pickle.dumps(_Evil(marker)))
|
||||
|
||||
assert serializer.loads(payload) is None
|
||||
assert not marker.exists()
|
||||
assert "invalid signature" in caplog.text
|
||||
|
||||
|
||||
class TestCacheSettings:
|
||||
@pytest.mark.parametrize(
|
||||
"alias",
|
||||
[
|
||||
pytest.param("default", id="default"),
|
||||
pytest.param("read-cache", id="read-cache"),
|
||||
],
|
||||
)
|
||||
def test_caches_use_signed_serializer(self, alias: str) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The configured cache aliases
|
||||
WHEN:
|
||||
- Their options are inspected
|
||||
THEN:
|
||||
- Each uses the signed serializer
|
||||
"""
|
||||
options = settings.CACHES[alias]["OPTIONS"]
|
||||
|
||||
assert options["serializer"] == "paperless.cache.SignedRedisSerializer"
|
||||
Reference in new issue
Block a user