From f895fd369ede1132344d22d83f1210e23ce52889 Mon Sep 17 00:00:00 2001 From: Trenton H <797416+stumpylog@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:23:06 -0800 Subject: [PATCH] Fix: validate the archive serial number against the range of the database column as well as the fixed range --- src/documents/consumer.py | 8 +- src/documents/models.py | 9 ++ src/documents/serialisers.py | 6 ++ .../test_api_archive_serial_number_range.py | 97 +++++++++++++++++++ 4 files changed, 116 insertions(+), 4 deletions(-) create mode 100644 src/documents/tests/test_api_archive_serial_number_range.py diff --git a/src/documents/consumer.py b/src/documents/consumer.py index 4ffe07784..ba2ae1922 100644 --- a/src/documents/consumer.py +++ b/src/documents/consumer.py @@ -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}: " diff --git a/src/documents/models.py b/src/documents/models.py index 9319f835b..4addbc61a 100644 --- a/src/documents/models.py +++ b/src/documents/models.py @@ -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 diff --git a/src/documents/serialisers.py b/src/documents/serialisers.py index e4bfbee9e..9d6203e0d 100644 --- a/src/documents/serialisers.py +++ b/src/documents/serialisers.py @@ -1152,6 +1152,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 @@ -2407,6 +2412,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 diff --git a/src/documents/tests/test_api_archive_serial_number_range.py b/src/documents/tests/test_api_archive_serial_number_range.py new file mode 100644 index 000000000..86de04f4f --- /dev/null +++ b/src/documents/tests/test_api_archive_serial_number_range.py @@ -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