From d1251aaef67a4396cbedc2026bb00ec0ef81d883 Mon Sep 17 00:00:00 2001 From: Trenton H <797416+stumpylog@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:38:51 -0800 Subject: [PATCH] Fix: return a JSON 404 for unmatched API URLs and non-numeric document ids (#14917) --- src/documents/views.py | 8 ++ src/paperless/tests/test_api_not_found.py | 95 +++++++++++++++++++++++ src/paperless/urls.py | 3 + src/paperless/views.py | 17 ++++ 4 files changed, 123 insertions(+) create mode 100644 src/paperless/tests/test_api_not_found.py diff --git a/src/documents/views.py b/src/documents/views.py index eedbdb5c8..e7a3143d2 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -1036,6 +1036,14 @@ class DocumentViewSet( # Bound the IN clauses used for search results and through-table lookups. selection_data_batch_size = 10_000 + def initial(self, request, *args, **kwargs): + super().initial(request, *args, **kwargs) + # Only ASCII digits can be a document id, reject anything else here, before + # any action calls int() on it + pk = kwargs.get("pk") + if pk is not None and not (pk.isascii() and pk.isdigit()): + raise Http404 + def _get_selection_data_for_queryset( self, queryset: QuerySet[Document], diff --git a/src/paperless/tests/test_api_not_found.py b/src/paperless/tests/test_api_not_found.py new file mode 100644 index 000000000..3a472925c --- /dev/null +++ b/src/paperless/tests/test_api_not_found.py @@ -0,0 +1,95 @@ +import pytest +from django.test import Client +from rest_framework import status +from rest_framework.test import APIClient + + +class TestUnmatchedApiPaths: + @pytest.mark.parametrize("method", ["get", "post", "put", "patch", "delete"]) + def test_unmatched_api_path_is_a_json_404( + self, + rest_api_client: APIClient, + method: str, + ) -> None: + """ + GIVEN: + - An unauthenticated client + WHEN: + - Any method is sent to an /api/ URL that no route matches + THEN: + - The response is a JSON 404, not a redirect to the login page + """ + response = getattr(rest_api_client, method)("/api/this_does_not_exist/") + + assert response.status_code == status.HTTP_404_NOT_FOUND + assert response["Content-Type"].startswith("application/json") + + def test_unmatched_api_path_is_a_json_404_when_authenticated( + self, + admin_client: APIClient, + ) -> None: + """ + GIVEN: + - An authenticated client + WHEN: + - An /api/ URL that no route matches is requested + THEN: + - The response is a JSON 404, not the frontend page + """ + response = admin_client.get("/api/this/is/nested/and/missing/") + + assert response.status_code == status.HTTP_404_NOT_FOUND + assert response["Content-Type"].startswith("application/json") + + def test_other_paths_still_reach_the_frontend_catch_all( + self, + client: Client, + ) -> None: + """ + GIVEN: + - An anonymous browser request + WHEN: + - A non-API path is requested + THEN: + - The frontend catch-all still applies, which sends the user to log in + """ + response = client.get("/documents/") + + assert response.status_code == status.HTTP_302_FOUND + assert "login" in response["Location"] + + +class TestDocumentRouteIds: + @pytest.mark.parametrize( + "action", + [ + "download", + "history", + "metadata", + "notes", + "preview", + "root", + "share_links", + "suggestions", + "thumb", + ], + ) + @pytest.mark.parametrize("pk", ["null", "true", "abc", "0.5", "%20"]) + def test_non_numeric_document_id_is_a_json_404( + self, + admin_client: APIClient, + action: str, + pk: str, + ) -> None: + """ + GIVEN: + - An authenticated client + WHEN: + - A document sub-route is requested with an id that is not a number + THEN: + - The response is a JSON 404, not a server error + """ + response = admin_client.get(f"/api/documents/{pk}/{action}/") + + assert response.status_code == status.HTTP_404_NOT_FOUND + assert response["Content-Type"].startswith("application/json") diff --git a/src/paperless/urls.py b/src/paperless/urls.py index 4b4086b08..20b3950e3 100644 --- a/src/paperless/urls.py +++ b/src/paperless/urls.py @@ -57,6 +57,7 @@ from documents.views import WorkflowTriggerViewSet from documents.views import WorkflowViewSet from documents.views import serve_logo from paperless.consumers import StatusConsumer +from paperless.views import ApiNotFoundView from paperless.views import ApplicationConfigurationViewSet from paperless.views import DisconnectSocialAccountView from paperless.views import FaviconView @@ -309,6 +310,8 @@ urlpatterns = [ RedirectView.as_view(url="schema/view/"), ), *api_router.urls, + # Must stay last, anything unmatched under /api/ is a JSON 404 + re_path(r"^.*$", ApiNotFoundView.as_view(), name="api_not_found"), ], ), ), diff --git a/src/paperless/views.py b/src/paperless/views.py index ee2c82123..27276468e 100644 --- a/src/paperless/views.py +++ b/src/paperless/views.py @@ -29,6 +29,7 @@ from rest_framework import serializers from rest_framework.authtoken.models import Token from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.decorators import action +from rest_framework.exceptions import NotFound from rest_framework.exceptions import ValidationError from rest_framework.fields import BooleanField from rest_framework.filters import OrderingFilter @@ -37,6 +38,7 @@ from rest_framework.pagination import PageNumberPagination from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.throttling import ScopedRateThrottle +from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from documents.models import PaperlessTask @@ -589,3 +591,18 @@ class SocialAccountProvidersView(GenericAPIView[Any]): ] return Response(sorted(resp, key=lambda p: p["name"])) + + +@extend_schema(exclude=True) +class ApiNotFoundView(APIView): + """ + A JSON 404 for any /api/ URL that no other route matches. Without this, those + URLs fall through to the frontend catch-all, which answers a redirect to the + login page or the single page app, never an error an API client can read. + """ + + authentication_classes = () + permission_classes = () + + def initial(self, request, *args, **kwargs): + raise NotFound