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