diff --git a/src/documents/filters.py b/src/documents/filters.py index 5ba9c9b49..01ddfa3cd 100644 --- a/src/documents/filters.py +++ b/src/documents/filters.py @@ -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)} diff --git a/src/documents/serialisers.py b/src/documents/serialisers.py index c677417b9..4a56d2fa9 100644 --- a/src/documents/serialisers.py +++ b/src/documents/serialisers.py @@ -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 = ( @@ -3290,10 +3296,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) @@ -3335,6 +3345,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) @@ -3386,40 +3424,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): @@ -3502,7 +3520,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) @@ -3588,6 +3610,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: @@ -3620,8 +3646,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: @@ -3679,30 +3707,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) diff --git a/src/documents/tests/test_api_integer_bounds_and_unique_names.py b/src/documents/tests/test_api_integer_bounds_and_unique_names.py new file mode 100644 index 000000000..18a2f0b46 --- /dev/null +++ b/src/documents/tests/test_api_integer_bounds_and_unique_names.py @@ -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 diff --git a/src/documents/tests/test_api_workflow_row_ownership.py b/src/documents/tests/test_api_workflow_row_ownership.py new file mode 100644 index 000000000..40edc9e22 --- /dev/null +++ b/src/documents/tests/test_api_workflow_row_ownership.py @@ -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"] diff --git a/src/paperless_mail/serialisers.py b/src/paperless_mail/serialisers.py index 7c2a7030f..d1dd66389 100644 --- a/src/paperless_mail/serialisers.py +++ b/src/paperless_mail/serialisers.py @@ -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 @@ -70,11 +77,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