Compare commits

..
Author SHA1 Message Date
Trenton H b783d5e895 Fix: sign cache entries so values planted in Redis are never unpickled (#14950)
* Fix: sign cache entries so values planted in Redis are never unpickled

* Guards against the small window where the suggestion cache could return a version and a None from get_many
2026-12-01 16:42:02 +00:00
dependabot[bot] 3c295be9b4 docker-compose(deps): Bump nginx in /docker/compose (#14928)
Bumps nginx from 1.31.7-alpine to 1.31.9-alpine.

---
updated-dependencies:
- dependency-name: nginx
  dependency-version: 1.31.9-alpine
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-01 07:54:03 -08:00
8 changed files with 208 additions and 125 deletions

No files matched your search

+1 -1
View File
@@ -35,7 +35,7 @@ services:
- "3143:3143" # IMAP
restart: unless-stopped
nginx:
image: docker.io/nginx:1.31.7-alpine
image: docker.io/nginx:1.31.9-alpine
hostname: nginx
container_name: nginx
ports:
+4 -3
View File
@@ -73,9 +73,10 @@ 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
if doc_key in cache_hits:
doc_suggestions: SuggestionCacheData = cache_hits[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 classifier format is the same
# The classifier hash is the same
# Then the suggestions can be used
@@ -1,114 +0,0 @@
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import Document
from paperless_testing.dirs import PaperlessDirs
from paperless_testing.factories import DocumentFactory
@pytest.fixture
def archived_document(paperless_dirs: PaperlessDirs) -> Document:
document = DocumentFactory.create(
title="title",
filename="source.pdf",
archive_filename="archived.pdf",
mime_type="application/pdf",
)
document.source_path.write_bytes(b"source")
document.archive_path.write_bytes(b"archive")
return document
class TestDownloadFollowFormatting:
@pytest.mark.parametrize("value", ["false", "0", "no", "off"])
def test_false_values_use_the_public_filename(
self,
admin_client: APIClient,
archived_document: Document,
value: str,
) -> None:
"""
GIVEN:
- A document whose name on disk differs from its public name
WHEN:
- It is downloaded with follow_formatting set to a false value
THEN:
- The public name is used, the string "false" is not true
"""
response = admin_client.get(
f"/api/documents/{archived_document.pk}/download/?follow_formatting={value}",
)
assert response.status_code == status.HTTP_200_OK
assert "title.pdf" in response["Content-Disposition"]
response.close()
@pytest.mark.parametrize("value", ["true", "True", "1", "yes", "on"])
def test_true_values_use_the_name_on_disk(
self,
admin_client: APIClient,
archived_document: Document,
value: str,
) -> None:
"""
GIVEN:
- A document whose name on disk differs from its public name
WHEN:
- It is downloaded with follow_formatting set to a true value
THEN:
- The name on disk is used
"""
response = admin_client.get(
f"/api/documents/{archived_document.pk}/download/?follow_formatting={value}",
)
assert "archived.pdf" in response["Content-Disposition"]
response.close()
def test_a_value_that_is_not_a_boolean_is_a_400(
self,
admin_client: APIClient,
archived_document: Document,
) -> None:
response = admin_client.get(
f"/api/documents/{archived_document.pk}/download/?follow_formatting=maybe",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
class TestDownloadFilenameControlCharacters:
def test_control_characters_do_not_fail_the_download(
self,
admin_client: APIClient,
paperless_dirs: PaperlessDirs,
) -> None:
"""
GIVEN:
- A document whose name on disk holds control characters, a title can
WHEN:
- It is downloaded following the name on disk
THEN:
- The download works and no control character is in the header
"""
document = DocumentFactory.create(
filename="source.pdf",
archive_filename="ar\r\nchi\x12ved.pdf",
mime_type="application/pdf",
)
document.source_path.write_bytes(b"source")
document.archive_path.parent.mkdir(parents=True, exist_ok=True)
document.archive_path.write_bytes(b"archive")
response = admin_client.get(
f"/api/documents/{document.pk}/download/?follow_formatting=true",
)
assert response.status_code == status.HTTP_200_OK
assert 'filename="archived.pdf"' in response["Content-Disposition"]
assert not any(
ord(char) < 32 or ord(char) == 127
for char in response["Content-Disposition"]
)
response.close()
+30
View File
@@ -0,0 +1,30 @@
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 -7
View File
@@ -1461,10 +1461,7 @@ class DocumentViewSet(
use_archive=not self.original_requested(request)
and file_doc.has_archive_version,
disposition=disposition,
# The query value is a string, "false" must not count as true
follow_formatting=serializers.BooleanField(default=False).run_validation(
request.query_params.get("follow_formatting", serializers.empty),
),
follow_formatting=request.query_params.get("follow_formatting", False),
)
def get_metadata(self, file, mime_type):
@@ -5275,9 +5272,6 @@ def serve_file(
.replace("\\", "_")
.replace('"', "_")
)
# A name can hold control characters, which a header cannot carry. The encoded
# form below percent encodes them, only this plain fallback needs them removed
filename_normalized = "".join(c for c in filename_normalized if c.isprintable())
filename_encoded = quote(filename)
content_disposition = (
f"{disposition}; "
+40
View File
@@ -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
+6
View File
@@ -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,
},
}
+126
View File
@@ -0,0 +1,126 @@
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"