mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-12-01 09:00:25 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7aad30b134 |
No files matched your search
@@ -0,0 +1,40 @@
|
||||
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,17 +807,23 @@ _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,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import pickle
|
||||
|
||||
import pytest
|
||||
from django.conf import settings
|
||||
from django.core.cache.backends.redis import RedisCache
|
||||
|
||||
from paperless.cache import SignedRedisSerializer
|
||||
from paperless.signed_pickle import compute_signature
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def serializer() -> SignedRedisSerializer:
|
||||
return SignedRedisSerializer()
|
||||
|
||||
|
||||
class TestSignedRedisSerializer:
|
||||
def test_round_trip(self, serializer: SignedRedisSerializer) -> None:
|
||||
value = {"a": [1, 2, 3], "b": ("x", None)}
|
||||
assert serializer.loads(serializer.dumps(value)) == value
|
||||
|
||||
def test_integers_are_stored_raw(self, serializer: SignedRedisSerializer) -> None:
|
||||
# incr/decr operate on the raw value in Redis
|
||||
assert serializer.dumps(7) == 7
|
||||
assert serializer.loads(b"7") == 7
|
||||
flag = bool(1)
|
||||
assert isinstance(serializer.dumps(flag), bytes)
|
||||
|
||||
def test_unsigned_pickle_is_not_loaded(
|
||||
self,
|
||||
serializer: SignedRedisSerializer,
|
||||
tmp_path,
|
||||
) -> None:
|
||||
marker = tmp_path / "marker"
|
||||
|
||||
class Evil:
|
||||
def __reduce__(self):
|
||||
return (marker.write_text, ("pwned",))
|
||||
|
||||
assert serializer.loads(pickle.dumps(Evil())) is None
|
||||
assert not marker.exists()
|
||||
|
||||
def test_pickle_signed_with_other_key_is_not_loaded(
|
||||
self,
|
||||
serializer: SignedRedisSerializer,
|
||||
tmp_path,
|
||||
) -> None:
|
||||
marker = tmp_path / "marker"
|
||||
|
||||
class Evil:
|
||||
def __reduce__(self):
|
||||
return (marker.write_text, ("pwned",))
|
||||
|
||||
data = pickle.dumps(Evil())
|
||||
forged = compute_signature(b"not the real data") + data
|
||||
assert serializer.loads(forged) is None
|
||||
assert not marker.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("alias", ["default", "read-cache"])
|
||||
def test_redis_caches_use_signed_serializer(alias: str) -> None:
|
||||
# The test settings use LocMemCache, so check the configuration is wired up
|
||||
# and that RedisCache honours it
|
||||
options = settings.CACHES[alias]["OPTIONS"]
|
||||
assert options["serializer"] == "paperless.cache.SignedRedisSerializer"
|
||||
cache = RedisCache("redis://localhost:6379", {"OPTIONS": options})
|
||||
assert isinstance(cache._cache._serializer, SignedRedisSerializer)
|
||||
Reference in new issue
Block a user