mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-30 08:35:24 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b150c1292 | ||
|
|
f895fd369e | ||
|
|
416161dd1e | ||
|
|
afa722ba95 |
No files matched your search
@@ -11,6 +11,7 @@ from typing import Final
|
||||
import magic
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.exceptions import ValidationError as DjangoValidationError
|
||||
from django.db import transaction
|
||||
from django.db.models import Max
|
||||
from django.db.models import Q
|
||||
@@ -1273,10 +1274,9 @@ class AsnCheckPlugin(
|
||||
return
|
||||
# Validate the range is above zero and less than uint32_t max
|
||||
# otherwise, Whoosh can't handle it in the index
|
||||
if (
|
||||
self.metadata.asn < Document.ARCHIVE_SERIAL_NUMBER_MIN
|
||||
or self.metadata.asn > Document.ARCHIVE_SERIAL_NUMBER_MAX
|
||||
):
|
||||
try:
|
||||
Document.validate_archive_serial_number(self.metadata.asn)
|
||||
except DjangoValidationError:
|
||||
self._fail(
|
||||
ConsumerStatusShortMessage.ASN_RANGE,
|
||||
f"Not consuming {self.filename}: "
|
||||
|
||||
@@ -105,6 +105,11 @@ logger = logging.getLogger("paperless.api")
|
||||
# match a row, and handing it to the database raises an error on some backends.
|
||||
INT64_MIN = -(2**63)
|
||||
INT64_MAX = 2**63 - 1
|
||||
# SmallIntegerField and IntegerField columns, the same size on every supported database
|
||||
INT16_MIN = -(2**15)
|
||||
INT16_MAX = 2**15 - 1
|
||||
INT32_MIN = -(2**31)
|
||||
INT32_MAX = 2**31 - 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)}
|
||||
|
||||
@@ -422,6 +422,15 @@ class Document(SoftDeleteModel, ModelWithOwner): # type: ignore[django-manager-
|
||||
res += f" {self.title}"
|
||||
return res
|
||||
|
||||
@classmethod
|
||||
def validate_archive_serial_number(cls, value: int) -> None:
|
||||
"""
|
||||
Run every validator of the ASN field. Besides the fixed range above, Django
|
||||
adds the range of the column for the database in use (a signed 32 bit
|
||||
integer on PostgreSQL), which a serializer built from the field does not apply
|
||||
"""
|
||||
cls._meta.get_field("archive_serial_number").run_validators(value)
|
||||
|
||||
def get_effective_barcodes(self) -> list["DocumentBarcode"]:
|
||||
"""
|
||||
Returns the stored barcodes for the document, like
|
||||
|
||||
@@ -2,6 +2,8 @@ from drf_spectacular.extensions import OpenApiAuthenticationExtension
|
||||
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_field
|
||||
from rest_framework import serializers
|
||||
|
||||
|
||||
class AngularApiAuthenticationOverrideScheme(OpenApiAuthenticationExtension):
|
||||
@@ -42,3 +44,89 @@ def generate_object_with_permissions_schema(serializer_class):
|
||||
)
|
||||
for operation in ["list", "retrieve"]
|
||||
}
|
||||
|
||||
|
||||
HTTP_METHODS = {"get", "put", "post", "patch", "delete"}
|
||||
|
||||
|
||||
def add_common_error_responses(result, generator, request, public):
|
||||
"""
|
||||
Document the errors nearly every operation can answer, so they do not have to be
|
||||
declared on each view: a 400 when validation of the input fails, and a 404 when
|
||||
the object named in the path, or the requested page of a list, does not exist.
|
||||
Responses a view declares itself are kept as they are.
|
||||
"""
|
||||
for item in result.get("paths", {}).values():
|
||||
for method, operation in item.items():
|
||||
if method not in HTTP_METHODS:
|
||||
continue
|
||||
parameters = [*item.get("parameters", []), *operation.get("parameters", [])]
|
||||
has_path_parameter = any(p.get("in") == "path" for p in parameters)
|
||||
has_input = (
|
||||
"requestBody" in operation
|
||||
or has_path_parameter
|
||||
or any(p.get("in") == "query" for p in parameters)
|
||||
)
|
||||
paginated = any(
|
||||
p.get("in") == "query" and p.get("name") == "page" for p in parameters
|
||||
)
|
||||
responses = operation.setdefault("responses", {})
|
||||
if has_input:
|
||||
responses.setdefault("400", {"description": "Invalid input"})
|
||||
if has_path_parameter or paginated:
|
||||
responses.setdefault(
|
||||
"404",
|
||||
{"description": "The object or page does not exist"},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
# Fields of the objects with an owner that a response only carries sometimes: the
|
||||
# permissions or the flags that replace them (see OwnedObjectSerializer), and counts a
|
||||
# queryset annotates, which a response to a create or an update does not have.
|
||||
CONDITIONAL_RESPONSE_FIELDS = (
|
||||
"permissions",
|
||||
"user_can_change",
|
||||
"is_shared_by_requester",
|
||||
"document_count",
|
||||
"last_correspondence",
|
||||
)
|
||||
|
||||
|
||||
# Components without an owner that still carry an annotated count
|
||||
COMPONENTS_WITH_ANNOTATED_COUNTS = {"CustomField"}
|
||||
|
||||
|
||||
def make_conditional_fields_optional(result, generator, request, public):
|
||||
"""
|
||||
drf-spectacular lists every read only field as required in a response. For the
|
||||
objects built on OwnedObjectSerializer that is wrong for the fields above, so they
|
||||
are taken out of the required list of those components.
|
||||
"""
|
||||
for name, component in result.get("components", {}).get("schemas", {}).items():
|
||||
properties = component.get("properties", {})
|
||||
required = component.get("required")
|
||||
owned = {"permissions", "user_can_change"} & set(properties)
|
||||
if not required or not (owned or name in COMPONENTS_WITH_ANNOTATED_COUNTS):
|
||||
continue
|
||||
remaining = [
|
||||
name for name in required if name not in CONDITIONAL_RESPONSE_FIELDS
|
||||
]
|
||||
if remaining:
|
||||
component["required"] = remaining
|
||||
else:
|
||||
del component["required"]
|
||||
return result
|
||||
|
||||
|
||||
@extend_schema_field({"type": "integer", "format": "int64"})
|
||||
class Int64Field(serializers.IntegerField):
|
||||
"""An integer that does not fit 32 bits, for example a size in bytes."""
|
||||
|
||||
|
||||
@extend_schema_field({"type": "string", "format": "date", "nullable": True})
|
||||
class NullableDateField(serializers.DateField):
|
||||
"""
|
||||
A date the schema documents as nullable. allow_null would also make a response
|
||||
carry an explicit null where the field is left out today.
|
||||
"""
|
||||
+111
-90
@@ -20,6 +20,7 @@ from django.core.validators import EmailValidator
|
||||
from django.core.validators import MaxLengthValidator
|
||||
from django.core.validators import MaxValueValidator
|
||||
from django.core.validators import MinValueValidator
|
||||
from django.core.validators import RegexValidator
|
||||
from django.core.validators import integer_validator
|
||||
from django.db import transaction
|
||||
from django.db.models import Count
|
||||
@@ -52,6 +53,8 @@ if settings.AUDIT_LOG_ENABLED:
|
||||
|
||||
from documents import bulk_edit
|
||||
from documents.data_models import DocumentSource
|
||||
from documents.filters import INT32_MAX
|
||||
from documents.filters import INT32_MIN
|
||||
from documents.filters import CustomFieldQueryParser
|
||||
from documents.filters import in_range_ids
|
||||
from documents.models import Correspondent
|
||||
@@ -91,6 +94,7 @@ from documents.permissions import permitted_object_ids
|
||||
from documents.permissions import restrict_queryset_to_visible
|
||||
from documents.permissions import set_permissions_for_objects
|
||||
from documents.regex import validate_regex_pattern
|
||||
from documents.schema import NullableDateField
|
||||
from documents.templating.filepath import validate_filepath_template_and_render
|
||||
from documents.templating.utils import convert_format_str_to_template_format
|
||||
from documents.templating.workflows import validate_workflow_template
|
||||
@@ -449,6 +453,10 @@ class OwnedObjectSerializer(
|
||||
|
||||
def validate_unique_together(self, validated_data, instance=None) -> None:
|
||||
# workaround for https://github.com/encode/django-rest-framework/issues/9358
|
||||
# An update that does not mention the owner keeps the current one, which
|
||||
# still has to be unique with the new name
|
||||
if instance is not None and "owner" not in validated_data:
|
||||
validated_data = {**validated_data, "owner": instance.owner}
|
||||
if "owner" in validated_data and "name" in self.Meta.fields:
|
||||
name = validated_data.get("name", instance.name if instance else None)
|
||||
objects = (
|
||||
@@ -511,7 +519,7 @@ class OwnedObjectListSerializer(serializers.ListSerializer[Any]):
|
||||
|
||||
|
||||
class CorrespondentSerializer(MatchingModelSerializer, OwnedObjectSerializer):
|
||||
last_correspondence = serializers.DateField(read_only=True, required=False)
|
||||
last_correspondence = NullableDateField(read_only=True, required=False)
|
||||
|
||||
class Meta:
|
||||
model = Correspondent
|
||||
@@ -574,11 +582,8 @@ class TagSerializer(MatchingModelSerializer, OwnedObjectSerializer):
|
||||
)
|
||||
|
||||
@extend_schema_field(
|
||||
field=serializers.ListSerializer(
|
||||
child=serializers.PrimaryKeyRelatedField(
|
||||
queryset=Tag.objects.all(),
|
||||
),
|
||||
),
|
||||
# The children are nested tags, not ids
|
||||
field={"type": "array", "items": {"$ref": "#/components/schemas/Tag"}},
|
||||
)
|
||||
def get_children(self, obj):
|
||||
children_map = self.context.get("children_map")
|
||||
@@ -645,12 +650,14 @@ class TagSerializer(MatchingModelSerializer, OwnedObjectSerializer):
|
||||
"parent",
|
||||
"children",
|
||||
)
|
||||
|
||||
def validate_color(self, color):
|
||||
regex = r"#[0-9a-fA-F]{6}"
|
||||
if not re.match(regex, color):
|
||||
raise serializers.ValidationError(_("Invalid color."))
|
||||
return color
|
||||
# A validator, so the schema publishes it as a pattern
|
||||
extra_kwargs = {
|
||||
"color": {
|
||||
"validators": [
|
||||
RegexValidator(r"^#[0-9a-fA-F]{6}$", message=_("Invalid color.")),
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
def validate(self, attrs):
|
||||
# Validate when changing parent
|
||||
@@ -1023,7 +1030,7 @@ class DocumentSerializer(
|
||||
|
||||
notes = NotesSerializer(many=True, required=False, read_only=True)
|
||||
root_document: RelatedField[Document, Document, Any] | ManyRelatedField = (
|
||||
serializers.PrimaryKeyRelatedField(read_only=True)
|
||||
serializers.PrimaryKeyRelatedField(read_only=True, allow_null=True)
|
||||
)
|
||||
versions = SerializerMethodField()
|
||||
|
||||
@@ -1146,6 +1153,11 @@ class DocumentSerializer(
|
||||
data["created"] = parsed.astimezone().date()
|
||||
return super().to_internal_value(data)
|
||||
|
||||
def validate_archive_serial_number(self, value):
|
||||
if value is not None:
|
||||
Document.validate_archive_serial_number(value)
|
||||
return value
|
||||
|
||||
def validate(self, attrs):
|
||||
if (
|
||||
"archive_serial_number" in attrs
|
||||
@@ -1484,6 +1496,13 @@ class SavedViewSerializer(OwnedObjectSerializer):
|
||||
|
||||
def validate(self, attrs):
|
||||
attrs = super().validate(attrs)
|
||||
# On a PATCH the nested rules are validated as partial, but a stored rule
|
||||
# always needs its type
|
||||
for rule in attrs.get("filter_rules") or []:
|
||||
if "rule_type" not in rule:
|
||||
raise serializers.ValidationError(
|
||||
{"filter_rules": "Every rule needs a rule_type"},
|
||||
)
|
||||
if "display_fields" in attrs and attrs["display_fields"] is not None:
|
||||
if not isinstance(attrs["display_fields"], list):
|
||||
raise serializers.ValidationError(
|
||||
@@ -1504,10 +1523,7 @@ class SavedViewSerializer(OwnedObjectSerializer):
|
||||
raise serializers.ValidationError(
|
||||
f"Invalid field: {field}",
|
||||
)
|
||||
elif (
|
||||
field == SavedView.DisplayFields.CUSTOM_FIELD
|
||||
or field not in SavedView.DisplayFields.values
|
||||
): # the bare 'custom_field_%d' template names no custom field
|
||||
elif field not in SavedView.DisplayFields.values:
|
||||
raise serializers.ValidationError(
|
||||
f"Invalid field: {field}",
|
||||
)
|
||||
@@ -1843,14 +1859,13 @@ class RunZoneOcrResponseSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
read_only=True,
|
||||
help_text="OK when the run was queued, skipped when it was not.",
|
||||
)
|
||||
# Not read only: spectacular lists every read only field of a response as required
|
||||
task_id = serializers.CharField(
|
||||
read_only=True,
|
||||
required=False,
|
||||
help_text="The queued task. Absent when the run was skipped.",
|
||||
)
|
||||
reason = serializers.ChoiceField(
|
||||
choices=[reason.value for reason in ZoneOcrSkipReason],
|
||||
read_only=True,
|
||||
required=False,
|
||||
help_text="Present only when the run was skipped.",
|
||||
)
|
||||
@@ -1859,7 +1874,10 @@ class RunZoneOcrResponseSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
class OcrErrorSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
"""The body of an error response from the OCR template actions."""
|
||||
|
||||
error = serializers.CharField(read_only=True)
|
||||
# Not read only: spectacular lists every read only field of a response as required.
|
||||
# A 404 from a missing document has a detail instead of an error.
|
||||
error = serializers.CharField(required=False)
|
||||
detail = serializers.CharField(required=False)
|
||||
|
||||
|
||||
class RunZoneOcrDocumentsSerializer(DocumentSelectionSerializer, RunZoneOcrSerializer):
|
||||
@@ -2397,6 +2415,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
required=False,
|
||||
min_value=Document.ARCHIVE_SERIAL_NUMBER_MIN,
|
||||
max_value=Document.ARCHIVE_SERIAL_NUMBER_MAX,
|
||||
validators=[Document.validate_archive_serial_number],
|
||||
)
|
||||
|
||||
# Accept either a list of custom field ids or a dict mapping id -> value
|
||||
@@ -3293,10 +3312,14 @@ class WorkflowTriggerSerializer(serializers.ModelSerializer[WorkflowTrigger]):
|
||||
]
|
||||
|
||||
def create(self, validated_data):
|
||||
# The id is only meaningful when this is nested in a workflow. On its own
|
||||
# a client chosen id would collide with, or overwrite, another row
|
||||
validated_data.pop("id", None)
|
||||
WorkflowTriggerSerializer.normalize_workflow_trigger_sources(validated_data)
|
||||
return super().create(validated_data)
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
validated_data.pop("id", None)
|
||||
WorkflowTriggerSerializer.normalize_workflow_trigger_sources(validated_data)
|
||||
return super().update(instance, validated_data)
|
||||
|
||||
@@ -3338,6 +3361,34 @@ class WorkflowActionWebhookSerializer(
|
||||
]
|
||||
|
||||
|
||||
def save_action_email_and_webhook(action, email_data, webhook_data) -> None:
|
||||
"""
|
||||
Store the nested email and webhook of a workflow action on the action's own rows.
|
||||
An id in the payload is never used, it could name a row that belongs to another
|
||||
action. An action with no row of that kind gets a new one. The data must already
|
||||
be cleaned by the nested serializers, an unknown key would be a model error.
|
||||
"""
|
||||
created = False
|
||||
for data, model, attribute in (
|
||||
(email_data, WorkflowActionEmail, "email"),
|
||||
(webhook_data, WorkflowActionWebhook, "webhook"),
|
||||
):
|
||||
if data is None:
|
||||
continue
|
||||
values = {key: value for key, value in data.items() if key != "id"}
|
||||
existing = getattr(action, attribute)
|
||||
if existing is not None:
|
||||
# Change the loaded row, a response is built from it
|
||||
for key, value in values.items():
|
||||
setattr(existing, key, value)
|
||||
existing.save()
|
||||
else:
|
||||
setattr(action, attribute, model.objects.create(**values))
|
||||
created = True
|
||||
if created:
|
||||
action.save()
|
||||
|
||||
|
||||
class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
|
||||
id = serializers.IntegerField(required=False, allow_null=True)
|
||||
assign_correspondent = CorrespondentField(allow_null=True, required=False)
|
||||
@@ -3389,40 +3440,20 @@ class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
|
||||
"ai_overwrite_existing",
|
||||
]
|
||||
|
||||
def _save_nested(self, instance, email_data, webhook_data) -> None:
|
||||
# Never trust an id from the payload here, it could name another action's row
|
||||
created = False
|
||||
for data, model, attribute in (
|
||||
(email_data, WorkflowActionEmail, "email"),
|
||||
(webhook_data, WorkflowActionWebhook, "webhook"),
|
||||
):
|
||||
if data is None:
|
||||
continue
|
||||
values = {key: value for key, value in data.items() if key != "id"}
|
||||
existing = getattr(instance, attribute)
|
||||
if existing is not None:
|
||||
# Change the loaded row, the response is built from it
|
||||
for key, value in values.items():
|
||||
setattr(existing, key, value)
|
||||
existing.save()
|
||||
else:
|
||||
setattr(instance, attribute, model.objects.create(**values))
|
||||
created = True
|
||||
if created:
|
||||
instance.save()
|
||||
|
||||
def create(self, validated_data):
|
||||
validated_data.pop("id", None)
|
||||
email_data = validated_data.pop("email", None)
|
||||
webhook_data = validated_data.pop("webhook", None)
|
||||
instance = super().create(validated_data)
|
||||
self._save_nested(instance, email_data, webhook_data)
|
||||
save_action_email_and_webhook(instance, email_data, webhook_data)
|
||||
return instance
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
validated_data.pop("id", None)
|
||||
email_data = validated_data.pop("email", None)
|
||||
webhook_data = validated_data.pop("webhook", None)
|
||||
instance = super().update(instance, validated_data)
|
||||
self._save_nested(instance, email_data, webhook_data)
|
||||
save_action_email_and_webhook(instance, email_data, webhook_data)
|
||||
return instance
|
||||
|
||||
def validate(self, attrs):
|
||||
@@ -3438,7 +3469,7 @@ class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
|
||||
{"assign_title": f"{e.args[0]}"},
|
||||
)
|
||||
|
||||
if attrs.get("assign_custom_fields_values") is not None:
|
||||
if attrs.get("assign_custom_fields_values"):
|
||||
if not isinstance(attrs["assign_custom_fields_values"], dict):
|
||||
raise serializers.ValidationError(
|
||||
{"assign_custom_fields_values": "Must be an object"},
|
||||
@@ -3449,37 +3480,23 @@ class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
|
||||
for field_id, value in attrs["assign_custom_fields_values"].items()
|
||||
}
|
||||
|
||||
action_type = attrs.get("type", self.instance.type if self.instance else None)
|
||||
for attribute, nested_type, serializer_class, label in (
|
||||
(
|
||||
"email",
|
||||
WorkflowAction.WorkflowActionType.EMAIL,
|
||||
WorkflowActionEmailSerializer,
|
||||
"Email",
|
||||
),
|
||||
(
|
||||
"webhook",
|
||||
WorkflowAction.WorkflowActionType.WEBHOOK,
|
||||
WorkflowActionWebhookSerializer,
|
||||
"Webhook",
|
||||
),
|
||||
if (
|
||||
"type" in attrs
|
||||
and attrs["type"] == WorkflowAction.WorkflowActionType.EMAIL
|
||||
and "email" not in attrs
|
||||
):
|
||||
if action_type != nested_type or not (
|
||||
"type" in attrs or attribute in attrs
|
||||
):
|
||||
continue
|
||||
if self.instance is not None and getattr(self.instance, attribute):
|
||||
# An existing row can be updated partially
|
||||
continue
|
||||
data = attrs.get(attribute)
|
||||
if not isinstance(data, dict):
|
||||
raise serializers.ValidationError(
|
||||
f"{label} data is required for {attribute} actions",
|
||||
)
|
||||
# A partial update skipped the required fields of this new row
|
||||
nested = serializer_class(data=data, context=self.context)
|
||||
if not nested.is_valid():
|
||||
raise serializers.ValidationError({attribute: nested.errors})
|
||||
raise serializers.ValidationError(
|
||||
"Email data is required for email actions",
|
||||
)
|
||||
|
||||
if (
|
||||
"type" in attrs
|
||||
and attrs["type"] == WorkflowAction.WorkflowActionType.WEBHOOK
|
||||
and "webhook" not in attrs
|
||||
):
|
||||
raise serializers.ValidationError(
|
||||
"Webhook data is required for webhook actions",
|
||||
)
|
||||
|
||||
if (
|
||||
"type" in attrs
|
||||
@@ -3519,7 +3536,11 @@ class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
|
||||
|
||||
|
||||
class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
|
||||
order = serializers.IntegerField(required=False)
|
||||
order = serializers.IntegerField(
|
||||
required=False,
|
||||
min_value=INT32_MIN,
|
||||
max_value=INT32_MAX,
|
||||
)
|
||||
|
||||
triggers = WorkflowTriggerSerializer(many=True)
|
||||
actions = WorkflowActionSerializer(many=True)
|
||||
@@ -3605,6 +3626,10 @@ class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
|
||||
) -> None:
|
||||
set_triggers = []
|
||||
set_actions = []
|
||||
# Only rows already attached to this workflow may be updated by id, an id
|
||||
# from anywhere else would take over or overwrite another workflow's row
|
||||
own_trigger_ids = set(instance.triggers.values_list("pk", flat=True))
|
||||
own_action_ids = set(instance.actions.values_list("pk", flat=True))
|
||||
|
||||
if triggers is not None and triggers is not serializers.empty:
|
||||
for trigger in triggers:
|
||||
@@ -3637,8 +3662,10 @@ class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
|
||||
)
|
||||
# Convert sources to strings to handle django-multiselectfield v1.0 changes
|
||||
WorkflowTriggerSerializer.normalize_workflow_trigger_sources(trigger)
|
||||
trigger_id = trigger.pop("id", None)
|
||||
trigger_instance, _ = WorkflowTrigger.objects.update_or_create(
|
||||
id=trigger.get("id"),
|
||||
# A row that is not already part of this workflow is never reused
|
||||
id=trigger_id if trigger_id in own_trigger_ids else None,
|
||||
defaults=trigger,
|
||||
)
|
||||
if filter_has_tags is not None:
|
||||
@@ -3696,30 +3723,24 @@ class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
|
||||
email_data = action.pop("email", None)
|
||||
webhook_data = action.pop("webhook", None)
|
||||
|
||||
action_id = action.pop("id", None)
|
||||
action_instance, _ = WorkflowAction.objects.update_or_create(
|
||||
id=action.get("id"),
|
||||
# A row that is not already part of this workflow is never reused
|
||||
id=action_id if action_id in own_action_ids else None,
|
||||
defaults=action,
|
||||
)
|
||||
|
||||
if email_data is not None:
|
||||
serializer = WorkflowActionEmailSerializer(data=email_data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
email, _ = WorkflowActionEmail.objects.update_or_create(
|
||||
id=email_data.get("id"),
|
||||
defaults=serializer.validated_data,
|
||||
)
|
||||
action_instance.email = email
|
||||
action_instance.save()
|
||||
email_data = serializer.validated_data
|
||||
|
||||
if webhook_data is not None:
|
||||
serializer = WorkflowActionWebhookSerializer(data=webhook_data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
webhook, _ = WorkflowActionWebhook.objects.update_or_create(
|
||||
id=webhook_data.get("id"),
|
||||
defaults=serializer.validated_data,
|
||||
)
|
||||
action_instance.webhook = webhook
|
||||
action_instance.save()
|
||||
webhook_data = serializer.validated_data
|
||||
|
||||
save_action_email_and_webhook(action_instance, email_data, webhook_data)
|
||||
|
||||
if assign_tags is not None:
|
||||
action_instance.assign_tags.set(assign_tags)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
from collections.abc import Generator
|
||||
|
||||
import pytest
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import connection
|
||||
from pytest_mock import MockerFixture
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import Document
|
||||
from paperless_testing.factories import DocumentFactory
|
||||
|
||||
SIGNED_INT32_RANGE = (-(2**31), 2**31 - 1)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def signed_int32_column(mocker: MockerFixture) -> Generator[None, None, None]:
|
||||
"""
|
||||
Make the database report a signed 32 bit integer range for the column, as
|
||||
PostgreSQL does. Django caches the validators of a field, so the cache is
|
||||
dropped before and after.
|
||||
"""
|
||||
field = Document._meta.get_field("archive_serial_number")
|
||||
field.__dict__.pop("validators", None)
|
||||
mocker.patch.object(
|
||||
connection.ops,
|
||||
"integer_field_range",
|
||||
return_value=SIGNED_INT32_RANGE,
|
||||
)
|
||||
yield
|
||||
field.__dict__.pop("validators", None)
|
||||
|
||||
|
||||
class TestArchiveSerialNumberRange:
|
||||
@pytest.mark.usefixtures("signed_int32_column")
|
||||
@pytest.mark.parametrize("value", [2**31, 3_000_000_000, 0xFF_FF_FF_FF])
|
||||
def test_value_beyond_the_column_is_rejected(self, value: int) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A database whose integer column stops at 2**31 - 1
|
||||
WHEN:
|
||||
- An ASN inside the fixed range but beyond the column is validated
|
||||
THEN:
|
||||
- It is rejected, the database would have raised an error
|
||||
"""
|
||||
with pytest.raises(ValidationError):
|
||||
Document.validate_archive_serial_number(value)
|
||||
|
||||
@pytest.mark.usefixtures("signed_int32_column")
|
||||
@pytest.mark.parametrize("value", [0, 1, 2**31 - 1])
|
||||
def test_value_within_the_column_is_accepted(self, value: int) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A database whose integer column stops at 2**31 - 1
|
||||
WHEN:
|
||||
- An ASN inside the column is validated
|
||||
THEN:
|
||||
- It is accepted
|
||||
"""
|
||||
Document.validate_archive_serial_number(value)
|
||||
|
||||
@pytest.mark.parametrize("value", [-1, 0xFF_FF_FF_FF + 1])
|
||||
def test_value_outside_the_fixed_range_is_rejected(self, value: int) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The fixed ASN range
|
||||
WHEN:
|
||||
- A value outside of it is validated
|
||||
THEN:
|
||||
- It is rejected whatever the database
|
||||
"""
|
||||
with pytest.raises(ValidationError):
|
||||
Document.validate_archive_serial_number(value)
|
||||
|
||||
@pytest.mark.usefixtures("signed_int32_column")
|
||||
def test_api_answers_400_for_a_value_beyond_the_column(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document and a database whose integer column stops at 2**31 - 1
|
||||
WHEN:
|
||||
- The document is patched with a larger ASN
|
||||
THEN:
|
||||
- The response is a 400 naming the field, not a database error
|
||||
"""
|
||||
document = DocumentFactory.create()
|
||||
|
||||
response = admin_client.patch(
|
||||
f"/api/documents/{document.pk}/",
|
||||
{"archive_serial_number": 3_000_000_000},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "archive_serial_number" in response.data
|
||||
@@ -190,12 +190,7 @@ class TestNullAndWrongTypeFields:
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"display_fields",
|
||||
[
|
||||
["custom_field_abc"],
|
||||
["custom_field_"],
|
||||
["xcustom_field_1"],
|
||||
["custom_field_%d"],
|
||||
],
|
||||
[["custom_field_abc"], ["custom_field_"], ["xcustom_field_1"]],
|
||||
)
|
||||
def test_saved_view_custom_field_name_must_be_well_formed(
|
||||
self,
|
||||
@@ -599,102 +594,6 @@ class TestStandaloneWorkflowActions:
|
||||
assert action.email is not None
|
||||
assert action.email.subject == "Subject"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("action_type", "nested", "payload"),
|
||||
[
|
||||
pytest.param(
|
||||
WorkflowAction.WorkflowActionType.EMAIL,
|
||||
"email",
|
||||
{"email": {}},
|
||||
id="email-empty",
|
||||
),
|
||||
pytest.param(
|
||||
WorkflowAction.WorkflowActionType.EMAIL,
|
||||
"email",
|
||||
{"email": None},
|
||||
id="email-null",
|
||||
),
|
||||
pytest.param(
|
||||
WorkflowAction.WorkflowActionType.EMAIL,
|
||||
"email",
|
||||
{"email": {"subject": "Only a subject"}},
|
||||
id="email-incomplete",
|
||||
),
|
||||
pytest.param(
|
||||
WorkflowAction.WorkflowActionType.WEBHOOK,
|
||||
"webhook",
|
||||
{"webhook": {}},
|
||||
id="webhook-empty",
|
||||
),
|
||||
pytest.param(
|
||||
WorkflowAction.WorkflowActionType.WEBHOOK,
|
||||
"webhook",
|
||||
{"webhook": None},
|
||||
id="webhook-null",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_patch_cannot_make_an_incomplete_nested_row(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
action_type: int,
|
||||
nested: str,
|
||||
payload: dict,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An action that has no email or webhook
|
||||
WHEN:
|
||||
- It is patched to an email or webhook action with no, or incomplete,
|
||||
email or webhook data
|
||||
THEN:
|
||||
- The response is a 400 and nothing is stored, a partial update only
|
||||
applies to a row that already exists
|
||||
"""
|
||||
action = WorkflowAction.objects.create(
|
||||
type=WorkflowAction.WorkflowActionType.ASSIGNMENT,
|
||||
)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/workflow_actions/{action.pk}/",
|
||||
{"type": action_type, **payload},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
action.refresh_from_db()
|
||||
assert getattr(action, nested) is None
|
||||
assert action.type == WorkflowAction.WorkflowActionType.ASSIGNMENT
|
||||
|
||||
@pytest.mark.parametrize("value", [[], "", 0, False, "text", 5])
|
||||
def test_custom_field_values_must_be_an_object(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
value: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- An action is created with custom field values that are not an object,
|
||||
including values that are falsy
|
||||
THEN:
|
||||
- The response is a 400 and nothing is stored
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflow_actions/",
|
||||
{
|
||||
"type": WorkflowAction.WorkflowActionType.ASSIGNMENT,
|
||||
"assign_custom_fields_values": value,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert WorkflowAction.objects.count() == 0
|
||||
|
||||
def test_an_id_in_the_payload_cannot_reach_another_actions_email(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
import pytest
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import Correspondent
|
||||
from documents.models import WorkflowAction
|
||||
from documents.models import WorkflowTrigger
|
||||
from paperless_mail.models import MailAccount
|
||||
from paperless_testing.http import send_json
|
||||
|
||||
ACCOUNT = {
|
||||
"name": "Email",
|
||||
"username": "username",
|
||||
"password": "password",
|
||||
"imap_server": "server.example.com",
|
||||
"imap_port": 993,
|
||||
"imap_security": MailAccount.ImapSecurity.SSL,
|
||||
"character_set": "UTF-8",
|
||||
}
|
||||
|
||||
TRIGGER = {"type": 2, "sources": [1, 2, 3], "matching_algorithm": 0}
|
||||
|
||||
|
||||
def create_account(client: APIClient) -> int:
|
||||
response = send_json(client, "POST", "/api/mail_accounts/", ACCOUNT)
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
return response.data["id"]
|
||||
|
||||
|
||||
class TestMailBounds:
|
||||
@pytest.mark.parametrize("port", [-1, 0, 65536, 2**40])
|
||||
def test_imap_port_outside_the_port_range_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
port: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A mail account is created with a port that cannot exist
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
{**ACCOUNT, "imap_port": port},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "imap_port" in response.data
|
||||
|
||||
@pytest.mark.parametrize("port", [1, 993, 65535])
|
||||
def test_imap_port_inside_the_range_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
port: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A mail account is created with a valid port
|
||||
THEN:
|
||||
- It is created
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
{**ACCOUNT, "imap_port": port},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
|
||||
@pytest.mark.parametrize("method", ["PATCH", "PUT"])
|
||||
def test_updating_to_an_impossible_port_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
method: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mail account
|
||||
WHEN:
|
||||
- It is updated with a negative port
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
account_id = create_account(admin_client)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
method,
|
||||
f"/api/mail_accounts/{account_id}/",
|
||||
{**ACCOUNT, "imap_port": -5},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize("order", [2**15, -(2**15) - 1, 2**40])
|
||||
def test_mail_rule_order_beyond_a_smallint_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
order: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mail account
|
||||
WHEN:
|
||||
- A rule is created with an order its column cannot hold
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
account_id = create_account(admin_client)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_rules/",
|
||||
{"name": "rule", "account": account_id, "action": 3, "order": order},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "order" in response.data
|
||||
|
||||
@pytest.mark.parametrize("order", [2**15 - 1, -(2**15)])
|
||||
def test_mail_rule_order_at_the_limits_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
order: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mail account
|
||||
WHEN:
|
||||
- A rule is created with the largest or smallest order
|
||||
THEN:
|
||||
- It is created
|
||||
"""
|
||||
account_id = create_account(admin_client)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_rules/",
|
||||
{"name": "rule", "account": account_id, "action": 3, "order": order},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("length", "expected"),
|
||||
[(256, status.HTTP_201_CREATED), (257, status.HTTP_400_BAD_REQUEST)],
|
||||
)
|
||||
def test_mail_rule_action_parameter_must_fit_the_column(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
length: int,
|
||||
expected: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mail account
|
||||
WHEN:
|
||||
- A rule is created with an action parameter at, or past, the column size
|
||||
THEN:
|
||||
- It is created, or rejected, accordingly
|
||||
"""
|
||||
account_id = create_account(admin_client)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_rules/",
|
||||
{
|
||||
"name": "rule",
|
||||
"account": account_id,
|
||||
"action": 3,
|
||||
"action_parameter": "x" * length,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == expected
|
||||
|
||||
def test_updating_a_mail_rule_to_an_impossible_order_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mail rule
|
||||
WHEN:
|
||||
- It is patched with an order beyond a smallint
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
account_id = create_account(admin_client)
|
||||
rule = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_rules/",
|
||||
{"name": "rule", "account": account_id, "action": 3},
|
||||
)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/mail_rules/{rule.data['id']}/",
|
||||
{"order": 2**40},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
|
||||
class TestWorkflowOrder:
|
||||
@pytest.mark.parametrize(
|
||||
("order", "expected"),
|
||||
[
|
||||
(2**31, status.HTTP_400_BAD_REQUEST),
|
||||
(-(2**31) - 1, status.HTTP_400_BAD_REQUEST),
|
||||
(2**40, status.HTTP_400_BAD_REQUEST),
|
||||
(2**31 - 1, status.HTTP_201_CREATED),
|
||||
(-(2**31), status.HTTP_201_CREATED),
|
||||
],
|
||||
)
|
||||
def test_workflow_order_must_fit_the_column(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
order: int,
|
||||
expected: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A workflow is created with an order beyond a 32 bit integer, or exactly
|
||||
at its limits
|
||||
THEN:
|
||||
- It is rejected, or created, accordingly
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflows/",
|
||||
{
|
||||
"name": "workflow",
|
||||
"order": order,
|
||||
"enabled": True,
|
||||
"triggers": [TRIGGER],
|
||||
"actions": [{"type": 1, "assign_title": "title"}],
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == expected
|
||||
|
||||
|
||||
class TestStandaloneWorkflowRowIds:
|
||||
def test_trigger_created_with_an_existing_id_gets_its_own(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An existing workflow trigger
|
||||
WHEN:
|
||||
- A new trigger is created with that trigger's id in the payload
|
||||
THEN:
|
||||
- A new row is created and the existing one is untouched
|
||||
"""
|
||||
existing = WorkflowTrigger.objects.create(
|
||||
type=2,
|
||||
sources="1",
|
||||
matching_algorithm=0,
|
||||
)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflow_triggers/",
|
||||
{**TRIGGER, "id": existing.pk},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
assert response.data["id"] != existing.pk
|
||||
assert WorkflowTrigger.objects.count() == 2
|
||||
|
||||
def test_action_created_with_an_existing_id_gets_its_own(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An existing workflow action
|
||||
WHEN:
|
||||
- A new action is created with that action's id in the payload
|
||||
THEN:
|
||||
- A new row is created and the existing one is untouched
|
||||
"""
|
||||
existing = WorkflowAction.objects.create(type=1, assign_title="original")
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflow_actions/",
|
||||
{"type": 1, "assign_title": "new", "id": existing.pk},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
assert response.data["id"] != existing.pk
|
||||
existing.refresh_from_db()
|
||||
assert existing.assign_title == "original"
|
||||
|
||||
def test_put_cannot_overwrite_another_trigger_through_the_body_id(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two workflow triggers
|
||||
WHEN:
|
||||
- One is replaced with a body that carries the other's id
|
||||
THEN:
|
||||
- Only the trigger named in the URL changes
|
||||
"""
|
||||
target = WorkflowTrigger.objects.create(
|
||||
type=2,
|
||||
sources="1",
|
||||
matching_algorithm=0,
|
||||
)
|
||||
other = WorkflowTrigger.objects.create(
|
||||
type=2,
|
||||
sources="1",
|
||||
matching_algorithm=0,
|
||||
filter_filename="keep",
|
||||
)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflow_triggers/{target.pk}/",
|
||||
{**TRIGGER, "filter_filename": "changed", "id": other.pk},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
target.refresh_from_db()
|
||||
other.refresh_from_db()
|
||||
assert target.filter_filename == "changed"
|
||||
assert other.filter_filename == "keep"
|
||||
|
||||
|
||||
class TestUniqueNameOnUpdate:
|
||||
@pytest.mark.parametrize("owner_kind", ["owned", "unowned"])
|
||||
def test_patching_to_an_existing_name_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
owner_kind: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two correspondents with the same owner, or none
|
||||
WHEN:
|
||||
- One is patched to the other's name without mentioning the owner
|
||||
THEN:
|
||||
- The response is a 400, as it is when creating a duplicate
|
||||
"""
|
||||
owner = admin_user if owner_kind == "owned" else None
|
||||
Correspondent.objects.create(name="taken", owner=owner)
|
||||
other = Correspondent.objects.create(name="free", owner=owner)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/correspondents/{other.pk}/",
|
||||
{"name": "taken"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
other.refresh_from_db()
|
||||
assert other.name == "free"
|
||||
|
||||
@pytest.mark.parametrize("owner_kind", ["owned", "unowned"])
|
||||
def test_renaming_to_a_free_name_or_keeping_the_name_still_works(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
owner_kind: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A correspondent
|
||||
WHEN:
|
||||
- It is renamed to a free name, then saved again under that name
|
||||
THEN:
|
||||
- Both requests succeed
|
||||
"""
|
||||
correspondent = Correspondent.objects.create(
|
||||
name="before",
|
||||
owner=admin_user if owner_kind == "owned" else None,
|
||||
)
|
||||
|
||||
first = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/correspondents/{correspondent.pk}/",
|
||||
{"name": "after"},
|
||||
)
|
||||
second = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/correspondents/{correspondent.pk}/",
|
||||
{"name": "after"},
|
||||
)
|
||||
|
||||
assert first.status_code == status.HTTP_200_OK
|
||||
assert second.status_code == status.HTTP_200_OK
|
||||
|
||||
def test_the_same_name_under_a_different_owner_is_allowed(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
regular_user: User,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Correspondents with the same name but different owners are allowed
|
||||
WHEN:
|
||||
- One correspondent is renamed to a name another owner already uses
|
||||
THEN:
|
||||
- The request succeeds
|
||||
"""
|
||||
Correspondent.objects.create(name="shared name", owner=regular_user)
|
||||
mine = Correspondent.objects.create(name="mine", owner=admin_user)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/correspondents/{mine.pk}/",
|
||||
{"name": "shared name"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
@@ -0,0 +1,139 @@
|
||||
import pytest
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from paperless_mail.models import MailAccount
|
||||
from paperless_testing.http import send_json
|
||||
|
||||
ACCOUNT = {
|
||||
"name": "Email",
|
||||
"username": "username",
|
||||
"password": "password",
|
||||
"imap_server": "server.example.com",
|
||||
"imap_port": 143,
|
||||
"imap_security": MailAccount.ImapSecurity.STARTTLS,
|
||||
"character_set": "UTF-8",
|
||||
}
|
||||
|
||||
|
||||
class TestStarttlsOnTheSslPort:
|
||||
def test_creating_a_starttls_account_on_port_993_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A mail account is created with STARTTLS on port 993
|
||||
THEN:
|
||||
- The response is a 400 naming the port, that pair can never connect
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
{**ACCOUNT, "imap_port": 993},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "imap_port" in response.data
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("security", "port"),
|
||||
[
|
||||
(MailAccount.ImapSecurity.STARTTLS, 143),
|
||||
(MailAccount.ImapSecurity.SSL, 993),
|
||||
(MailAccount.ImapSecurity.NONE, 143),
|
||||
],
|
||||
)
|
||||
def test_other_combinations_are_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
security: int,
|
||||
port: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A mail account is created with a sensible security and port pair
|
||||
THEN:
|
||||
- It is created
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
{**ACCOUNT, "imap_security": security, "imap_port": port},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
|
||||
def test_the_account_test_endpoint_reports_it_as_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- The account test is run with STARTTLS on port 993
|
||||
THEN:
|
||||
- The response is a 400, the mailbox class refuses that pair with an
|
||||
error that used to escape as a 500
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/test/",
|
||||
{**ACCOUNT, "imap_port": 993},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
def test_a_patch_that_creates_the_pair_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A STARTTLS account on port 143, and an SSL account on port 993
|
||||
WHEN:
|
||||
- Only the port of the first, or only the security of the second, is patched
|
||||
THEN:
|
||||
- Both requests are a 400, the stored half of the pair counts
|
||||
"""
|
||||
starttls = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
ACCOUNT,
|
||||
).data["id"]
|
||||
ssl = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
{
|
||||
**ACCOUNT,
|
||||
"name": "Other",
|
||||
"imap_port": 993,
|
||||
"imap_security": MailAccount.ImapSecurity.SSL,
|
||||
},
|
||||
).data["id"]
|
||||
|
||||
port_patch = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/mail_accounts/{starttls}/",
|
||||
{"imap_port": 993},
|
||||
)
|
||||
security_patch = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/mail_accounts/{ssl}/",
|
||||
{"imap_security": MailAccount.ImapSecurity.STARTTLS},
|
||||
)
|
||||
|
||||
assert port_patch.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert security_patch.status_code == status.HTTP_400_BAD_REQUEST
|
||||
@@ -0,0 +1,405 @@
|
||||
import imaplib
|
||||
import shutil
|
||||
import socket
|
||||
import ssl
|
||||
|
||||
import pytest
|
||||
from django.contrib.auth.models import User
|
||||
from django.core import mail
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from pytest_django.fixtures import Settings
|
||||
from pytest_mock import MockerFixture
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import Document
|
||||
from documents.models import SavedView
|
||||
from paperless_mail.mail import MailError
|
||||
from paperless_testing.dirs import PaperlessDirs
|
||||
from paperless_testing.factories import DocumentFactory
|
||||
from paperless_testing.factories import UserFactory
|
||||
from paperless_testing.http import send_json
|
||||
from paperless_testing.permissions import grant_global
|
||||
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
|
||||
|
||||
EMAIL = {
|
||||
"addresses": "hello@paperless-ngx.com",
|
||||
"subject": "subject",
|
||||
"message": "message",
|
||||
"use_archive_version": False,
|
||||
}
|
||||
|
||||
MAIL_ACCOUNT = {
|
||||
"imap_server": "server.example.com",
|
||||
"imap_port": 993,
|
||||
"imap_security": 2,
|
||||
"username": "admin",
|
||||
"password": "secret",
|
||||
}
|
||||
|
||||
|
||||
class TestEmailSingleDocument:
|
||||
def _document_with_file(self, paperless_dirs: PaperlessDirs) -> Document:
|
||||
document = DocumentFactory.create(
|
||||
filename="test.pdf",
|
||||
mime_type="application/pdf",
|
||||
)
|
||||
shutil.copy(SIMPLE_DIGITAL_PDF, document.source_path)
|
||||
return document
|
||||
|
||||
def test_json_body_sends_the_email(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
paperless_dirs: PaperlessDirs,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document with a file
|
||||
WHEN:
|
||||
- The per document email endpoint gets a JSON body
|
||||
THEN:
|
||||
- The email is sent, a JSON body used to crash on a QueryDict only call
|
||||
"""
|
||||
document = self._document_with_file(paperless_dirs)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
f"/api/documents/{document.pk}/email/",
|
||||
EMAIL,
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert len(mail.outbox) == 1
|
||||
|
||||
def test_form_body_still_sends_the_email(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
paperless_dirs: PaperlessDirs,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document with a file
|
||||
WHEN:
|
||||
- The endpoint gets a form encoded body
|
||||
THEN:
|
||||
- The email is sent
|
||||
"""
|
||||
document = self._document_with_file(paperless_dirs)
|
||||
|
||||
response = admin_client.post(
|
||||
f"/api/documents/{document.pk}/email/",
|
||||
EMAIL,
|
||||
format="multipart",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert len(mail.outbox) == 1
|
||||
|
||||
def test_json_body_is_still_validated(self, admin_client: APIClient) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document
|
||||
WHEN:
|
||||
- A JSON body without addresses is sent
|
||||
THEN:
|
||||
- The response is a 400 from the serializer, not a server error
|
||||
"""
|
||||
document = DocumentFactory.create()
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
f"/api/documents/{document.pk}/email/",
|
||||
{"subject": "only a subject"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "addresses" in response.data
|
||||
|
||||
|
||||
class TestMailAccountTest:
|
||||
def test_form_encoded_body_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
mocker: MockerFixture,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mailbox that connects
|
||||
WHEN:
|
||||
- The account test gets a form encoded body, which is a read only QueryDict
|
||||
THEN:
|
||||
- The request succeeds, the view must not write into the request data
|
||||
"""
|
||||
mocker.patch("paperless_mail.views.get_mailbox")
|
||||
mocker.patch("paperless_mail.views.mailbox_login")
|
||||
|
||||
response = admin_client.post(
|
||||
"/api/mail_accounts/test/",
|
||||
MAIL_ACCOUNT,
|
||||
format="multipart",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data == {"success": True}
|
||||
|
||||
def test_write_only_serializer_fields_are_not_passed_to_the_model(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
mocker: MockerFixture,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mailbox that connects
|
||||
WHEN:
|
||||
- The account test body carries set_permissions, which is not a model field
|
||||
THEN:
|
||||
- The request succeeds
|
||||
"""
|
||||
mocker.patch("paperless_mail.views.get_mailbox")
|
||||
mocker.patch("paperless_mail.views.mailbox_login")
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/test/",
|
||||
{
|
||||
**MAIL_ACCOUNT,
|
||||
"set_permissions": {"view": {"users": [], "groups": []}},
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
def test_multipart_body_with_a_large_file_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
mocker: MockerFixture,
|
||||
settings: Settings,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mailbox that connects, and uploads that spill to a temporary file
|
||||
WHEN:
|
||||
- The account test gets a multipart body that carries a large file
|
||||
THEN:
|
||||
- The request succeeds, copying the request data would try to deep copy
|
||||
the temporary file and fail
|
||||
"""
|
||||
settings.FILE_UPLOAD_MAX_MEMORY_SIZE = 10
|
||||
mocker.patch("paperless_mail.views.get_mailbox")
|
||||
mocker.patch("paperless_mail.views.mailbox_login")
|
||||
|
||||
response = admin_client.post(
|
||||
"/api/mail_accounts/test/",
|
||||
{
|
||||
**MAIL_ACCOUNT,
|
||||
"attachment": SimpleUploadedFile("junk.bin", b"0" * 1000),
|
||||
},
|
||||
format="multipart",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
pytest.param(ConnectionRefusedError, id="refused"),
|
||||
pytest.param(socket.gaierror, id="unknown-host"),
|
||||
pytest.param(TimeoutError, id="timeout"),
|
||||
pytest.param(ssl.SSLError, id="tls"),
|
||||
pytest.param(imaplib.IMAP4.error, id="imap-error"),
|
||||
pytest.param(UnicodeError, id="bad-host-name"),
|
||||
pytest.param(MailError, id="mail-error"),
|
||||
],
|
||||
)
|
||||
def test_connection_failures_are_reported_as_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
mocker: MockerFixture,
|
||||
error: type[Exception],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mailbox that cannot be reached
|
||||
WHEN:
|
||||
- The account test is run
|
||||
THEN:
|
||||
- The response is a 400 saying the server cannot be reached, that is the
|
||||
answer this endpoint exists to give
|
||||
"""
|
||||
mocker.patch("paperless_mail.views.get_mailbox", side_effect=error("boom"))
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/test/",
|
||||
MAIL_ACCOUNT,
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert response.content == b"Unable to connect to server"
|
||||
|
||||
|
||||
class TestDeactivateTotp:
|
||||
def test_unknown_user_is_a_404_for_a_superuser(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A superuser
|
||||
WHEN:
|
||||
- TOTP is deactivated for a user id that does not exist
|
||||
THEN:
|
||||
- The response is a 404
|
||||
"""
|
||||
response = admin_client.post("/api/users/999999/deactivate_totp/")
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
def test_non_numeric_user_id_is_a_404_for_a_superuser(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A superuser
|
||||
WHEN:
|
||||
- The user id is not a number
|
||||
THEN:
|
||||
- The response is a 404, not a server error
|
||||
"""
|
||||
response = admin_client.post("/api/users/abc/deactivate_totp/")
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
def test_status_does_not_reveal_whether_another_user_exists(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
regular_user: User,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A regular user allowed to use the users API, and another user
|
||||
WHEN:
|
||||
- They deactivate TOTP for another existing user, and for one that does not
|
||||
exist
|
||||
THEN:
|
||||
- Both answers are a 403, so the status cannot be used to find user ids
|
||||
"""
|
||||
grant_global(regular_user, "add_user", "change_user")
|
||||
other = UserFactory.create(username="other")
|
||||
rest_api_client.force_authenticate(user=regular_user)
|
||||
|
||||
existing = rest_api_client.post(f"/api/users/{other.pk}/deactivate_totp/")
|
||||
missing = rest_api_client.post("/api/users/999999/deactivate_totp/")
|
||||
|
||||
assert existing.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert missing.status_code == status.HTTP_403_FORBIDDEN
|
||||
|
||||
def test_a_user_can_reach_their_own_record(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
regular_user: User,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A regular user with no authenticator
|
||||
WHEN:
|
||||
- They deactivate TOTP for themselves
|
||||
THEN:
|
||||
- The lookup succeeds and the answer is that no TOTP was found
|
||||
"""
|
||||
grant_global(regular_user, "add_user", "change_user")
|
||||
rest_api_client.force_authenticate(user=regular_user)
|
||||
|
||||
response = rest_api_client.post(
|
||||
f"/api/users/{regular_user.pk}/deactivate_totp/",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
assert response.content == b"TOTP not found"
|
||||
|
||||
|
||||
class TestSavedViewPartialRules:
|
||||
def test_patch_with_a_rule_missing_its_type_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A saved view
|
||||
WHEN:
|
||||
- It is patched with a filter rule that has no rule_type
|
||||
THEN:
|
||||
- The response is a 400, not a database error
|
||||
"""
|
||||
view = SavedView.objects.create(
|
||||
name="view",
|
||||
owner=admin_user,
|
||||
sort_field="created",
|
||||
)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/saved_views/{view.pk}/",
|
||||
{"filter_rules": [{"value": "1"}]},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "filter_rules" in response.data
|
||||
|
||||
|
||||
class TestConfigFormBody:
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
["language=", "llm_api_key=", "language=&llm_api_key="],
|
||||
)
|
||||
def test_form_encoded_empty_values_are_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
config_id: int,
|
||||
body: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The application configuration
|
||||
WHEN:
|
||||
- A form encoded body with empty values is patched in
|
||||
THEN:
|
||||
- The request succeeds, the serializer used to write into the read only
|
||||
QueryDict
|
||||
"""
|
||||
response = admin_client.patch(
|
||||
f"/api/config/{config_id}/",
|
||||
data=body,
|
||||
content_type="application/x-www-form-urlencoded",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
def test_form_encoded_empty_json_field_is_a_clean_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
config_id: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The application configuration
|
||||
WHEN:
|
||||
- An empty value for a JSON field arrives in a form encoded body
|
||||
THEN:
|
||||
- The response is a 400 naming the field, not a server error
|
||||
"""
|
||||
response = admin_client.patch(
|
||||
f"/api/config/{config_id}/",
|
||||
data="user_args=",
|
||||
content_type="application/x-www-form-urlencoded",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "user_args" in response.data
|
||||
@@ -5,6 +5,7 @@ from django.core.management import call_command
|
||||
from django.core.management.base import CommandError
|
||||
from drf_spectacular.generators import SchemaGenerator
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
from rest_framework.test import APITestCase
|
||||
|
||||
|
||||
@@ -341,6 +342,276 @@ class TestDocumentListObjectFilterSchema:
|
||||
assert param["explode"] is False
|
||||
|
||||
|
||||
class TestCommonErrorResponsesSchema:
|
||||
def test_detail_operations_document_400_and_404(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The detail operations of a resource are read
|
||||
THEN:
|
||||
- A 400 and a 404 are documented, no view declares them itself
|
||||
"""
|
||||
operation = api_schema["paths"]["/api/tags/{id}/"]["patch"]
|
||||
|
||||
assert "400" in operation["responses"]
|
||||
assert "404" in operation["responses"]
|
||||
|
||||
def test_paginated_list_documents_404_for_a_missing_page(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- A paginated list operation is read
|
||||
THEN:
|
||||
- A 404 is documented, an out of range page answers one
|
||||
"""
|
||||
responses = api_schema["paths"]["/api/tags/"]["get"]["responses"]
|
||||
|
||||
assert "404" in responses
|
||||
|
||||
def test_operation_without_input_has_no_400(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An operation with no parameters and no body
|
||||
WHEN:
|
||||
- Its responses are read
|
||||
THEN:
|
||||
- No 400 is added, there is no input to reject
|
||||
"""
|
||||
responses = api_schema["paths"]["/api/status/"]["get"]["responses"]
|
||||
|
||||
assert "400" not in responses
|
||||
assert "404" not in responses
|
||||
|
||||
def test_responses_declared_by_a_view_are_kept(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An operation whose view documents its own 400
|
||||
WHEN:
|
||||
- Its responses are read
|
||||
THEN:
|
||||
- The description of the view is kept
|
||||
"""
|
||||
responses = api_schema["paths"]["/api/oauth/callback/"]["get"]["responses"]
|
||||
|
||||
assert responses["400"]["description"] != "Invalid input"
|
||||
|
||||
|
||||
class TestDocumentFileContentTypesSchema:
|
||||
@pytest.mark.parametrize(
|
||||
("path", "content_type"),
|
||||
[
|
||||
("/api/documents/{id}/download/", "*/*"),
|
||||
("/api/documents/{id}/preview/", "*/*"),
|
||||
("/api/documents/{id}/thumb/", "image/webp"),
|
||||
],
|
||||
)
|
||||
def test_file_endpoints_declare_the_real_content_type(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
path: str,
|
||||
content_type: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The 200 response of a document file endpoint is read
|
||||
THEN:
|
||||
- It declares the content type it is served with, not JSON
|
||||
"""
|
||||
content = api_schema["paths"][path]["get"]["responses"]["200"]["content"]
|
||||
|
||||
assert list(content) == [content_type]
|
||||
|
||||
|
||||
class TestConditionalResponseFieldsSchema:
|
||||
@pytest.mark.parametrize(
|
||||
"component",
|
||||
["Tag", "Correspondent", "DocumentType", "StoragePath", "Document"],
|
||||
)
|
||||
def test_fields_present_only_sometimes_are_not_required(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
component: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The response component of an owned object is read
|
||||
THEN:
|
||||
- Permissions, the permission flags and the annotated counts are not
|
||||
required, a create or update response and a response without full_perms
|
||||
do not carry them
|
||||
"""
|
||||
schema = api_schema["components"]["schemas"][component]
|
||||
required = set(schema.get("required", []))
|
||||
|
||||
assert required.isdisjoint(
|
||||
{
|
||||
"permissions",
|
||||
"user_can_change",
|
||||
"is_shared_by_requester",
|
||||
"document_count",
|
||||
"last_correspondence",
|
||||
},
|
||||
)
|
||||
assert "id" in required
|
||||
|
||||
def test_fields_of_other_components_stay_required(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A response component that is not an owned object but has a count
|
||||
WHEN:
|
||||
- Its required fields are read
|
||||
THEN:
|
||||
- The count is still required, it is always present
|
||||
"""
|
||||
schema = api_schema["components"]["schemas"]["ShareLinkBundle"]
|
||||
|
||||
assert "document_count" in schema["required"]
|
||||
|
||||
|
||||
class TestSystemStatusSchema:
|
||||
def test_status_fields_match_the_response(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The system status response is read
|
||||
THEN:
|
||||
- The index, classifier and sanity check fields are inside tasks, as the
|
||||
view returns them, and storage sizes are 64 bit
|
||||
"""
|
||||
schemas = api_schema["components"]["schemas"]
|
||||
status_schema = schemas["SystemStatus"]
|
||||
tasks = schemas["Tasks"]["properties"]
|
||||
|
||||
assert set(status_schema["properties"]) == {
|
||||
"pngx_version",
|
||||
"server_os",
|
||||
"install_type",
|
||||
"storage",
|
||||
"database",
|
||||
"tasks",
|
||||
}
|
||||
assert {
|
||||
"index_status",
|
||||
"classifier_last_trained",
|
||||
"sanity_check_error",
|
||||
"llmindex_status",
|
||||
} <= set(tasks)
|
||||
assert schemas["Storage"]["properties"]["total"]["format"] == "int64"
|
||||
|
||||
|
||||
class TestUiSettingsSchema:
|
||||
def test_get_response_has_user_settings_and_permissions(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The response of GET /api/ui_settings/ is read
|
||||
THEN:
|
||||
- It has the user, settings and permissions the view returns, and no
|
||||
request body
|
||||
"""
|
||||
operation = api_schema["paths"]["/api/ui_settings/"]["get"]
|
||||
response = operation["responses"]["200"]["content"]["application/json"]
|
||||
|
||||
assert "requestBody" not in operation
|
||||
assert response["schema"]["$ref"].endswith("/UiSettingsResponse")
|
||||
properties = api_schema["components"]["schemas"]["UiSettingsResponse"][
|
||||
"properties"
|
||||
]
|
||||
assert set(properties) == {"user", "settings", "permissions"}
|
||||
|
||||
|
||||
class TestRunZoneOcrResponseSchema:
|
||||
def test_task_id_and_reason_are_optional(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The response of run-zone-ocr is read
|
||||
THEN:
|
||||
- Only the result is required, task_id is absent when the run was
|
||||
skipped and the reason is absent when it was queued
|
||||
"""
|
||||
schema = api_schema["components"]["schemas"]["RunZoneOcrResponse"]
|
||||
|
||||
assert schema["required"] == ["result"]
|
||||
|
||||
|
||||
class TestDocumentShareLinksSchema:
|
||||
def test_response_is_a_list_of_share_links(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The response of the share links of a document is read
|
||||
THEN:
|
||||
- It is the share link serializer, which allows a null expiration
|
||||
"""
|
||||
operation = api_schema["paths"]["/api/documents/{id}/share_links/"]["get"]
|
||||
items = operation["responses"]["200"]["content"]["application/json"]["schema"][
|
||||
"items"
|
||||
]
|
||||
|
||||
assert items["$ref"].endswith("/ShareLink")
|
||||
|
||||
|
||||
class TestTagChildrenAndHistorySchema:
|
||||
def test_tag_children_are_nested_tags(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The children of a tag are read
|
||||
THEN:
|
||||
- They are tags, the API nests the objects and does not return ids
|
||||
"""
|
||||
children = api_schema["components"]["schemas"]["Tag"]["properties"]["children"]
|
||||
|
||||
assert children["items"] == {"$ref": "#/components/schemas/Tag"}
|
||||
|
||||
def test_history_is_an_unpaginated_list(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The history response of a document is read
|
||||
THEN:
|
||||
- It is a plain array of log entries, the view does not paginate
|
||||
"""
|
||||
operation = api_schema["paths"]["/api/documents/{id}/history/"]["get"]
|
||||
schema = operation["responses"]["200"]["content"]["application/json"]["schema"]
|
||||
|
||||
assert schema["type"] == "array"
|
||||
|
||||
|
||||
class TestOauthCallbackSchema:
|
||||
@pytest.mark.parametrize("name", ["code", "state"])
|
||||
def test_empty_code_and_state_are_not_schema_valid(
|
||||
@@ -363,6 +634,200 @@ class TestOauthCallbackSchema:
|
||||
assert param["schema"]["minLength"] == 1
|
||||
|
||||
|
||||
class TestRemainingResponseShapesSchema:
|
||||
def test_logs_limit_must_be_positive(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The limit parameter of the log endpoint is read
|
||||
THEN:
|
||||
- It has a minimum of 1, the view rejects anything lower
|
||||
"""
|
||||
params = api_schema["paths"]["/api/logs/{id}/"]["get"]["parameters"]
|
||||
limit = next(p for p in params if p["name"] == "limit")
|
||||
|
||||
assert limit["schema"]["minimum"] == 1
|
||||
|
||||
@pytest.mark.parametrize("name", ["since", "until"])
|
||||
def test_release_notes_versions_have_a_pattern(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
name: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The version parameters of the release notes are read
|
||||
THEN:
|
||||
- They are patterned like a version, anything else answers a 400
|
||||
"""
|
||||
params = api_schema["paths"]["/api/release_notes/"]["get"]["parameters"]
|
||||
param = next(p for p in params if p["name"] == name)
|
||||
|
||||
assert "pattern" in param["schema"]
|
||||
|
||||
def test_deactivate_totp_404_is_html(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The 404 of deactivate_totp is read
|
||||
THEN:
|
||||
- It is text, the view answers with a plain not found response
|
||||
"""
|
||||
responses = api_schema["paths"]["/api/users/{id}/deactivate_totp/"]["post"][
|
||||
"responses"
|
||||
]
|
||||
|
||||
assert list(responses["404"]["content"]) == ["text/html"]
|
||||
|
||||
def test_ocr_error_body_has_no_required_fields(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The error body of the OCR actions is read
|
||||
THEN:
|
||||
- Neither error nor detail is required, a missing document answers with
|
||||
a detail and the actions answer with an error
|
||||
"""
|
||||
schema = api_schema["components"]["schemas"]["OcrError"]
|
||||
|
||||
assert "required" not in schema
|
||||
assert {"error", "detail"} <= set(schema["properties"])
|
||||
|
||||
def test_nullable_response_fields(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The root document of a document and the last correspondence of a
|
||||
correspondent are read
|
||||
THEN:
|
||||
- Both are nullable, a root document has no root and a correspondent
|
||||
may have no documents
|
||||
"""
|
||||
schemas = api_schema["components"]["schemas"]
|
||||
|
||||
assert schemas["Document"]["properties"]["root_document"]["nullable"] is True
|
||||
assert (
|
||||
schemas["Correspondent"]["properties"]["last_correspondence"]["nullable"]
|
||||
is True
|
||||
)
|
||||
|
||||
def test_custom_field_count_is_optional(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The custom field response is read
|
||||
THEN:
|
||||
- document_count is not required, a create response does not have it
|
||||
"""
|
||||
required = api_schema["components"]["schemas"]["CustomField"]["required"]
|
||||
|
||||
assert "document_count" not in required
|
||||
|
||||
|
||||
class TestSearchAndMailTestSchema:
|
||||
def test_autocomplete_term_is_required(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The term parameter of autocomplete is read
|
||||
THEN:
|
||||
- It is required, the view answers 400 without it
|
||||
"""
|
||||
params = api_schema["paths"]["/api/search/autocomplete/"]["get"]["parameters"]
|
||||
term = next(p for p in params if p["name"] == "term")
|
||||
|
||||
assert term["required"] is True
|
||||
|
||||
def test_global_search_query_has_a_minimum_length(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The query parameter of the global search is read
|
||||
THEN:
|
||||
- It has a minimum length of 3, the view answers 400 to a shorter one
|
||||
"""
|
||||
params = api_schema["paths"]["/api/search/"]["get"]["parameters"]
|
||||
query = next(p for p in params if p["name"] == "query")
|
||||
|
||||
assert query["schema"]["minLength"] == 3
|
||||
|
||||
def test_mail_account_test_400_is_html(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The 400 of the mail account test is read
|
||||
THEN:
|
||||
- It is text, the view answers with a plain bad request response
|
||||
"""
|
||||
responses = api_schema["paths"]["/api/mail_accounts/test/"]["post"]["responses"]
|
||||
|
||||
assert list(responses["400"]["content"]) == ["text/html"]
|
||||
|
||||
|
||||
class TestTagColorSchema:
|
||||
def test_color_has_a_hex_pattern(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The color of a tag request is read
|
||||
THEN:
|
||||
- It has a hex pattern, the serializer rejects anything else
|
||||
"""
|
||||
color = api_schema["components"]["schemas"]["TagRequest"]["properties"]["color"]
|
||||
|
||||
assert color["pattern"] == "^#[0-9a-fA-F]{6}$"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("color", "expected"),
|
||||
[
|
||||
("#a6cee3", 201),
|
||||
("#A6CEE3", 201),
|
||||
("a6cee3", 400),
|
||||
("#a6cee", 400),
|
||||
("#a6ceez", 400),
|
||||
("#a6cee3x", 400),
|
||||
],
|
||||
)
|
||||
def test_color_validation_is_unchanged(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
color: str,
|
||||
expected: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A tag request
|
||||
WHEN:
|
||||
- It is created with a valid or an invalid color
|
||||
THEN:
|
||||
- Only a # followed by six hex digits is accepted
|
||||
"""
|
||||
response = admin_client.post(
|
||||
"/api/tags/",
|
||||
{"name": "colored", "color": color},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == expected
|
||||
|
||||
|
||||
class TestOcrPageImageSchema:
|
||||
def test_page_image_is_declared_as_png(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
import json
|
||||
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import WorkflowAction
|
||||
from documents.models import WorkflowActionEmail
|
||||
from documents.models import WorkflowTrigger
|
||||
from paperless_testing.http import send_json
|
||||
|
||||
EMAIL = {
|
||||
"subject": "original",
|
||||
"body": "body",
|
||||
"to": "someone@example.com",
|
||||
"include_document": False,
|
||||
}
|
||||
|
||||
|
||||
def workflow_body(name: str, *, trigger: dict, action: dict) -> dict:
|
||||
return {
|
||||
"name": name,
|
||||
"order": 0,
|
||||
"enabled": True,
|
||||
"triggers": [
|
||||
{"type": 2, "sources": [1], "matching_algorithm": 0, **trigger},
|
||||
],
|
||||
"actions": [{"type": 3, "email": EMAIL, **action}],
|
||||
}
|
||||
|
||||
|
||||
def make_workflow(client: APIClient, name: str) -> dict:
|
||||
response = send_json(
|
||||
client,
|
||||
"POST",
|
||||
"/api/workflows/",
|
||||
workflow_body(name, trigger={}, action={}),
|
||||
)
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
return response.data
|
||||
|
||||
|
||||
class TestWorkflowRowOwnership:
|
||||
def test_update_cannot_take_over_another_workflows_action(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two workflows, each with an email action
|
||||
WHEN:
|
||||
- The first is updated with the id of the second one's action and a changed
|
||||
email
|
||||
THEN:
|
||||
- The second workflow's action and email are untouched, the first gets its
|
||||
own action
|
||||
"""
|
||||
first = make_workflow(admin_client, "first")
|
||||
second = make_workflow(admin_client, "second")
|
||||
foreign_action = second["actions"][0]
|
||||
foreign_email_id = foreign_action["email"]["id"]
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{first['id']}/",
|
||||
workflow_body(
|
||||
"first",
|
||||
trigger={"id": first["triggers"][0]["id"]},
|
||||
action={
|
||||
"id": foreign_action["id"],
|
||||
"email": {**EMAIL, "subject": "taken over"},
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["actions"][0]["id"] != foreign_action["id"]
|
||||
assert WorkflowActionEmail.objects.get(pk=foreign_email_id).subject == (
|
||||
"original"
|
||||
)
|
||||
second_actions = list(
|
||||
WorkflowAction.objects.filter(workflows__pk=second["id"]),
|
||||
)
|
||||
assert [a.pk for a in second_actions] == [foreign_action["id"]]
|
||||
|
||||
def test_update_cannot_take_over_another_workflows_trigger(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two workflows
|
||||
WHEN:
|
||||
- The first is updated with the id of the second one's trigger and a
|
||||
different filter
|
||||
THEN:
|
||||
- The second workflow's trigger is untouched
|
||||
"""
|
||||
first = make_workflow(admin_client, "first")
|
||||
second = make_workflow(admin_client, "second")
|
||||
foreign_trigger_id = second["triggers"][0]["id"]
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{first['id']}/",
|
||||
workflow_body(
|
||||
"first",
|
||||
trigger={"id": foreign_trigger_id, "filter_filename": "taken"},
|
||||
action={"id": first["actions"][0]["id"]},
|
||||
),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["triggers"][0]["id"] != foreign_trigger_id
|
||||
assert WorkflowTrigger.objects.get(pk=foreign_trigger_id).filter_filename != (
|
||||
"taken"
|
||||
)
|
||||
assert list(
|
||||
WorkflowTrigger.objects.filter(workflows__pk=second["id"]).values_list(
|
||||
"pk",
|
||||
flat=True,
|
||||
),
|
||||
) == [foreign_trigger_id]
|
||||
|
||||
def test_nested_email_id_of_another_action_is_ignored(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two workflows with email actions
|
||||
WHEN:
|
||||
- The first is updated, keeping its own action, with the second action's
|
||||
email id in the nested email
|
||||
THEN:
|
||||
- The other email is untouched and the action's own email is the one
|
||||
changed
|
||||
"""
|
||||
first = make_workflow(admin_client, "first")
|
||||
second = make_workflow(admin_client, "second")
|
||||
own_action = first["actions"][0]
|
||||
own_email_id = own_action["email"]["id"]
|
||||
foreign_email_id = second["actions"][0]["email"]["id"]
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{first['id']}/",
|
||||
workflow_body(
|
||||
"first",
|
||||
trigger={"id": first["triggers"][0]["id"]},
|
||||
action={
|
||||
"id": own_action["id"],
|
||||
"email": {**EMAIL, "id": foreign_email_id, "subject": "mine"},
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert WorkflowActionEmail.objects.get(pk=foreign_email_id).subject == (
|
||||
"original"
|
||||
)
|
||||
assert response.data["actions"][0]["email"]["id"] == own_email_id
|
||||
assert WorkflowActionEmail.objects.get(pk=own_email_id).subject == "mine"
|
||||
|
||||
def test_nested_email_id_beyond_the_database_range_is_ignored(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A workflow with an email action
|
||||
WHEN:
|
||||
- It is updated with a nested email id larger than a column can hold
|
||||
THEN:
|
||||
- The request succeeds and the action keeps its own email row
|
||||
"""
|
||||
workflow = make_workflow(admin_client, "workflow")
|
||||
action = workflow["actions"][0]
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{workflow['id']}/",
|
||||
workflow_body(
|
||||
"workflow",
|
||||
trigger={"id": workflow["triggers"][0]["id"]},
|
||||
action={
|
||||
"id": action["id"],
|
||||
"email": {**EMAIL, "id": 2**63},
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["actions"][0]["email"]["id"] == action["email"]["id"]
|
||||
|
||||
def test_create_ignores_ids_of_existing_rows(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An existing workflow
|
||||
WHEN:
|
||||
- A new workflow is created that carries that workflow's trigger and
|
||||
action ids
|
||||
THEN:
|
||||
- New rows are created and the existing ones are untouched
|
||||
"""
|
||||
existing = make_workflow(admin_client, "existing")
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflows/",
|
||||
workflow_body(
|
||||
"new",
|
||||
trigger={
|
||||
"id": existing["triggers"][0]["id"],
|
||||
"filter_filename": "taken",
|
||||
},
|
||||
action={"id": existing["actions"][0]["id"]},
|
||||
),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
assert response.data["triggers"][0]["id"] != existing["triggers"][0]["id"]
|
||||
assert response.data["actions"][0]["id"] != existing["actions"][0]["id"]
|
||||
assert WorkflowTrigger.objects.get(
|
||||
pk=existing["triggers"][0]["id"],
|
||||
).filter_filename != ("taken")
|
||||
|
||||
def test_editing_a_workflow_keeps_its_row_ids(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A workflow read back from the API, as the UI does before an edit
|
||||
WHEN:
|
||||
- It is sent back with a changed name and email subject
|
||||
THEN:
|
||||
- Its trigger, action and email keep their ids and no rows are added
|
||||
"""
|
||||
workflow = make_workflow(admin_client, "workflow")
|
||||
body = admin_client.get(f"/api/workflows/{workflow['id']}/").data
|
||||
body = json.loads(json.dumps(body))
|
||||
body["name"] = "renamed"
|
||||
body["actions"][0]["email"]["subject"] = "edited"
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{workflow['id']}/",
|
||||
body,
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["triggers"][0]["id"] == workflow["triggers"][0]["id"]
|
||||
assert response.data["actions"][0]["id"] == workflow["actions"][0]["id"]
|
||||
assert (
|
||||
response.data["actions"][0]["email"]["id"]
|
||||
== (workflow["actions"][0]["email"]["id"])
|
||||
)
|
||||
assert response.data["actions"][0]["email"]["subject"] == "edited"
|
||||
assert WorkflowAction.objects.count() == 1
|
||||
assert WorkflowActionEmail.objects.count() == 1
|
||||
assert WorkflowTrigger.objects.count() == 1
|
||||
|
||||
def test_a_new_action_in_an_update_is_added_beside_the_existing_one(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A workflow with one action
|
||||
WHEN:
|
||||
- It is updated with that action plus a new one without an id
|
||||
THEN:
|
||||
- The first action keeps its id and a second one is created
|
||||
"""
|
||||
workflow = make_workflow(admin_client, "workflow")
|
||||
body = json.loads(
|
||||
json.dumps(admin_client.get(f"/api/workflows/{workflow['id']}/").data),
|
||||
)
|
||||
body["actions"].append({"type": 1, "assign_title": "added"})
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{workflow['id']}/",
|
||||
body,
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert len(response.data["actions"]) == 2
|
||||
assert response.data["actions"][0]["id"] == workflow["actions"][0]["id"]
|
||||
+104
-52
@@ -198,6 +198,7 @@ from documents.permissions import set_permissions_for_objects
|
||||
from documents.permissions import user_is_unrestricted
|
||||
from documents.plugins.date_parsing import get_date_parser
|
||||
from documents.regex import safe_regex_fullmatch
|
||||
from documents.schema import Int64Field
|
||||
from documents.schema import generate_object_with_permissions_schema
|
||||
from documents.search import SearchHit
|
||||
from documents.serialisers import AcknowledgeTasksViewSerializer
|
||||
@@ -766,7 +767,8 @@ class EmailDocumentDetailSchema(EmailSerializer):
|
||||
location=OpenApiParameter.QUERY,
|
||||
),
|
||||
],
|
||||
responses={200: OpenApiTypes.BINARY},
|
||||
# The file is served with its own mime type
|
||||
responses={(200, "*/*"): OpenApiTypes.BINARY},
|
||||
),
|
||||
history=extend_schema(
|
||||
description="View the document history",
|
||||
@@ -785,6 +787,7 @@ class EmailDocumentDetailSchema(EmailSerializer):
|
||||
"id": serializers.IntegerField(),
|
||||
"username": serializers.CharField(),
|
||||
},
|
||||
allow_null=True,
|
||||
),
|
||||
},
|
||||
),
|
||||
@@ -933,11 +936,11 @@ class EmailDocumentDetailSchema(EmailSerializer):
|
||||
),
|
||||
thumb=extend_schema(
|
||||
description="View the document thumbnail",
|
||||
responses={200: OpenApiTypes.BINARY},
|
||||
responses={(200, "image/webp"): OpenApiTypes.BINARY},
|
||||
),
|
||||
preview=extend_schema(
|
||||
description="View the document preview",
|
||||
responses={200: OpenApiTypes.BINARY},
|
||||
responses={(200, "*/*"): OpenApiTypes.BINARY},
|
||||
),
|
||||
share_links=extend_schema(
|
||||
operation_id="document_share_links",
|
||||
@@ -950,18 +953,7 @@ class EmailDocumentDetailSchema(EmailSerializer):
|
||||
),
|
||||
],
|
||||
responses={
|
||||
200: {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"type": "integer"},
|
||||
"created": {"type": "string", "format": "date-time"},
|
||||
"expiration": {"type": "string", "format": "date-time"},
|
||||
"slug": {"type": "string"},
|
||||
},
|
||||
},
|
||||
},
|
||||
200: ShareLinkSerializer(many=True),
|
||||
400: None,
|
||||
403: None,
|
||||
404: None,
|
||||
@@ -2010,7 +2002,12 @@ class DocumentViewSet(
|
||||
},
|
||||
)
|
||||
|
||||
@action(methods=["get"], detail=True, filter_backends=[])
|
||||
@action(
|
||||
methods=["get"],
|
||||
detail=True,
|
||||
filter_backends=[],
|
||||
pagination_class=None,
|
||||
)
|
||||
def share_links(self, request, pk=None):
|
||||
currentUser = request.user
|
||||
try:
|
||||
@@ -2046,7 +2043,13 @@ class DocumentViewSet(
|
||||
serializer = ShareLinkSerializer(links, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
@action(methods=["get"], detail=True, name="Audit Trail", filter_backends=[])
|
||||
@action(
|
||||
methods=["get"],
|
||||
detail=True,
|
||||
name="Audit Trail",
|
||||
filter_backends=[],
|
||||
pagination_class=None,
|
||||
)
|
||||
def history(self, request, pk=None):
|
||||
if not settings.AUDIT_LOG_ENABLED:
|
||||
return HttpResponseBadRequest("Audit log is disabled")
|
||||
@@ -2120,8 +2123,9 @@ class DocumentViewSet(
|
||||
)
|
||||
# TODO: deprecated, remove with drop of support for API v9
|
||||
def email_document(self, request, pk=None):
|
||||
request_data = request.data.copy()
|
||||
request_data.setlist("documents", [pk])
|
||||
# A JSON body is a plain dict and a form body a QueryDict, copy into a dict
|
||||
request_data = dict(request.data.items())
|
||||
request_data["documents"] = [pk]
|
||||
return self.email_documents(request, data=request_data)
|
||||
|
||||
@action(
|
||||
@@ -2925,7 +2929,7 @@ LOG_FILES = {
|
||||
),
|
||||
OpenApiParameter(
|
||||
name="limit",
|
||||
type=OpenApiTypes.INT,
|
||||
type={"type": "integer", "minimum": 1},
|
||||
location=OpenApiParameter.QUERY,
|
||||
description="Return only the last N entries from the log file",
|
||||
required=False,
|
||||
@@ -3724,7 +3728,7 @@ class SelectionDataView(DocumentSelectionMixin, GenericAPIView[Any]):
|
||||
parameters=[
|
||||
OpenApiParameter(
|
||||
name="term",
|
||||
required=False,
|
||||
required=True,
|
||||
type=str,
|
||||
description="Term to search for",
|
||||
),
|
||||
@@ -3775,7 +3779,8 @@ class SearchAutoCompleteView(GenericAPIView[Any]):
|
||||
OpenApiParameter(
|
||||
name="query",
|
||||
required=True,
|
||||
type=str,
|
||||
# Shorter queries are answered with a 400
|
||||
type={"type": "string", "minLength": 3},
|
||||
description="Query to search for",
|
||||
),
|
||||
OpenApiParameter(
|
||||
@@ -4318,6 +4323,46 @@ class StoragePathViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Storag
|
||||
return Response(result)
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
description="The UI settings of the current user, merged with the settings of the server and the current user and permissions",
|
||||
request=None,
|
||||
responses={
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="UiSettingsResponse",
|
||||
fields={
|
||||
"user": inline_serializer(
|
||||
name="UiSettingsUser",
|
||||
fields={
|
||||
"id": serializers.IntegerField(),
|
||||
"username": serializers.CharField(),
|
||||
"is_staff": serializers.BooleanField(),
|
||||
"is_superuser": serializers.BooleanField(),
|
||||
"groups": serializers.ListField(
|
||||
child=serializers.IntegerField(),
|
||||
),
|
||||
"first_name": serializers.CharField(required=False),
|
||||
"last_name": serializers.CharField(required=False),
|
||||
},
|
||||
),
|
||||
"settings": serializers.DictField(),
|
||||
"permissions": serializers.ListField(
|
||||
child=serializers.CharField(),
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
post=extend_schema(
|
||||
description="Save the UI settings of the current user",
|
||||
responses={
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="UiSettingsSaveResult",
|
||||
fields={"success": serializers.BooleanField()},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
class UiSettingsView(GenericAPIView[Any]):
|
||||
queryset = UiSettings.objects.all()
|
||||
permission_classes = (IsAuthenticated, PaperlessObjectPermissions)
|
||||
@@ -4601,6 +4646,11 @@ class RemoteVersionView(GenericAPIView[Any]):
|
||||
)
|
||||
|
||||
|
||||
VERSION_PATTERN = (
|
||||
r"^v?[0-9]+(\.[0-9]+){0,3}((a|b|rc)[0-9]+)?(\.post[0-9]+)?(\.dev[0-9]+)?$"
|
||||
)
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
description=(
|
||||
@@ -4611,13 +4661,15 @@ class RemoteVersionView(GenericAPIView[Any]):
|
||||
parameters=[
|
||||
OpenApiParameter(
|
||||
name="since",
|
||||
type=OpenApiTypes.STR,
|
||||
# A version number, anything else is answered with a 400
|
||||
type={"type": "string", "pattern": VERSION_PATTERN},
|
||||
location=OpenApiParameter.QUERY,
|
||||
required=False,
|
||||
),
|
||||
OpenApiParameter(
|
||||
name="until",
|
||||
type=OpenApiTypes.STR,
|
||||
# A version number, anything else is answered with a 400
|
||||
type={"type": "string", "pattern": VERSION_PATTERN},
|
||||
location=OpenApiParameter.QUERY,
|
||||
required=False,
|
||||
),
|
||||
@@ -5548,8 +5600,8 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
|
||||
"storage": inline_serializer(
|
||||
name="Storage",
|
||||
fields={
|
||||
"total": serializers.IntegerField(),
|
||||
"available": serializers.IntegerField(),
|
||||
"total": Int64Field(),
|
||||
"available": Int64Field(),
|
||||
},
|
||||
),
|
||||
"database": inline_serializer(
|
||||
@@ -5558,7 +5610,7 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
|
||||
"type": serializers.CharField(),
|
||||
"url": serializers.CharField(),
|
||||
"status": serializers.CharField(),
|
||||
"error": serializers.CharField(),
|
||||
"error": serializers.CharField(allow_null=True),
|
||||
"migration_status": inline_serializer(
|
||||
name="MigrationStatus",
|
||||
fields={
|
||||
@@ -5577,8 +5629,32 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
|
||||
fields={
|
||||
"redis_url": serializers.CharField(),
|
||||
"redis_status": serializers.CharField(),
|
||||
"redis_error": serializers.CharField(),
|
||||
"redis_error": serializers.CharField(allow_null=True),
|
||||
"celery_status": serializers.CharField(),
|
||||
"celery_url": serializers.CharField(allow_null=True),
|
||||
"celery_error": serializers.CharField(allow_null=True),
|
||||
"index_status": serializers.CharField(),
|
||||
"index_last_modified": serializers.DateTimeField(
|
||||
allow_null=True,
|
||||
),
|
||||
"index_error": serializers.CharField(allow_null=True),
|
||||
"classifier_status": serializers.CharField(),
|
||||
"classifier_last_trained": serializers.DateTimeField(
|
||||
allow_null=True,
|
||||
),
|
||||
"classifier_error": serializers.CharField(allow_null=True),
|
||||
"sanity_check_status": serializers.CharField(),
|
||||
"sanity_check_last_run": serializers.DateTimeField(
|
||||
allow_null=True,
|
||||
),
|
||||
"sanity_check_error": serializers.CharField(
|
||||
allow_null=True,
|
||||
),
|
||||
"llmindex_status": serializers.CharField(),
|
||||
"llmindex_last_modified": serializers.DateTimeField(
|
||||
allow_null=True,
|
||||
),
|
||||
"llmindex_error": serializers.CharField(allow_null=True),
|
||||
"summary": inline_serializer(
|
||||
name="TasksSummaryOverview",
|
||||
fields={
|
||||
@@ -5591,30 +5667,6 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
|
||||
),
|
||||
},
|
||||
),
|
||||
"index": inline_serializer(
|
||||
name="Index",
|
||||
fields={
|
||||
"status": serializers.CharField(),
|
||||
"error": serializers.CharField(),
|
||||
"last_modified": serializers.DateTimeField(),
|
||||
},
|
||||
),
|
||||
"classifier": inline_serializer(
|
||||
name="Classifier",
|
||||
fields={
|
||||
"status": serializers.CharField(),
|
||||
"error": serializers.CharField(),
|
||||
"last_trained": serializers.DateTimeField(),
|
||||
},
|
||||
),
|
||||
"sanity_check": inline_serializer(
|
||||
name="SanityCheck",
|
||||
fields={
|
||||
"status": serializers.CharField(),
|
||||
"error": serializers.CharField(),
|
||||
"last_run": serializers.DateTimeField(),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
|
||||
@@ -15,6 +15,7 @@ from django.contrib.auth.models import User
|
||||
from django.contrib.auth.password_validation import validate_password
|
||||
from django.core.files.uploadedfile import InMemoryUploadedFile
|
||||
from django.core.files.uploadedfile import UploadedFile
|
||||
from django.http import QueryDict
|
||||
from PIL import Image
|
||||
from rest_framework import serializers
|
||||
from rest_framework.authtoken.serializers import AuthTokenSerializer
|
||||
@@ -284,6 +285,9 @@ class ApplicationConfigurationSerializer(
|
||||
return value
|
||||
|
||||
def run_validation(self, data):
|
||||
# A form encoded body arrives as an immutable QueryDict
|
||||
if isinstance(data, QueryDict) and not data._mutable:
|
||||
data = data.copy()
|
||||
# Empty strings treated as None to avoid unexpected behavior
|
||||
if "user_args" in data and data["user_args"] == "":
|
||||
data["user_args"] = None
|
||||
|
||||
@@ -237,6 +237,11 @@ SPECTACULAR_SETTINGS = {
|
||||
"NoteFormatEnum": "documents.models.Note.Format",
|
||||
},
|
||||
"SCHEMA_PATH_PREFIX_INSERT": FORCE_SCRIPT_NAME or "",
|
||||
"POSTPROCESSING_HOOKS": [
|
||||
"drf_spectacular.hooks.postprocess_schema_enums",
|
||||
"documents.schema.add_common_error_responses",
|
||||
"documents.schema.make_conditional_fields_optional",
|
||||
],
|
||||
}
|
||||
|
||||
WSGI_APPLICATION = "paperless.wsgi.application"
|
||||
|
||||
+10
-3
@@ -34,6 +34,7 @@ from rest_framework.exceptions import ValidationError
|
||||
from rest_framework.fields import BooleanField
|
||||
from rest_framework.filters import OrderingFilter
|
||||
from rest_framework.generics import GenericAPIView
|
||||
from rest_framework.generics import get_object_or_404
|
||||
from rest_framework.pagination import PageNumberPagination
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
@@ -211,17 +212,23 @@ class UserViewSet(ModelViewSet[User]):
|
||||
request=None,
|
||||
responses={
|
||||
200: OpenApiTypes.BOOL,
|
||||
404: OpenApiTypes.STR,
|
||||
(404, "text/html"): OpenApiTypes.STR,
|
||||
},
|
||||
)
|
||||
@action(detail=True, methods=["post"])
|
||||
def deactivate_totp(self, request, pk=None):
|
||||
request_user = request.user
|
||||
user = User.objects.get(pk=pk)
|
||||
if not request_user.is_superuser and request_user != user:
|
||||
# Decide on permission before looking the user up, so the response does not
|
||||
# reveal whether another user's id exists
|
||||
try:
|
||||
is_self = int(pk) == request_user.pk
|
||||
except (TypeError, ValueError):
|
||||
is_self = False
|
||||
if not request_user.is_superuser and not is_self:
|
||||
return HttpResponseForbidden(
|
||||
"You do not have permission to deactivate TOTP for this user",
|
||||
)
|
||||
user = get_object_or_404(User, pk=pk)
|
||||
authenticator = Authenticator.objects.filter(
|
||||
user=user,
|
||||
type=Authenticator.Type.TOTP,
|
||||
|
||||
@@ -2,6 +2,8 @@ from django.utils.translation import gettext as _
|
||||
from rest_framework import serializers
|
||||
from rest_framework.exceptions import PermissionDenied
|
||||
|
||||
from documents.filters import INT16_MAX
|
||||
from documents.filters import INT16_MIN
|
||||
from documents.permissions import has_perms_owner_aware
|
||||
from documents.permissions import restrict_queryset_to_visible
|
||||
from documents.serialisers import CorrespondentField
|
||||
@@ -17,7 +19,12 @@ from paperless_mail.models import ProcessedMail
|
||||
|
||||
class MailAccountSerializer(OwnedObjectSerializer):
|
||||
password = ObfuscatedPasswordField()
|
||||
imap_port = serializers.IntegerField(required=True, allow_null=False)
|
||||
imap_port = serializers.IntegerField(
|
||||
required=True,
|
||||
allow_null=False,
|
||||
min_value=1,
|
||||
max_value=65535,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = MailAccount
|
||||
@@ -39,6 +46,21 @@ class MailAccountSerializer(OwnedObjectSerializer):
|
||||
"expiration",
|
||||
]
|
||||
|
||||
def validate(self, attrs):
|
||||
attrs = super().validate(attrs)
|
||||
# On an update the other half of the pair is the stored one
|
||||
security = attrs.get(
|
||||
"imap_security",
|
||||
getattr(self.instance, "imap_security", None),
|
||||
)
|
||||
port = attrs.get("imap_port", getattr(self.instance, "imap_port", None))
|
||||
if security == MailAccount.ImapSecurity.STARTTLS and port == 993:
|
||||
# Connecting would fail every time, port 993 speaks SSL from the start
|
||||
raise serializers.ValidationError(
|
||||
{"imap_port": "Port 993 requires SSL, it cannot be used with STARTTLS"},
|
||||
)
|
||||
return attrs
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
if "password" in validated_data and is_obfuscated_password(
|
||||
validated_data["password"],
|
||||
@@ -70,11 +92,16 @@ class MailRuleSerializer(OwnedObjectSerializer):
|
||||
allow_null=True,
|
||||
required=False,
|
||||
default="",
|
||||
max_length=256,
|
||||
)
|
||||
assign_correspondent = CorrespondentField(allow_null=True, required=False)
|
||||
assign_tags = TagsField(many=True, allow_null=True, required=False)
|
||||
assign_document_type = DocumentTypeField(allow_null=True, required=False)
|
||||
order = serializers.IntegerField(required=False)
|
||||
order = serializers.IntegerField(
|
||||
required=False,
|
||||
min_value=INT16_MIN,
|
||||
max_value=INT16_MAX,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = MailRule
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import datetime
|
||||
import imaplib
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
@@ -66,7 +67,7 @@ class DeleteProcessedMailPermissions(BasePermission):
|
||||
name="MailAccountTestResponse",
|
||||
fields={"success": serializers.BooleanField()},
|
||||
),
|
||||
400: OpenApiTypes.STR,
|
||||
(400, "text/html"): OpenApiTypes.STR,
|
||||
},
|
||||
),
|
||||
process=extend_schema(
|
||||
@@ -99,8 +100,11 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]):
|
||||
@action(methods=["post"], detail=False)
|
||||
def test(self, request):
|
||||
logger = logging.getLogger("paperless_mail")
|
||||
request.data["name"] = datetime.datetime.now().isoformat()
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
# request.data is read only for a form encoded body, and QueryDict.copy would
|
||||
# deep copy any uploaded file, so build a plain dict
|
||||
data = dict(request.data.items())
|
||||
data["name"] = datetime.datetime.now().isoformat()
|
||||
serializer = self.get_serializer(data=data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
existing_account = None
|
||||
account_id = request.data.get("id")
|
||||
@@ -136,7 +140,15 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]):
|
||||
serializer.validated_data["refresh_token"] = existing_account.refresh_token
|
||||
serializer.validated_data["expiration"] = existing_account.expiration
|
||||
|
||||
account = MailAccount(**serializer.validated_data)
|
||||
# The serializer also carries write only fields that are not model fields
|
||||
model_fields = {field.name for field in MailAccount._meta.concrete_fields}
|
||||
account = MailAccount(
|
||||
**{
|
||||
key: value
|
||||
for key, value in serializer.validated_data.items()
|
||||
if key in model_fields
|
||||
},
|
||||
)
|
||||
try:
|
||||
with get_mailbox(
|
||||
account.imap_server,
|
||||
@@ -162,9 +174,11 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]):
|
||||
|
||||
mailbox_login(M, account)
|
||||
return Response({"success": True})
|
||||
except MailError:
|
||||
except (MailError, OSError, imaplib.IMAP4.error, UnicodeError) as exc:
|
||||
# A refused connection, an unknown host, a timeout, a TLS failure or a bad
|
||||
# host name is exactly what this endpoint exists to report
|
||||
logger.error(
|
||||
"Mail account connectivity test failed",
|
||||
f"Mail account connectivity test failed: {type(exc).__name__}: {exc}",
|
||||
)
|
||||
return HttpResponseBadRequest("Unable to connect to server")
|
||||
|
||||
|
||||
Reference in new issue
Block a user