mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-30 08:35:24 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b05b8289b | ||
|
|
d35c6e6e97 | ||
|
|
8b80913d3d | ||
|
|
51822d6273 | ||
|
|
1dc797e9be | ||
|
|
0cb56c49bb | ||
|
|
5cea561838 | ||
|
|
ca32553478 | ||
|
|
cfbb383514 |
No files matched your search
+4
-4
@@ -129,10 +129,10 @@ ARG RUNTIME_PACKAGES="\
|
||||
ghostscript \
|
||||
gnupg \
|
||||
icc-profiles-free \
|
||||
# PostgreSQL client library, used by psycopg
|
||||
libpq5 \
|
||||
# MariaDB client library, used by mysqlclient
|
||||
libmariadb3 \
|
||||
# PostgreSQL
|
||||
postgresql-client \
|
||||
# MySQL / MariaDB
|
||||
mariadb-client \
|
||||
# OCRmyPDF dependencies
|
||||
tesseract-ocr \
|
||||
tesseract-ocr-eng \
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Single-shot database readiness probe used by the init-wait-for-db s6 service.
|
||||
|
||||
Exits 0 if the database server is accepting connections, 1 otherwise. The
|
||||
retry and backoff loop lives in the calling shell script.
|
||||
|
||||
This replaces pg_isready / mariadb-admin ping, so the image does not need the
|
||||
PostgreSQL or MariaDB command line clients. Like those tools, this only checks
|
||||
that the server answers. A server which responds with an error, such as bad
|
||||
credentials or an unknown database, counts as ready, so the real error is
|
||||
reported by the migrations step instead of this one timing out.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
CONNECT_TIMEOUT = 5
|
||||
|
||||
|
||||
def postgres_ready() -> bool:
|
||||
from psycopg import pq
|
||||
from psycopg.conninfo import make_conninfo
|
||||
|
||||
# This is libpq's PQping, which is what pg_isready uses. It reports OK when
|
||||
# the server answers, even if it would refuse these credentials, and REJECT
|
||||
# when the server is up but still starting or shutting down.
|
||||
conninfo = make_conninfo(
|
||||
host=os.environ.get("PAPERLESS_DBHOST", "localhost"),
|
||||
port=int(os.environ.get("PAPERLESS_DBPORT", "5432")),
|
||||
user=os.environ.get("PAPERLESS_DBUSER", "paperless"),
|
||||
connect_timeout=CONNECT_TIMEOUT,
|
||||
)
|
||||
return pq.PGconn.ping(conninfo.encode()) == pq.Ping.OK
|
||||
|
||||
|
||||
def mariadb_ready() -> bool:
|
||||
import MySQLdb
|
||||
|
||||
try:
|
||||
MySQLdb.connect(
|
||||
host=os.environ.get("PAPERLESS_DBHOST", "localhost"),
|
||||
port=int(os.environ.get("PAPERLESS_DBPORT", "3306")),
|
||||
user=os.environ.get("PAPERLESS_DBUSER", "paperless"),
|
||||
passwd=os.environ.get("PAPERLESS_DBPASS", "paperless"),
|
||||
connect_timeout=CONNECT_TIMEOUT,
|
||||
).close()
|
||||
return True
|
||||
except MySQLdb.OperationalError as e:
|
||||
# Codes below 2000 are errors sent by the server (access denied, too
|
||||
# many connections, ...). 2000+ are client side (can't connect, lost
|
||||
# connection), meaning the server was not reached.
|
||||
code = e.args[0] if e.args and isinstance(e.args[0], int) else 0
|
||||
return 0 < code < 2000
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if os.environ.get("PAPERLESS_DBENGINE") == "mariadb":
|
||||
ready = mariadb_ready()
|
||||
else:
|
||||
ready = postgres_ready()
|
||||
return 0 if ready else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -7,7 +7,6 @@ set -euo pipefail
|
||||
declare -r LOG_PREFIX="[init-db-wait]"
|
||||
|
||||
declare -ri TIMEOUT=60
|
||||
declare -r PROBE="/etc/s6-overlay/s6-rc.d/init-wait-for-db/db_ready.py"
|
||||
declare -i ATTEMPT=0
|
||||
declare -i DELAY=0
|
||||
declare -i STARTED_AT=${EPOCHSECONDS:?EPOCHSECONDS var unset}
|
||||
@@ -36,7 +35,11 @@ delay_next_attempt() {
|
||||
wait_for_postgres() {
|
||||
echo "${LOG_PREFIX} Waiting for PostgreSQL to start..."
|
||||
|
||||
while ! python3 "${PROBE}"; do
|
||||
local -r host="${PAPERLESS_DBHOST:-localhost}"
|
||||
local -r port="${PAPERLESS_DBPORT:-5432}"
|
||||
local -r user="${PAPERLESS_DBUSER:-paperless}"
|
||||
|
||||
while ! pg_isready -h "${host}" -p "${port}" --username "${user}"; do
|
||||
delay_next_attempt
|
||||
done
|
||||
echo "${LOG_PREFIX} Connected to PostgreSQL"
|
||||
@@ -45,7 +48,10 @@ wait_for_postgres() {
|
||||
wait_for_mariadb() {
|
||||
echo "${LOG_PREFIX} Waiting for MariaDB to start..."
|
||||
|
||||
while ! python3 "${PROBE}"; do
|
||||
local -r host="${PAPERLESS_DBHOST:-localhost}"
|
||||
local -r port="${PAPERLESS_DBPORT:-3306}"
|
||||
|
||||
while ! mariadb-admin --host="${host}" --port="${port}" --skip-ssl ping --silent >/dev/null 2>&1; do
|
||||
delay_next_attempt
|
||||
done
|
||||
echo "${LOG_PREFIX} Connected to MariaDB"
|
||||
|
||||
+137
-21
@@ -6,13 +6,17 @@ import json
|
||||
import logging
|
||||
import operator
|
||||
from contextlib import contextmanager
|
||||
from datetime import UTC
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
from decimal import InvalidOperation
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import Any
|
||||
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.db import models
|
||||
from django.db.models import Case
|
||||
from django.db.models import CharField
|
||||
from django.db.models import Count
|
||||
@@ -29,13 +33,15 @@ from django.db.models.functions import NullIf
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django_filters import DateFilter
|
||||
from django_filters.fields import IsoDateTimeField
|
||||
from django_filters.filters import IsoDateTimeFilter
|
||||
from django_filters.rest_framework import BooleanFilter
|
||||
from django_filters.rest_framework import CharFilter
|
||||
from django_filters.rest_framework import DateTimeFilter
|
||||
from django_filters.rest_framework import Filter
|
||||
from django_filters.rest_framework import FilterSet
|
||||
from django_filters.rest_framework import MultipleChoiceFilter
|
||||
from django_filters.rest_framework import NumberFilter
|
||||
from django_filters.rest_framework.filterset import FILTER_FOR_DBFIELD_DEFAULTS
|
||||
from drf_spectacular.utils import extend_schema_field
|
||||
from guardian.utils import get_group_obj_perms_model
|
||||
from guardian.utils import get_user_obj_perms_model
|
||||
@@ -95,7 +101,100 @@ CUSTOM_FIELD_QUERY_MAX_ATOMS = 20
|
||||
logger = logging.getLogger("paperless.api")
|
||||
|
||||
|
||||
class CorrespondentFilterSet(FilterSet):
|
||||
# The smallest and largest values a 64 bit integer column can hold. Nothing outside can
|
||||
# match a row, and handing it to the database raises an error on some backends.
|
||||
INT64_MIN = -(2**63)
|
||||
INT64_MAX = 2**63 - 1
|
||||
# Real UTC offsets run from -12:00 to +14:00, databases reject anything much larger.
|
||||
MAX_UTC_OFFSET = timedelta(hours=14)
|
||||
DATE_PART_BOUNDS = {"year": (1, 9999), "month": (1, 12), "day": (1, 31)}
|
||||
# A datetime year is turned into UTC boundaries in the active timezone, so the first
|
||||
# and last year overflow for any timezone other than UTC
|
||||
DATETIME_YEAR_BOUNDS = (2, 9998)
|
||||
|
||||
|
||||
def in_id_range(value: int) -> bool:
|
||||
return INT64_MIN <= value <= INT64_MAX
|
||||
|
||||
|
||||
class BoundedDecimalField(forms.DecimalField):
|
||||
"""
|
||||
django-filter only bounds numbers at 1e50, which is far past any integer column
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs: Any) -> None:
|
||||
kwargs.setdefault("min_value", INT64_MIN)
|
||||
kwargs.setdefault("max_value", INT64_MAX)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class BoundedNumberFilter(NumberFilter):
|
||||
field_class = BoundedDecimalField
|
||||
|
||||
|
||||
class BoundedDateTimeField(IsoDateTimeField):
|
||||
def clean(self, value: Any) -> Any:
|
||||
value = super().clean(value)
|
||||
if value is not None and timezone.is_aware(value):
|
||||
offset = value.utcoffset()
|
||||
if offset is not None and abs(offset) > MAX_UTC_OFFSET:
|
||||
raise forms.ValidationError(
|
||||
_("Enter a valid UTC offset."),
|
||||
code="invalid",
|
||||
)
|
||||
try:
|
||||
value.astimezone(UTC)
|
||||
except OverflowError:
|
||||
raise forms.ValidationError(
|
||||
_("Enter a valid date and time."),
|
||||
code="invalid",
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
class BoundedDateTimeFilter(IsoDateTimeFilter):
|
||||
field_class = BoundedDateTimeField
|
||||
|
||||
|
||||
class BoundedFilterSet(FilterSet):
|
||||
"""
|
||||
A FilterSet whose generated number and datetime filters reject values the database
|
||||
cannot hold, as a 400, instead of failing later as a server error
|
||||
"""
|
||||
|
||||
FILTER_DEFAULTS = {
|
||||
**FILTER_FOR_DBFIELD_DEFAULTS,
|
||||
**{
|
||||
field: {"filter_class": BoundedNumberFilter}
|
||||
for field in (
|
||||
models.AutoField,
|
||||
models.BigAutoField,
|
||||
models.SmallAutoField,
|
||||
models.IntegerField,
|
||||
models.BigIntegerField,
|
||||
models.SmallIntegerField,
|
||||
models.PositiveIntegerField,
|
||||
models.PositiveSmallIntegerField,
|
||||
models.PositiveBigIntegerField,
|
||||
)
|
||||
},
|
||||
models.DateTimeField: {"filter_class": BoundedDateTimeFilter},
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def filter_for_field(cls, field, field_name, lookup_expr=None):
|
||||
filter_ = super().filter_for_field(field, field_name, lookup_expr)
|
||||
# The lookup resolves to a plain integer field, so only here is it known to be
|
||||
# a year, month or day
|
||||
bounds = DATE_PART_BOUNDS.get(lookup_expr)
|
||||
if lookup_expr == "year" and isinstance(field, models.DateTimeField):
|
||||
bounds = DATETIME_YEAR_BOUNDS
|
||||
if bounds is not None and isinstance(filter_, NumberFilter):
|
||||
filter_.extra["min_value"], filter_.extra["max_value"] = bounds
|
||||
return filter_
|
||||
|
||||
|
||||
class CorrespondentFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = Correspondent
|
||||
fields = {
|
||||
@@ -104,7 +203,7 @@ class CorrespondentFilterSet(FilterSet):
|
||||
}
|
||||
|
||||
|
||||
class TagFilterSet(FilterSet):
|
||||
class TagFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = Tag
|
||||
fields = {
|
||||
@@ -119,7 +218,7 @@ class TagFilterSet(FilterSet):
|
||||
)
|
||||
|
||||
|
||||
class DocumentTypeFilterSet(FilterSet):
|
||||
class DocumentTypeFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = DocumentType
|
||||
fields = {
|
||||
@@ -128,7 +227,7 @@ class DocumentTypeFilterSet(FilterSet):
|
||||
}
|
||||
|
||||
|
||||
class StoragePathFilterSet(FilterSet):
|
||||
class StoragePathFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = StoragePath
|
||||
fields = {
|
||||
@@ -155,9 +254,21 @@ class ObjectFilter(Filter):
|
||||
return qs
|
||||
|
||||
if self.in_list:
|
||||
qs = qs.filter(**{f"{self.field_name}__id__in": object_ids}).distinct()
|
||||
qs = qs.filter(
|
||||
**{
|
||||
f"{self.field_name}__id__in": [
|
||||
obj_id for obj_id in object_ids if in_id_range(obj_id)
|
||||
],
|
||||
},
|
||||
).distinct()
|
||||
else:
|
||||
for obj_id in object_ids:
|
||||
if not in_id_range(obj_id):
|
||||
# No row has this id: excluding it changes nothing, requiring it
|
||||
# matches nothing
|
||||
if self.exclude:
|
||||
continue
|
||||
return qs.none()
|
||||
if self.exclude:
|
||||
qs = qs.exclude(**{f"{self.field_name}__id": obj_id})
|
||||
else:
|
||||
@@ -242,7 +353,7 @@ class SharedByUser(Filter):
|
||||
)
|
||||
|
||||
|
||||
class CustomFieldFilterSet(FilterSet):
|
||||
class CustomFieldFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = CustomField
|
||||
fields = {
|
||||
@@ -251,8 +362,8 @@ class CustomFieldFilterSet(FilterSet):
|
||||
}
|
||||
|
||||
|
||||
class WorkflowFilterSet(FilterSet):
|
||||
trigger_type = NumberFilter(field_name="triggers__type", distinct=True)
|
||||
class WorkflowFilterSet(BoundedFilterSet):
|
||||
trigger_type = BoundedNumberFilter(field_name="triggers__type", distinct=True)
|
||||
|
||||
class Meta:
|
||||
model = Workflow
|
||||
@@ -852,7 +963,7 @@ class CustomFieldQueryFilter(Filter):
|
||||
return qs.filter(pk__in=matching_ids)
|
||||
|
||||
|
||||
class DocumentFilterSet(FilterSet):
|
||||
class DocumentFilterSet(BoundedFilterSet):
|
||||
has_duplicates = BooleanFilter(method="filter_has_duplicates")
|
||||
|
||||
def __init__(self, *args: Any, user: Any = None, **kwargs: Any) -> None:
|
||||
@@ -984,7 +1095,7 @@ class DocumentFilterSet(FilterSet):
|
||||
}
|
||||
|
||||
|
||||
class ShareLinkFilterSet(FilterSet):
|
||||
class ShareLinkFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = ShareLink
|
||||
fields = {
|
||||
@@ -993,7 +1104,7 @@ class ShareLinkFilterSet(FilterSet):
|
||||
}
|
||||
|
||||
|
||||
class ShareLinkBundleFilterSet(FilterSet):
|
||||
class ShareLinkBundleFilterSet(BoundedFilterSet):
|
||||
documents = Filter(method="filter_documents")
|
||||
|
||||
class Meta:
|
||||
@@ -1013,10 +1124,13 @@ class ShareLinkBundleFilterSet(FilterSet):
|
||||
return queryset.none()
|
||||
if not ids:
|
||||
return queryset
|
||||
ids = [item for item in ids if in_id_range(item)]
|
||||
if not ids:
|
||||
return queryset.none()
|
||||
return queryset.filter(documents__in=ids).distinct()
|
||||
|
||||
|
||||
class PaperlessTaskFilterSet(FilterSet):
|
||||
class PaperlessTaskFilterSet(BoundedFilterSet):
|
||||
name = CharFilter(
|
||||
method="filter_name",
|
||||
label="Name",
|
||||
@@ -1052,13 +1166,13 @@ class PaperlessTaskFilterSet(FilterSet):
|
||||
field_name="acknowledged",
|
||||
)
|
||||
|
||||
date_created_after = DateTimeFilter(
|
||||
date_created_after = BoundedDateTimeFilter(
|
||||
field_name="date_created",
|
||||
lookup_expr="gte",
|
||||
label="Created After",
|
||||
)
|
||||
|
||||
date_created_before = DateTimeFilter(
|
||||
date_created_before = BoundedDateTimeFilter(
|
||||
field_name="date_created",
|
||||
lookup_expr="lte",
|
||||
label="Created Before",
|
||||
@@ -1110,9 +1224,10 @@ class PaperlessTaskFilterSet(FilterSet):
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
else:
|
||||
query |= Q(result_data__document_id=numeric_value) | Q(
|
||||
result_data__duplicate_of=numeric_value,
|
||||
)
|
||||
if in_id_range(numeric_value):
|
||||
query |= Q(result_data__document_id=numeric_value) | Q(
|
||||
result_data__duplicate_of=numeric_value,
|
||||
)
|
||||
|
||||
if "duplicate" in value.lower():
|
||||
query |= Q(result_data__duplicate_of__isnull=False)
|
||||
@@ -1184,12 +1299,13 @@ class DocumentsOrderingFilter(OrderingFilter):
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
param = request.query_params.get("ordering")
|
||||
if param and self.prefix in param:
|
||||
custom_field_id = int(param.split(self.prefix)[1])
|
||||
custom_field_suffix = param.split(self.prefix)[1]
|
||||
try:
|
||||
custom_field_id = int(custom_field_suffix)
|
||||
field = CustomField.objects.get(pk=custom_field_id)
|
||||
except CustomField.DoesNotExist:
|
||||
except (ValueError, CustomField.DoesNotExist):
|
||||
raise serializers.ValidationError(
|
||||
{self.prefix + str(custom_field_id): [_("Custom field not found")]},
|
||||
{self.prefix + custom_field_suffix: [_("Custom field not found")]},
|
||||
)
|
||||
|
||||
annotation = None
|
||||
|
||||
@@ -74,6 +74,10 @@ _LOCK_BACKOFF_CAP: Final[float] = 10.0 # seconds
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
# Upper bound on autocomplete suggestions. tantivy sizes its collector from the
|
||||
# requested limit, so an unbounded value aborts the whole process on allocation.
|
||||
MAX_AUTOCOMPLETE_LIMIT = 1000
|
||||
|
||||
|
||||
class ViewerGrant(NamedTuple):
|
||||
"""Direct user and group view grants for a single document.
|
||||
@@ -998,7 +1002,8 @@ class TantivyBackend:
|
||||
|
||||
Args:
|
||||
term: Prefix to match against autocomplete words
|
||||
limit: Maximum number of suggestions to return
|
||||
limit: Maximum number of suggestions to return, capped at
|
||||
MAX_AUTOCOMPLETE_LIMIT
|
||||
user: User for permission filtering (None for no filtering)
|
||||
|
||||
Returns:
|
||||
@@ -1021,7 +1026,7 @@ class TantivyBackend:
|
||||
"autocomplete_word",
|
||||
normalized_term,
|
||||
permission_query,
|
||||
limit,
|
||||
min(limit, MAX_AUTOCOMPLETE_LIMIT),
|
||||
)
|
||||
|
||||
return [x[0] for x in matches]
|
||||
|
||||
@@ -53,6 +53,7 @@ if settings.AUDIT_LOG_ENABLED:
|
||||
from documents import bulk_edit
|
||||
from documents.data_models import DocumentSource
|
||||
from documents.filters import CustomFieldQueryParser
|
||||
from documents.filters import in_id_range
|
||||
from documents.models import Correspondent
|
||||
from documents.models import CustomField
|
||||
from documents.models import CustomFieldInstance
|
||||
@@ -112,6 +113,10 @@ if TYPE_CHECKING:
|
||||
|
||||
logger = logging.getLogger("paperless.serializers")
|
||||
|
||||
# How much of an upload is read to detect its type. libmagic examines at most
|
||||
# 7 MiB (its default bytes_max), so this is more than it will ever look at.
|
||||
_MIME_SNIFF_BYTES = 8 * 1024 * 1024
|
||||
|
||||
|
||||
# https://www.django-rest-framework.org/api-guide/serializers/#example
|
||||
class DynamicFieldsModelSerializer(serializers.ModelSerializer[Any]):
|
||||
@@ -226,7 +231,7 @@ class SetPermissionsMixin:
|
||||
def _validate_user_ids(self, user_ids):
|
||||
users = User.objects.none()
|
||||
if user_ids is not None:
|
||||
users = User.objects.filter(id__in=user_ids)
|
||||
users = User.objects.filter(id__in=[i for i in user_ids if in_id_range(i)])
|
||||
if not users.count() == len(user_ids):
|
||||
raise serializers.ValidationError(
|
||||
"Some users in don't exist or were specified twice.",
|
||||
@@ -236,7 +241,9 @@ class SetPermissionsMixin:
|
||||
def _validate_group_ids(self, group_ids):
|
||||
groups = Group.objects.none()
|
||||
if group_ids is not None:
|
||||
groups = Group.objects.filter(id__in=group_ids)
|
||||
groups = Group.objects.filter(
|
||||
id__in=[i for i in group_ids if in_id_range(i)],
|
||||
)
|
||||
if not groups.count() == len(group_ids):
|
||||
raise serializers.ValidationError(
|
||||
"Some groups in don't exist or were specified twice.",
|
||||
@@ -2363,8 +2370,9 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
)
|
||||
|
||||
def validate_document(self, document):
|
||||
document_data = document.file.read()
|
||||
mime_type = magic.from_buffer(document_data, mime=True)
|
||||
# libmagic only examines a bounded prefix, so an upload of any size is
|
||||
# never read into memory just to detect its type
|
||||
mime_type = magic.from_buffer(document.read(_MIME_SNIFF_BYTES), mime=True)
|
||||
|
||||
if not is_mime_type_supported(mime_type):
|
||||
if (
|
||||
@@ -2380,7 +2388,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
_("File type %(type)s not supported") % {"type": mime_type},
|
||||
)
|
||||
|
||||
return document.name, document_data
|
||||
return document.name, document
|
||||
|
||||
def validate_correspondent(self, correspondent):
|
||||
if correspondent:
|
||||
|
||||
@@ -1069,6 +1069,13 @@ class TestAutocomplete:
|
||||
results = backend.autocomplete("micro", limit=10)
|
||||
assert "microsoft" in results
|
||||
|
||||
def test_huge_limit_is_clamped(self, backend: TantivyBackend) -> None:
|
||||
"""An oversized limit must be capped, not handed to tantivy as-is."""
|
||||
doc = DocumentFactory.create(title="Microsoft invoice", content="payment")
|
||||
backend.add_or_update(doc)
|
||||
|
||||
assert "microsoft" in backend.autocomplete("micro", limit=10**15)
|
||||
|
||||
def test_results_ordered_by_document_frequency(
|
||||
self,
|
||||
backend: TantivyBackend,
|
||||
|
||||
@@ -2089,6 +2089,38 @@ class TestDocumentApi(DirectoriesMixin, ConsumeTaskMixin, APITestCase):
|
||||
self.assertIsNone(overrides.document_type_id)
|
||||
self.assertIsNone(overrides.tag_ids)
|
||||
|
||||
def test_upload_type_is_detected_from_a_prefix(self) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An upload larger than the prefix read to detect its type
|
||||
WHEN:
|
||||
- The document is posted
|
||||
THEN:
|
||||
- The type is detected from the prefix and the upload is accepted
|
||||
- The file handed to the consumer holds the whole upload
|
||||
"""
|
||||
self.consume_file_mock.return_value = celery.result.AsyncResult(
|
||||
id=str(uuid.uuid4()),
|
||||
)
|
||||
content = SIMPLE_DIGITAL_PDF.read_bytes()
|
||||
|
||||
with (
|
||||
mock.patch("documents.serialisers._MIME_SNIFF_BYTES", 1024),
|
||||
SimpleUploadedFile(
|
||||
"simple.pdf",
|
||||
content,
|
||||
content_type="application/pdf",
|
||||
) as f,
|
||||
):
|
||||
response = self.client.post(
|
||||
"/api/documents/post_document/",
|
||||
{"document": f},
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
input_doc, _ = self.assert_queue_consumption_task_call_args()
|
||||
self.assertEqual(input_doc.original_file.read_bytes(), content)
|
||||
|
||||
def test_upload_with_path_traversal_filename_is_reduced_to_basename(self) -> None:
|
||||
self.consume_file_mock.return_value = celery.result.AsyncResult(
|
||||
id=str(uuid.uuid4()),
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from django.core.management import call_command
|
||||
from django.core.management.base import CommandError
|
||||
@@ -337,3 +339,41 @@ class TestDocumentListObjectFilterSchema:
|
||||
param = next(p for p in params if p["name"] == param_name)
|
||||
assert param["schema"] == {"type": "array", "items": {"type": "integer"}}
|
||||
assert param["explode"] is False
|
||||
|
||||
|
||||
class TestOauthCallbackSchema:
|
||||
@pytest.mark.parametrize("name", ["code", "state"])
|
||||
def test_empty_code_and_state_are_not_schema_valid(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
name: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The code and state parameters of the OAuth callback are read
|
||||
THEN:
|
||||
- They are required and not empty, the view answers 400 to an empty one
|
||||
"""
|
||||
params = api_schema["paths"]["/api/oauth/callback/"]["get"]["parameters"]
|
||||
param = next(p for p in params if p["name"] == name)
|
||||
|
||||
assert param["required"] is True
|
||||
assert param["schema"]["minLength"] == 1
|
||||
|
||||
|
||||
class TestOcrPageImageSchema:
|
||||
def test_page_image_is_declared_as_png(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The 200 response of the OCR template page image is read
|
||||
THEN:
|
||||
- It is a PNG, which is what the view serves
|
||||
"""
|
||||
path = "/api/ocr_templates/document-page-image/{doc_id}/{page}/"
|
||||
content = api_schema["paths"][path]["get"]["responses"]["200"]["content"]
|
||||
|
||||
assert list(content) == ["image/png"]
|
||||
@@ -996,6 +996,9 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
|
||||
response = self.client.get("/api/search/autocomplete/?term=test&limit=-1")
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
response = self.client.get("/api/search/autocomplete/?term=test&limit=null")
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
response = self.client.get("/api/search/autocomplete/")
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import Document
|
||||
from documents.models import Tag
|
||||
from paperless_testing.factories import CorrespondentFactory
|
||||
from paperless_testing.factories import DocumentFactory
|
||||
from paperless_testing.factories import TagFactory
|
||||
|
||||
HUGE = 2**63 # one above the largest signed 64 bit integer
|
||||
|
||||
|
||||
class TestFilterInputBounds:
|
||||
@pytest.mark.parametrize(
|
||||
("path", "query"),
|
||||
[
|
||||
pytest.param("/api/tags/", f"id__in={HUGE}", id="tags-id-in"),
|
||||
pytest.param("/api/tags/", f"id={HUGE}", id="tags-id-exact"),
|
||||
pytest.param("/api/tags/", f"id__in=1,{HUGE}", id="tags-id-in-mixed"),
|
||||
pytest.param("/api/documents/", f"id__in={HUGE}", id="documents-id-in"),
|
||||
pytest.param("/api/documents/", "created__year=0", id="year-zero"),
|
||||
pytest.param("/api/documents/", "created__year=10000", id="year-too-big"),
|
||||
pytest.param("/api/documents/", "created__month=13", id="month-13"),
|
||||
pytest.param("/api/documents/", "created__day=0", id="day-zero"),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"created__year=-10000000000000000",
|
||||
id="year-hugely-negative",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"added__gt=2024-01-01T00:00:00%2B16:29",
|
||||
id="offset-too-large",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"added__gt=0001-01-01T00:00:00%2B05:00",
|
||||
id="utc-conversion-overflows",
|
||||
),
|
||||
pytest.param("/api/share_links/", "created__year=0", id="share-links-year"),
|
||||
pytest.param(
|
||||
"/api/share_links/",
|
||||
f"expiration__day={HUGE}",
|
||||
id="share-links-day",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/share_link_bundles/",
|
||||
"expiration__year=100000000000000000",
|
||||
id="bundles-year",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/tasks/",
|
||||
"date_created_after=2024-01-01T00:00:00%2B16:29",
|
||||
id="tasks-offset",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"ordering=custom_field_abc",
|
||||
id="ordering-not-a-number",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
f"ordering=custom_field_{HUGE}",
|
||||
id="ordering-out-of-range",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_out_of_range_value_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
path: str,
|
||||
query: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A filter or ordering value outside what the database can hold is sent
|
||||
THEN:
|
||||
- The response is a 400, not a server error
|
||||
"""
|
||||
response = admin_client.get(f"{path}?{query}")
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "query"),
|
||||
[
|
||||
pytest.param("/api/documents/", f"tags__id__all={HUGE}", id="tags-all"),
|
||||
pytest.param("/api/documents/", f"tags__id__in={HUGE}", id="tags-in"),
|
||||
pytest.param(
|
||||
"/api/share_link_bundles/",
|
||||
f"documents={HUGE}",
|
||||
id="bundle-documents",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_id_list_with_an_impossible_id_matches_nothing(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
path: str,
|
||||
query: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document that has a tag
|
||||
WHEN:
|
||||
- An id list filter includes an id that no row can have
|
||||
THEN:
|
||||
- The request succeeds and nothing matches
|
||||
"""
|
||||
document = DocumentFactory.create()
|
||||
document.tags.add(TagFactory.create())
|
||||
|
||||
response = admin_client.get(f"{path}?{query}")
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["count"] == 0
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "query"),
|
||||
[
|
||||
pytest.param("/api/tags/", "id__in=1,2", id="id-in"),
|
||||
pytest.param("/api/documents/", "created__year=2024", id="year"),
|
||||
pytest.param("/api/documents/", "created__year=9999", id="year-max"),
|
||||
pytest.param("/api/documents/", "created__month=12", id="month"),
|
||||
pytest.param("/api/documents/", "created__day=31", id="day"),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"added__gt=2024-01-01T00:00:00%2B14:00",
|
||||
id="offset-at-the-limit",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"added__gt=2024-01-01T00:00:00-12:00",
|
||||
id="negative-offset",
|
||||
),
|
||||
pytest.param("/api/tasks/", "date_created_after=2024-01-01", id="tasks"),
|
||||
],
|
||||
)
|
||||
def test_in_range_values_still_work(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
path: str,
|
||||
query: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- Filters with ordinary values are sent
|
||||
THEN:
|
||||
- The request succeeds
|
||||
"""
|
||||
response = admin_client.get(f"{path}?{query}")
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
|
||||
class TestDatetimeYearBounds:
|
||||
@pytest.mark.parametrize("timezone_name", ["Europe/Berlin", "America/New_York"])
|
||||
@pytest.mark.parametrize("year", [1, 9999])
|
||||
def test_first_and_last_year_of_a_datetime_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
settings,
|
||||
timezone_name: str,
|
||||
year: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A deployment in a timezone other than UTC
|
||||
WHEN:
|
||||
- A datetime field is filtered by the first or last year
|
||||
THEN:
|
||||
- The response is a 400, as the year boundary overflows when converted
|
||||
to UTC
|
||||
"""
|
||||
settings.TIME_ZONE = timezone_name
|
||||
|
||||
response = admin_client.get(f"/api/documents/?added__year={year}")
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize("timezone_name", ["Europe/Berlin", "America/New_York"])
|
||||
@pytest.mark.parametrize(
|
||||
("field", "year"),
|
||||
[("added", 2), ("added", 9998), ("created", 1), ("created", 9999)],
|
||||
)
|
||||
def test_supported_years_succeed(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
settings,
|
||||
timezone_name: str,
|
||||
field: str,
|
||||
year: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A deployment in a timezone other than UTC
|
||||
WHEN:
|
||||
- A datetime field is filtered by a year inside the supported range, or
|
||||
a date only field by any year
|
||||
THEN:
|
||||
- The request succeeds
|
||||
"""
|
||||
settings.TIME_ZONE = timezone_name
|
||||
|
||||
response = admin_client.get(f"/api/documents/?{field}__year={year}")
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
|
||||
class TestFilterValueParsing:
|
||||
@pytest.mark.parametrize("value", ["1", "0"])
|
||||
def test_isnull_accepts_numeric_booleans(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
value: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document with a correspondent and one without
|
||||
WHEN:
|
||||
- A generated isnull filter is given 1 or 0, as the UI sends
|
||||
THEN:
|
||||
- Only the matching document is returned
|
||||
"""
|
||||
with_correspondent = DocumentFactory.create(
|
||||
correspondent=CorrespondentFactory.create(),
|
||||
)
|
||||
without_correspondent = DocumentFactory.create()
|
||||
|
||||
response = admin_client.get(f"/api/documents/?correspondent__isnull={value}")
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
expected = without_correspondent if value == "1" else with_correspondent
|
||||
assert [r["id"] for r in response.json()["results"]] == [expected.pk]
|
||||
|
||||
def test_datetime_filter_rejects_locale_formats(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A datetime filter is given a day first or month first date
|
||||
THEN:
|
||||
- The response is a 400, only ISO 8601 is accepted
|
||||
"""
|
||||
response = admin_client.get("/api/documents/?added__gt=01/02/2024 10:00")
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
|
||||
class TestBulkSelectionRejectsInvalidFilters:
|
||||
@pytest.mark.parametrize(
|
||||
"filters",
|
||||
[{"id__in": str(HUGE)}, {"created__year": "abc"}],
|
||||
)
|
||||
def test_documents_are_not_selected(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
filters: dict[str, str],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Documents exist
|
||||
WHEN:
|
||||
- A bulk delete of all documents is requested with a filter that is invalid
|
||||
THEN:
|
||||
- The response is a 400 and nothing is queued
|
||||
"""
|
||||
DocumentFactory.create()
|
||||
|
||||
with mock.patch("documents.views.execute_bulk_operation") as execute:
|
||||
# A real id, so a request that is wrongly accepted fails the assertions
|
||||
# below instead of failing to render a mock as JSON
|
||||
execute.apply_async.return_value.id = "task-id"
|
||||
response = admin_client.post(
|
||||
"/api/documents/delete/",
|
||||
{"all": True, "filters": filters},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
execute.apply_async.assert_not_called()
|
||||
assert Document.objects.count() == 1
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"filters",
|
||||
[{"id__in": str(HUGE)}, {"id": "abc"}],
|
||||
)
|
||||
def test_objects_are_not_selected(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
filters: dict[str, str],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Tags exist
|
||||
WHEN:
|
||||
- A bulk delete of all tags is requested with a filter that is invalid
|
||||
THEN:
|
||||
- The response is a 400 and no tag is deleted
|
||||
"""
|
||||
TagFactory.create()
|
||||
|
||||
response = admin_client.post(
|
||||
"/api/bulk_edit_objects/",
|
||||
{
|
||||
"object_type": "tags",
|
||||
"operation": "delete",
|
||||
"all": True,
|
||||
"filters": filters,
|
||||
},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert Tag.objects.count() == 1
|
||||
|
||||
|
||||
class TestSetPermissionsIdBounds:
|
||||
@pytest.mark.parametrize("grantee", ["users", "groups"])
|
||||
@pytest.mark.parametrize("bad_id", [HUGE, -HUGE, "abc", None])
|
||||
def test_impossible_grantee_id_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
grantee: str,
|
||||
bad_id: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A tag
|
||||
WHEN:
|
||||
- Permissions are set with a user or group id that cannot exist
|
||||
THEN:
|
||||
- The response is a 400, not a server error
|
||||
"""
|
||||
tag = TagFactory.create()
|
||||
|
||||
response = admin_client.put(
|
||||
f"/api/tags/{tag.pk}/",
|
||||
{"name": tag.name, "set_permissions": {"view": {grantee: [bad_id]}}},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
+126
-18
@@ -942,7 +942,7 @@ class EmailDocumentDetailSchema(EmailSerializer):
|
||||
parameters=[
|
||||
OpenApiParameter(
|
||||
name="id",
|
||||
type=OpenApiTypes.STR,
|
||||
type=OpenApiTypes.INT,
|
||||
location=OpenApiParameter.PATH,
|
||||
),
|
||||
],
|
||||
@@ -1036,6 +1036,14 @@ class DocumentViewSet(
|
||||
# Bound the IN clauses used for search results and through-table lookups.
|
||||
selection_data_batch_size = 10_000
|
||||
|
||||
def initial(self, request, *args, **kwargs):
|
||||
super().initial(request, *args, **kwargs)
|
||||
# Only ASCII digits can be a document id, reject anything else here, before
|
||||
# any action calls int() on it
|
||||
pk = kwargs.get("pk")
|
||||
if pk is not None and not (pk.isascii() and pk.isdigit()):
|
||||
raise Http404
|
||||
|
||||
def _get_selection_data_for_queryset(
|
||||
self,
|
||||
queryset: QuerySet[Document],
|
||||
@@ -2205,7 +2213,7 @@ class DocumentViewSet(
|
||||
raise Http404
|
||||
|
||||
try:
|
||||
doc_name, doc_data = serializer.validated_data.get("document")
|
||||
doc_name, doc_file = serializer.validated_data.get("document")
|
||||
version_label = serializer.validated_data.get("version_label")
|
||||
|
||||
t = int(mktime(datetime.now().timetuple()))
|
||||
@@ -2216,7 +2224,9 @@ class DocumentViewSet(
|
||||
pathvalidate.sanitize_filename(doc_name),
|
||||
)
|
||||
|
||||
temp_file_path.write_bytes(doc_data)
|
||||
with temp_file_path.open("wb") as scratch_file:
|
||||
for chunk in doc_file.chunks():
|
||||
scratch_file.write(chunk)
|
||||
|
||||
os.utime(temp_file_path, times=(t, t))
|
||||
|
||||
@@ -2884,6 +2894,13 @@ class UnifiedSearchViewSet(DocumentViewSet):
|
||||
return Response(max_asn + 1)
|
||||
|
||||
|
||||
LOG_FILES = {
|
||||
"paperless": "paperless.log",
|
||||
"mail": "mail.log",
|
||||
"celery": "celery.log",
|
||||
}
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
list=extend_schema(
|
||||
description="Logs view",
|
||||
@@ -2901,6 +2918,7 @@ class UnifiedSearchViewSet(DocumentViewSet):
|
||||
name="id",
|
||||
type=OpenApiTypes.STR,
|
||||
location=OpenApiParameter.PATH,
|
||||
enum=list(LOG_FILES),
|
||||
),
|
||||
OpenApiParameter(
|
||||
name="limit",
|
||||
@@ -2921,11 +2939,7 @@ class UnifiedSearchViewSet(DocumentViewSet):
|
||||
class LogViewSet(ViewSet):
|
||||
permission_classes = (IsAuthenticated, PaperlessAdminPermissions)
|
||||
|
||||
ALLOWED_LOG_FILES = {
|
||||
"paperless": "paperless.log",
|
||||
"mail": "mail.log",
|
||||
"celery": "celery.log",
|
||||
}
|
||||
ALLOWED_LOG_FILES = LOG_FILES
|
||||
|
||||
def get_log_file(self, log_key: str) -> Path:
|
||||
return Path(settings.LOGGING_DIR) / self.ALLOWED_LOG_FILES[log_key]
|
||||
@@ -3059,11 +3073,15 @@ class DocumentSelectionMixin:
|
||||
root_document__isnull=True,
|
||||
)
|
||||
# orm-filtered docs
|
||||
filtered_documents = DocumentFilterSet(
|
||||
# An invalid filter is dropped by .qs, which would select every document
|
||||
filterset = DocumentFilterSet(
|
||||
data=orm_filters,
|
||||
queryset=permitted_documents,
|
||||
user=user,
|
||||
).qs.distinct()
|
||||
)
|
||||
if not filterset.is_valid():
|
||||
raise ValidationError({"filters": filterset.errors})
|
||||
filtered_documents = filterset.qs.distinct()
|
||||
# tantivy-filtered docs (if search params provided)
|
||||
search_filtered_ids = self._get_search_document_ids(
|
||||
user=user,
|
||||
@@ -3498,7 +3516,7 @@ class PostDocumentView(GenericAPIView[Any]):
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
doc_name, doc_data = serializer.validated_data.get("document")
|
||||
doc_name, doc_file = serializer.validated_data.get("document")
|
||||
doc_name = normalize("NFC", doc_name)
|
||||
correspondent_id = serializer.validated_data.get("correspondent")
|
||||
document_type_id = serializer.validated_data.get("document_type")
|
||||
@@ -3518,7 +3536,9 @@ class PostDocumentView(GenericAPIView[Any]):
|
||||
pathvalidate.sanitize_filename(doc_name),
|
||||
)
|
||||
|
||||
temp_file_path.write_bytes(doc_data)
|
||||
with temp_file_path.open("wb") as scratch_file:
|
||||
for chunk in doc_file.chunks():
|
||||
scratch_file.write(chunk)
|
||||
|
||||
os.utime(temp_file_path, times=(t, t))
|
||||
|
||||
@@ -3733,7 +3753,10 @@ class SearchAutoCompleteView(GenericAPIView[Any]):
|
||||
return HttpResponseBadRequest("Term required")
|
||||
|
||||
if "limit" in request.query_params:
|
||||
limit = int(request.query_params["limit"])
|
||||
try:
|
||||
limit = int(request.query_params["limit"])
|
||||
except ValueError:
|
||||
return HttpResponseBadRequest("Invalid limit")
|
||||
if limit <= 0:
|
||||
return HttpResponseBadRequest("Invalid limit")
|
||||
else:
|
||||
@@ -4009,7 +4032,36 @@ class GlobalSearchView(PassUserMixin):
|
||||
get=extend_schema(
|
||||
description="Get statistics for the current user",
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="Statistics",
|
||||
fields={
|
||||
"documents_total": serializers.IntegerField(),
|
||||
"documents_inbox": serializers.IntegerField(allow_null=True),
|
||||
"inbox_tag": serializers.IntegerField(
|
||||
allow_null=True,
|
||||
help_text="The first inbox tag, kept for backwards compatibility",
|
||||
),
|
||||
"inbox_tags": serializers.ListField(
|
||||
child=serializers.IntegerField(),
|
||||
allow_null=True,
|
||||
),
|
||||
"document_file_type_counts": serializers.ListField(
|
||||
child=inline_serializer(
|
||||
name="MimeTypeCount",
|
||||
fields={
|
||||
"mime_type": serializers.CharField(),
|
||||
"mime_type_count": serializers.IntegerField(),
|
||||
},
|
||||
),
|
||||
),
|
||||
"character_count": serializers.IntegerField(),
|
||||
"tag_count": serializers.IntegerField(),
|
||||
"correspondent_count": serializers.IntegerField(),
|
||||
"document_type_count": serializers.IntegerField(),
|
||||
"storage_path_count": serializers.IntegerField(),
|
||||
"current_asn": serializers.IntegerField(),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -4494,7 +4546,13 @@ def get_github_stars() -> int | None:
|
||||
get=extend_schema(
|
||||
description="Get the current version of the Paperless-NGX server",
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="RemoteVersion",
|
||||
fields={
|
||||
"version": serializers.CharField(),
|
||||
"update_available": serializers.BooleanField(),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -4559,7 +4617,17 @@ class RemoteVersionView(GenericAPIView[Any]):
|
||||
),
|
||||
],
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="ReleaseNotes",
|
||||
fields={
|
||||
"version": serializers.CharField(),
|
||||
"releases": serializers.ListField(
|
||||
child=serializers.DictField(),
|
||||
help_text="GitHub release objects",
|
||||
),
|
||||
"stars": serializers.IntegerField(allow_null=True),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -5274,10 +5342,14 @@ class BulkEditObjectsView(PassUserMixin):
|
||||
user_permitted_objects = object_class.objects.filter(
|
||||
id__in=permitted_object_ids(user, object_class, perm_codename),
|
||||
)
|
||||
objs = filterset_class(
|
||||
# An invalid filter is dropped by .qs, which would select every object
|
||||
filterset = filterset_class(
|
||||
data=filters,
|
||||
queryset=user_permitted_objects,
|
||||
).qs
|
||||
)
|
||||
if not filterset.is_valid():
|
||||
raise ValidationError({"filters": filterset.errors})
|
||||
objs = filterset.qs
|
||||
if object_type == "tags":
|
||||
editable_ids = set(user_permitted_objects.values_list("pk", flat=True))
|
||||
all_ids = set(objs.values_list("pk", flat=True))
|
||||
@@ -5823,6 +5895,26 @@ class SystemStatusView(PassUserMixin):
|
||||
)
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
description="List the documents in the trash",
|
||||
responses={(200, "application/json"): DocumentSerializer(many=True)},
|
||||
),
|
||||
post=extend_schema(
|
||||
description="Restore documents from the trash, or delete them permanently",
|
||||
responses={
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="TrashActionResult",
|
||||
fields={
|
||||
"result": serializers.CharField(),
|
||||
"doc_ids": serializers.ListField(
|
||||
child=serializers.IntegerField(),
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
class TrashView(ListModelMixin, PassUserMixin):
|
||||
permission_classes = (IsAuthenticated, TrashPermissions)
|
||||
serializer_class = TrashSerializer
|
||||
@@ -5971,6 +6063,22 @@ class OcrTemplateViewSet(BulkPermissionMixin, PassUserMixin, ModelViewSet[OcrTem
|
||||
]
|
||||
return super().get_permissions()
|
||||
|
||||
@extend_schema(
|
||||
parameters=[
|
||||
OpenApiParameter(
|
||||
name="doc_id",
|
||||
type=OpenApiTypes.INT,
|
||||
location=OpenApiParameter.PATH,
|
||||
),
|
||||
OpenApiParameter(
|
||||
name="page",
|
||||
type={"type": "integer", "minimum": 1},
|
||||
location=OpenApiParameter.PATH,
|
||||
description="1-based page number",
|
||||
),
|
||||
],
|
||||
responses={(200, "image/png"): OpenApiTypes.BINARY},
|
||||
)
|
||||
@action(
|
||||
detail=False,
|
||||
methods=["get"],
|
||||
|
||||
@@ -2,7 +2,7 @@ msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: paperless-ngx\n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-11-27 02:54+0000\n"
|
||||
"POT-Creation-Date: 2026-11-28 23:01+0000\n"
|
||||
"PO-Revision-Date: 2022-02-17 04:17\n"
|
||||
"Last-Translator: \n"
|
||||
"Language-Team: English\n"
|
||||
@@ -1879,49 +1879,49 @@ msgstr ""
|
||||
msgid "OCR template zones"
|
||||
msgstr ""
|
||||
|
||||
#: documents/serialisers.py:491 documents/serialisers.py:815
|
||||
#: documents/serialisers.py:2913 documents/views.py:372 documents/views.py:638
|
||||
#: documents/views.py:2868 paperless_mail/serialisers.py:145
|
||||
#: documents/serialisers.py:495 documents/serialisers.py:819
|
||||
#: documents/serialisers.py:2918 documents/views.py:372 documents/views.py:638
|
||||
#: documents/views.py:2870 paperless_mail/serialisers.py:145
|
||||
msgid "Insufficient permissions."
|
||||
msgstr ""
|
||||
|
||||
#: documents/serialisers.py:647
|
||||
#: documents/serialisers.py:651
|
||||
msgid "Invalid color."
|
||||
msgstr ""
|
||||
|
||||
#: documents/serialisers.py:2380
|
||||
#: documents/serialisers.py:2385
|
||||
#, python-format
|
||||
msgid "File type %(type)s not supported"
|
||||
msgstr ""
|
||||
|
||||
#: documents/serialisers.py:2424
|
||||
#: documents/serialisers.py:2429
|
||||
#, python-format
|
||||
msgid "Custom field id must be an integer: %(id)s"
|
||||
msgstr ""
|
||||
|
||||
#: documents/serialisers.py:2431
|
||||
#: documents/serialisers.py:2436
|
||||
#, python-format
|
||||
msgid "Custom field with id %(id)s does not exist"
|
||||
msgstr ""
|
||||
|
||||
#: documents/serialisers.py:2448 documents/serialisers.py:2458
|
||||
#: documents/serialisers.py:2453 documents/serialisers.py:2463
|
||||
msgid ""
|
||||
"Custom fields must be a list of integers or an object mapping ids to values."
|
||||
msgstr ""
|
||||
|
||||
#: documents/serialisers.py:2453
|
||||
#: documents/serialisers.py:2458
|
||||
msgid "Some custom fields don't exist or were specified twice."
|
||||
msgstr ""
|
||||
|
||||
#: documents/serialisers.py:2600
|
||||
#: documents/serialisers.py:2605
|
||||
msgid "Invalid variable detected."
|
||||
msgstr ""
|
||||
|
||||
#: documents/serialisers.py:2969
|
||||
#: documents/serialisers.py:2974
|
||||
msgid "Duplicate document identifiers are not allowed."
|
||||
msgstr ""
|
||||
|
||||
#: documents/serialisers.py:2999 documents/views.py:5001
|
||||
#: documents/serialisers.py:3004 documents/views.py:5008
|
||||
#, python-format
|
||||
msgid "Documents not found: %(ids)s"
|
||||
msgstr ""
|
||||
@@ -2192,7 +2192,7 @@ msgstr ""
|
||||
msgid "Specify only one of text, title_search, query, or more_like_id."
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:365 documents/views.py:2865
|
||||
#: documents/views.py:365 documents/views.py:2867
|
||||
msgid "Invalid more_like_id"
|
||||
msgstr ""
|
||||
|
||||
@@ -2208,20 +2208,20 @@ msgstr ""
|
||||
msgid "AI backend rejected the request. Check logs for details."
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:5017
|
||||
#: documents/views.py:5024
|
||||
#, python-format
|
||||
msgid "Insufficient permissions to share document %(id)s."
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:5064
|
||||
#: documents/views.py:5071
|
||||
msgid "Bundle is already being processed."
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:5130
|
||||
#: documents/views.py:5137
|
||||
msgid "The share link bundle is still being prepared. Please try again later."
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:5144
|
||||
#: documents/views.py:5151
|
||||
msgid "The share link bundle is unavailable."
|
||||
msgstr ""
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import pytest
|
||||
from django.test import Client
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
|
||||
class TestUnmatchedApiPaths:
|
||||
@pytest.mark.parametrize("method", ["get", "post", "put", "patch", "delete"])
|
||||
def test_unmatched_api_path_is_a_json_404(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
method: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An unauthenticated client
|
||||
WHEN:
|
||||
- Any method is sent to an /api/ URL that no route matches
|
||||
THEN:
|
||||
- The response is a JSON 404, not a redirect to the login page
|
||||
"""
|
||||
response = getattr(rest_api_client, method)("/api/this_does_not_exist/")
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
assert response["Content-Type"].startswith("application/json")
|
||||
|
||||
def test_unmatched_api_path_is_a_json_404_when_authenticated(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- An /api/ URL that no route matches is requested
|
||||
THEN:
|
||||
- The response is a JSON 404, not the frontend page
|
||||
"""
|
||||
response = admin_client.get("/api/this/is/nested/and/missing/")
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
assert response["Content-Type"].startswith("application/json")
|
||||
|
||||
def test_other_paths_still_reach_the_frontend_catch_all(
|
||||
self,
|
||||
client: Client,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An anonymous browser request
|
||||
WHEN:
|
||||
- A non-API path is requested
|
||||
THEN:
|
||||
- The frontend catch-all still applies, which sends the user to log in
|
||||
"""
|
||||
response = client.get("/documents/")
|
||||
|
||||
assert response.status_code == status.HTTP_302_FOUND
|
||||
assert "login" in response["Location"]
|
||||
|
||||
|
||||
class TestDocumentRouteIds:
|
||||
@pytest.mark.parametrize(
|
||||
"action",
|
||||
[
|
||||
"download",
|
||||
"history",
|
||||
"metadata",
|
||||
"notes",
|
||||
"preview",
|
||||
"root",
|
||||
"share_links",
|
||||
"suggestions",
|
||||
"thumb",
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("pk", ["null", "true", "abc", "0.5", "%20"])
|
||||
def test_non_numeric_document_id_is_a_json_404(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
action: str,
|
||||
pk: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A document sub-route is requested with an id that is not a number
|
||||
THEN:
|
||||
- The response is a JSON 404, not a server error
|
||||
"""
|
||||
response = admin_client.get(f"/api/documents/{pk}/{action}/")
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
assert response["Content-Type"].startswith("application/json")
|
||||
@@ -57,6 +57,7 @@ from documents.views import WorkflowTriggerViewSet
|
||||
from documents.views import WorkflowViewSet
|
||||
from documents.views import serve_logo
|
||||
from paperless.consumers import StatusConsumer
|
||||
from paperless.views import ApiNotFoundView
|
||||
from paperless.views import ApplicationConfigurationViewSet
|
||||
from paperless.views import DisconnectSocialAccountView
|
||||
from paperless.views import FaviconView
|
||||
@@ -309,6 +310,8 @@ urlpatterns = [
|
||||
RedirectView.as_view(url="schema/view/"),
|
||||
),
|
||||
*api_router.urls,
|
||||
# Must stay last, anything unmatched under /api/ is a JSON 404
|
||||
re_path(r"^.*$", ApiNotFoundView.as_view(), name="api_not_found"),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
+47
-3
@@ -24,9 +24,12 @@ from django_filters.rest_framework import DjangoFilterBackend
|
||||
from drf_spectacular.types import OpenApiTypes
|
||||
from drf_spectacular.utils import extend_schema
|
||||
from drf_spectacular.utils import extend_schema_view
|
||||
from drf_spectacular.utils import inline_serializer
|
||||
from rest_framework import serializers
|
||||
from rest_framework.authtoken.models import Token
|
||||
from rest_framework.authtoken.views import ObtainAuthToken
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.exceptions import NotFound
|
||||
from rest_framework.exceptions import ValidationError
|
||||
from rest_framework.fields import BooleanField
|
||||
from rest_framework.filters import OrderingFilter
|
||||
@@ -35,6 +38,7 @@ from rest_framework.pagination import PageNumberPagination
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.throttling import ScopedRateThrottle
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.viewsets import ModelViewSet
|
||||
|
||||
from documents.models import PaperlessTask
|
||||
@@ -274,8 +278,16 @@ class ProfileView(GenericAPIView[Any]):
|
||||
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
description="Generate a new TOTP secret, its otpauth URL and a QR code",
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="TotpSetup",
|
||||
fields={
|
||||
"url": serializers.CharField(),
|
||||
"qr_svg": serializers.CharField(help_text="QR code as an SVG"),
|
||||
"secret": serializers.CharField(),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
post=extend_schema(
|
||||
@@ -290,7 +302,17 @@ class ProfileView(GenericAPIView[Any]):
|
||||
},
|
||||
},
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="TotpActivation",
|
||||
fields={
|
||||
"success": serializers.BooleanField(),
|
||||
"recovery_codes": serializers.ListField(
|
||||
child=serializers.CharField(),
|
||||
allow_null=True,
|
||||
help_text="Only returned when the code was valid",
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
delete=extend_schema(
|
||||
@@ -523,7 +545,14 @@ class DisconnectSocialAccountView(GenericAPIView[Any]):
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="SocialAccountProvider",
|
||||
fields={
|
||||
"name": serializers.CharField(),
|
||||
"login_url": serializers.CharField(),
|
||||
},
|
||||
many=True,
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -557,3 +586,18 @@ class SocialAccountProvidersView(GenericAPIView[Any]):
|
||||
]
|
||||
|
||||
return Response(sorted(resp, key=lambda p: p["name"]))
|
||||
|
||||
|
||||
@extend_schema(exclude=True)
|
||||
class ApiNotFoundView(APIView):
|
||||
"""
|
||||
A JSON 404 for any /api/ URL that no other route matches. Without this, those
|
||||
URLs fall through to the frontend catch-all, which answers a redirect to the
|
||||
login page or the single page app, never an error an API client can read.
|
||||
"""
|
||||
|
||||
authentication_classes = ()
|
||||
permission_classes = ()
|
||||
|
||||
def initial(self, request, *args, **kwargs):
|
||||
raise NotFound
|
||||
@@ -2,6 +2,7 @@ import datetime
|
||||
import imaplib
|
||||
import itertools
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import ssl
|
||||
import tempfile
|
||||
@@ -1135,12 +1136,12 @@ class MailAccountHandler(LoggingMixin):
|
||||
doc_type,
|
||||
):
|
||||
settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_, temp_filename = tempfile.mkstemp(
|
||||
fd, temp_filename = tempfile.mkstemp(
|
||||
prefix="paperless-mail-",
|
||||
dir=settings.SCRATCH_DIR,
|
||||
suffix=".eml",
|
||||
)
|
||||
with Path(temp_filename).open("wb") as f:
|
||||
with os.fdopen(fd, "wb") as f:
|
||||
# Move "From"-header to beginning of file
|
||||
# TODO: This ugly workaround is needed because the parser is
|
||||
# chosen only by the mime_type detected via magic
|
||||
|
||||
@@ -10,6 +10,7 @@ from django.http import HttpResponseRedirect
|
||||
from django.utils import timezone
|
||||
from django_filters.rest_framework import DjangoFilterBackend
|
||||
from drf_spectacular.types import OpenApiTypes
|
||||
from drf_spectacular.utils import OpenApiParameter
|
||||
from drf_spectacular.utils import extend_schema
|
||||
from drf_spectacular.utils import extend_schema_view
|
||||
from drf_spectacular.utils import inline_serializer
|
||||
@@ -254,8 +255,39 @@ class MailRuleViewSet(PassUserMixin, ModelViewSet[MailRule]):
|
||||
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
description="Callback view for OAuth2 authentication",
|
||||
responses={200: None},
|
||||
description=(
|
||||
"Callback view for OAuth2 authentication. Redirects back to the "
|
||||
"frontend, with the outcome in the query string"
|
||||
),
|
||||
parameters=[
|
||||
OpenApiParameter(
|
||||
name="code",
|
||||
# An empty value is rejected
|
||||
type={"type": "string", "minLength": 1},
|
||||
location=OpenApiParameter.QUERY,
|
||||
required=True,
|
||||
description="Authorization code returned by the OAuth provider",
|
||||
),
|
||||
OpenApiParameter(
|
||||
name="state",
|
||||
# An empty value is rejected
|
||||
type={"type": "string", "minLength": 1},
|
||||
location=OpenApiParameter.QUERY,
|
||||
required=True,
|
||||
description="State value, must match the one stored in the session",
|
||||
),
|
||||
OpenApiParameter(
|
||||
name="scope",
|
||||
type=OpenApiTypes.STR,
|
||||
location=OpenApiParameter.QUERY,
|
||||
required=False,
|
||||
description="Granted scopes, sent by Gmail but not by Outlook",
|
||||
),
|
||||
],
|
||||
responses={
|
||||
302: None,
|
||||
(400, "text/html"): OpenApiTypes.STR,
|
||||
},
|
||||
),
|
||||
)
|
||||
class OauthCallbackView(GenericAPIView[Any]):
|
||||
|
||||
Reference in new issue
Block a user