mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-30 08:35:24 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
416161dd1e | ||
|
|
afa722ba95 |
No files matched your search
@@ -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)}
|
||||
|
||||
@@ -52,6 +52,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
|
||||
@@ -449,6 +451,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 = (
|
||||
@@ -1484,6 +1490,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 +1517,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}",
|
||||
)
|
||||
@@ -3293,10 +3303,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 +3352,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 +3431,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 +3460,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 +3471,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 +3527,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 +3617,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 +3653,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 +3714,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)
|
||||
|
||||
@@ -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
|
||||
@@ -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"]
|
||||
@@ -2120,8 +2120,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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -217,11 +218,17 @@ class UserViewSet(ModelViewSet[User]):
|
||||
@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
|
||||
@@ -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