From ceb82861bb001d509c187ec49f4f8874547979ee Mon Sep 17 00:00:00 2001 From: stumpylog <797416+stumpylog@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:17:57 -0800 Subject: [PATCH] Chore: Give restrict_queryset_to_visible one meaning for no user Two near-identical helpers treated a missing user in opposite ways. restrict_queryset_to_visible returned everything for None while restrict_queryset_to_owner_visible and permitted_object_ids returned only unowned rows, and about a dozen call sites spelled the same restriction inline with permitted_object_ids. Which one a caller got decided whether a workflow could see another user's private objects, and it was easy to pick the wrong one. restrict_queryset_to_visible now reads None as no identity, exactly like permitted_object_ids, and an active superuser still skips the subquery. restrict_queryset_to_owner_visible is gone and its AI callers use the single helper. The inline restrictions in the matching, tag, bulk edit, zone OCR and OCR template code use it too. The callers that really do want no restriction without a user, add_inbox_tags and the child tag list, now say so explicitly, so behavior is unchanged. exclude(pk__in=...) denial checks are left as they are, since they ask a different question. --- src/documents/matching.py | 26 ++-- src/documents/permissions.py | 74 ++++-------- src/documents/serialisers.py | 11 +- src/documents/signals/handlers.py | 13 +- .../test_permission_filtering_security.py | 113 ++++++++++++++++-- src/documents/views.py | 18 +-- src/documents/zone_ocr.py | 12 +- src/paperless_ai/matching.py | 13 +- src/paperless_ai/taxonomy.py | 4 +- 9 files changed, 187 insertions(+), 97 deletions(-) diff --git a/src/documents/matching.py b/src/documents/matching.py index c2d89dede..71bf7a637 100644 --- a/src/documents/matching.py +++ b/src/documents/matching.py @@ -19,7 +19,7 @@ from documents.models import StoragePath from documents.models import Tag from documents.models import Workflow from documents.models import WorkflowTrigger -from documents.permissions import permitted_object_ids +from documents.permissions import restrict_queryset_to_visible from documents.regex import safe_regex_search if TYPE_CHECKING: @@ -55,8 +55,10 @@ def match_correspondents(document: Document, classifier: DocumentClassifier, use user = document.owner if user is not None: - correspondents = Correspondent.objects.filter( - id__in=permitted_object_ids(user, Correspondent, "view_correspondent"), + correspondents = restrict_queryset_to_visible( + Correspondent.objects.all(), + user, + "view_correspondent", ) else: correspondents = Correspondent.objects.all() @@ -84,8 +86,10 @@ def match_document_types(document: Document, classifier: DocumentClassifier, use user = document.owner if user is not None: - document_types = DocumentType.objects.filter( - id__in=permitted_object_ids(user, DocumentType, "view_documenttype"), + document_types = restrict_queryset_to_visible( + DocumentType.objects.all(), + user, + "view_documenttype", ) else: document_types = DocumentType.objects.all() @@ -112,8 +116,10 @@ def match_tags(document: Document, classifier: DocumentClassifier, user=None): user = document.owner if user is not None: - tags = Tag.objects.filter( - id__in=permitted_object_ids(user, Tag, "view_tag"), + tags = restrict_queryset_to_visible( + Tag.objects.all(), + user, + "view_tag", ) else: tags = Tag.objects.all() @@ -143,8 +149,10 @@ def match_storage_paths(document: Document, classifier: DocumentClassifier, user user = document.owner if user is not None: - storage_paths = StoragePath.objects.filter( - id__in=permitted_object_ids(user, StoragePath, "view_storagepath"), + storage_paths = restrict_queryset_to_visible( + StoragePath.objects.all(), + user, + "view_storagepath", ) else: storage_paths = StoragePath.objects.all() diff --git a/src/documents/permissions.py b/src/documents/permissions.py index bf2305505..c6fb0cd6c 100644 --- a/src/documents/permissions.py +++ b/src/documents/permissions.py @@ -435,31 +435,33 @@ def annotate_authorizing_fields( ) -def user_is_unrestricted(user: User | None) -> bool: +def user_is_active_superuser(user: User | None) -> bool: """ - True when ``user`` means "no restriction at all" (an absent user, or an - *active* superuser) without needing a database check to know it. - - ``permitted_object_ids(None, ...)`` itself means the much narrower "only - unowned rows", which is NOT the same thing as "no user filtering - requested", so callers must special-case this before ever calling it. - A deactivated superuser is deliberately NOT unrestricted here, matching - permitted_object_ids's own is_active-before-is_superuser ordering. - - Callers that can avoid a database round trip entirely when this is true - (e.g. checking a single already-loaded object's visibility rather than - filtering a queryset) should do so via this function directly, rather - than through restrict_queryset_to_visible() below. + True only for an active, authenticated superuser. ``None`` is not one. """ - if user is None: - return True return ( - getattr(user, "is_authenticated", False) + user is not None + and getattr(user, "is_authenticated", False) and getattr(user, "is_active", False) and getattr(user, "is_superuser", False) ) +def user_is_unrestricted(user: User | None) -> bool: + """ + True when ``user`` means "no restriction at all": an absent user, or an + active superuser. + + This is for callers that treat "no user" as "do not filter", such as a + system-triggered code path. It is NOT how ``permitted_object_ids`` and + ``restrict_queryset_to_visible`` read ``None``: they take it to mean "no + identity", which sees only unowned rows. A deactivated superuser is not + unrestricted, matching ``permitted_object_ids``'s is_active-before- + is_superuser ordering. + """ + return user is None or user_is_active_superuser(user) + + def restrict_queryset_to_visible( queryset: QuerySet[ModelT], user: User | None, @@ -468,38 +470,14 @@ def restrict_queryset_to_visible( """ Restrict ``queryset`` to the rows ``user`` may see with ``perm``. - Delegates the visibility check to the database as a - ``WHERE id IN (subquery)`` rather than materializing the full - permitted-id set into a Python collection first: a caller that only - needs to check a small handful of rows (a resolved-id list, a few - RAG-neighbour candidate ids) never pays for scanning or holding the - installation's entire taxonomy in memory to do it. + ``user=None`` means no identity and sees only unowned rows, exactly as in + ``permitted_object_ids``. A caller that wants "no restriction" when there + is no user has to say so itself rather than rely on ``None``. - Returns ``queryset`` unchanged for user_is_unrestricted(user); every - other case is delegated to ``permitted_object_ids`` rather than - re-deciding the ordering here. - """ - if user_is_unrestricted(user): - return queryset - return queryset.filter(pk__in=permitted_object_ids(user, queryset.model, perm)) - - -def user_is_active_superuser(user: User | None) -> bool: - """ - True only for an active, authenticated superuser. - """ - return user is not None and user_is_unrestricted(user) - - -def restrict_queryset_to_owner_visible( - queryset: QuerySet[ModelT], - user: User | None, - perm: str, -) -> QuerySet[ModelT]: - """ - Like ``restrict_queryset_to_visible``, but ``user=None`` sees only unowned - rows (``permitted_object_ids(None, ...)`` semantics) instead of every row. - See ``user_is_active_superuser``. + The check is a ``WHERE id IN (subquery)`` rather than a materialized id + set, so a caller that only checks a handful of rows never scans or holds + the installation's whole taxonomy. An active superuser skips the subquery + entirely and gets ``queryset`` back unchanged. """ if user_is_active_superuser(user): return queryset diff --git a/src/documents/serialisers.py b/src/documents/serialisers.py index 78d43b7fa..c42fda9ab 100644 --- a/src/documents/serialisers.py +++ b/src/documents/serialisers.py @@ -86,7 +86,6 @@ from documents.permissions import get_document_count_filter_for_user from documents.permissions import get_permission_grantees from documents.permissions import has_perms_owner_aware from documents.permissions import permitted_document_ids -from documents.permissions import permitted_object_ids from documents.permissions import restrict_queryset_to_visible from documents.permissions import set_permissions_for_objects from documents.regex import validate_regex_pattern @@ -597,7 +596,9 @@ class TagSerializer(MatchingModelSerializer, OwnedObjectSerializer): .annotate(document_count=Count("documents", filter=filter_q)) ) user = getattr(request, "user", None) if request else self.user - children = restrict_queryset_to_visible(children, user, "view_tag") + # No user at all (no request, no serializer user) means no restriction + if user is not None: + children = restrict_queryset_to_visible(children, user, "view_tag") view = self.context.get("view") ordering = ( @@ -1796,8 +1797,10 @@ class RunZoneOcrSerializer(serializers.Serializer[Any]): serializers.PrimaryKeyRelatedField, ): # pragma: no cover return - template_field.queryset = OcrTemplate.objects.filter( - id__in=permitted_object_ids(user, OcrTemplate, "view_ocrtemplate"), + template_field.queryset = restrict_queryset_to_visible( + OcrTemplate.objects.all(), + user, + "view_ocrtemplate", ).prefetch_related("zones", "zones__custom_field") diff --git a/src/documents/signals/handlers.py b/src/documents/signals/handlers.py index 6c537dd8e..4d4bab126 100644 --- a/src/documents/signals/handlers.py +++ b/src/documents/signals/handlers.py @@ -85,11 +85,14 @@ DRF_DATETIME_FIELD = serializers.DateTimeField() def add_inbox_tags(sender, document: Document, logging_group=None, **kwargs) -> None: - inbox_tags = restrict_queryset_to_visible( - Tag.objects.filter(is_inbox_tag=True), - document.owner, - "view_tag", - ) + inbox_tags = Tag.objects.filter(is_inbox_tag=True) + # An unowned document gets every inbox tag, not just the unowned ones + if document.owner is not None: + inbox_tags = restrict_queryset_to_visible( + inbox_tags, + document.owner, + "view_tag", + ) document.add_nested_tags(inbox_tags) diff --git a/src/documents/tests/test_permission_filtering_security.py b/src/documents/tests/test_permission_filtering_security.py index 8b1b0169a..d244b2643 100644 --- a/src/documents/tests/test_permission_filtering_security.py +++ b/src/documents/tests/test_permission_filtering_security.py @@ -24,7 +24,9 @@ from documents.permissions import has_perms_owner_aware from documents.permissions import permitted_document_ids from documents.permissions import permitted_object_ids from documents.permissions import restrict_queryset_to_visible +from documents.serialisers import TagSerializer from documents.serialisers import _get_viewable_duplicates +from documents.signals.handlers import add_inbox_tags from paperless_testing.factories import CorrespondentFactory from paperless_testing.factories import DocumentFactory from paperless_testing.factories import DocumentTypeFactory @@ -1285,25 +1287,34 @@ class TestBulkEditObjectsTagDescendantPartialPermission: @pytest.mark.django_db class TestRestrictQuerysetToVisible: """restrict_queryset_to_visible() returns its queryset argument - unchanged only for "no restriction at all", so the cases that may do - that have to be kept narrow.""" + unchanged only for an active superuser, so the cases that may do that + have to be kept narrow.""" - def test_no_user_means_no_restriction(self) -> None: + def test_no_user_sees_only_unowned_rows(self) -> None: """ GIVEN: - No user at all (a system-triggered call) + - One owned and one unowned tag WHEN: - restrict_queryset_to_visible() is called THEN: - - The queryset is returned unfiltered, rather than - permitted_object_ids(None, ...)'s narrower "unowned rows only" + - Only the unowned tag is visible, matching permitted_object_ids + for None, never the whole queryset """ owner = UserFactory(username="vis_none_owner") - tag = TagFactory(owner=owner) + owned = TagFactory(owner=owner) + unowned = TagFactory(owner=None) - visible = restrict_queryset_to_visible(Tag.objects.all(), None, "view_tag") + visible_ids = set( + restrict_queryset_to_visible( + Tag.objects.all(), + None, + "view_tag", + ).values_list("pk", flat=True), + ) - assert tag.pk in visible.values_list("pk", flat=True) + assert unowned.pk in visible_ids + assert owned.pk not in visible_ids def test_active_superuser_means_no_restriction(self) -> None: """ @@ -1472,3 +1483,89 @@ class TestGetPermissionGrantees: "change": {"users": [], "groups": []}, }, } + + +@pytest.mark.django_db +class TestAddInboxTagsVisibility: + def test_unowned_document_gets_every_inbox_tag(self) -> None: + """ + GIVEN: + - An unowned document + - An inbox tag owned by a user and an unowned inbox tag + WHEN: + - add_inbox_tags() runs for the document + THEN: + - Both inbox tags are added, since an unowned document is not + restricted to unowned tags + """ + owner = UserFactory(username="inbox_owner") + owned = TagFactory(owner=owner, is_inbox_tag=True) + unowned = TagFactory(owner=None, is_inbox_tag=True) + doc = DocumentFactory(owner=None) + + add_inbox_tags(sender=None, document=doc) + + assert set(doc.tags.values_list("pk", flat=True)) == {owned.pk, unowned.pk} + + def test_owned_document_only_gets_inbox_tags_its_owner_can_view(self) -> None: + """ + GIVEN: + - A document owned by one user + - An inbox tag owned by the same user, one owned by someone else, + and one unowned + WHEN: + - add_inbox_tags() runs for the document + THEN: + - Only the owner's tag and the unowned tag are added + """ + owner = UserFactory(username="inbox_doc_owner") + other = UserFactory(username="inbox_other") + own = TagFactory(owner=owner, is_inbox_tag=True) + hidden = TagFactory(owner=other, is_inbox_tag=True) + unowned = TagFactory(owner=None, is_inbox_tag=True) + doc = DocumentFactory(owner=owner) + + add_inbox_tags(sender=None, document=doc) + + added = set(doc.tags.values_list("pk", flat=True)) + assert added == {own.pk, unowned.pk} + assert hidden.pk not in added + + +@pytest.mark.django_db +class TestTagSerializerChildrenVisibility: + def test_no_user_and_no_request_shows_every_child(self) -> None: + """ + GIVEN: + - A tag with a child owned by another user + - A TagSerializer with neither a request nor a user + WHEN: + - The children are serialized + THEN: + - The child is listed, since no user at all means no restriction + here, unlike restrict_queryset_to_visible(None) + """ + parent = TagFactory(owner=None) + child = TagFactory(owner=UserFactory(), tn_parent=parent) + + serializer = TagSerializer(parent, context={}) + + assert {entry["id"] for entry in serializer.data["children"]} == {child.pk} + + def test_serializer_user_without_request_hides_unviewable_child(self) -> None: + """ + GIVEN: + - A tag with a child owned by another user + - A TagSerializer given a regular user but no request + WHEN: + - The children are serialized + THEN: + - The child is not listed, the user having no view permission on it + """ + parent = TagFactory(owner=None) + TagFactory(owner=UserFactory(), tn_parent=parent) + viewer = UserFactory() + + serializer = TagSerializer(parent, user=viewer, context={}) + + assert serializer.data["children"] == [] diff --git a/src/documents/views.py b/src/documents/views.py index e7a3143d2..82175c2bf 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -662,11 +662,13 @@ class TagViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Tag]): user = getattr(getattr(self, "request", None), "user", None) children_source = list( annotate_document_count_for_related_queryset( - Tag.objects.filter( - pk__in=descendant_pks | {t.pk for t in all_tags}, - ) - .filter(pk__in=permitted_object_ids(user, Tag, "view_tag")) - .select_related("owner"), + restrict_queryset_to_visible( + Tag.objects.filter( + pk__in=descendant_pks | {t.pk for t in all_tags}, + ), + user, + "view_tag", + ).select_related("owner"), through_model=self.document_count_through, related_object_field=self._get_document_count_source_field(), user=user, @@ -5331,8 +5333,10 @@ class BulkEditObjectsView(PassUserMixin): "document_types": DocumentTypeFilterSet, "storage_paths": StoragePathFilterSet, }[object_type] - user_permitted_objects = object_class.objects.filter( - id__in=permitted_object_ids(user, object_class, perm_codename), + user_permitted_objects = restrict_queryset_to_visible( + object_class.objects.all(), + user, + perm_codename, ) objs = filterset_class( data=filters, diff --git a/src/documents/zone_ocr.py b/src/documents/zone_ocr.py index c74d7df80..303b87677 100644 --- a/src/documents/zone_ocr.py +++ b/src/documents/zone_ocr.py @@ -44,7 +44,7 @@ from documents.models import OcrTemplate from documents.models import OcrTemplateZone from documents.parsers import ParseError from documents.parsers import rasterize_pdf_page_to_png -from documents.permissions import permitted_object_ids +from documents.permissions import restrict_queryset_to_visible from documents.regex import safe_regex_fullmatch from documents.validators import monetary_validator from documents.versioning import get_root_document @@ -261,12 +261,12 @@ def _visible_templates( """The enabled templates both the owner and the requester can view, if given.""" templates = OcrTemplate.objects.filter(enabled=True) if owner is not None: - templates = templates.filter( - id__in=permitted_object_ids(owner, OcrTemplate, "view_ocrtemplate"), - ) + templates = restrict_queryset_to_visible(templates, owner, "view_ocrtemplate") if requester is not None: - templates = templates.filter( - id__in=permitted_object_ids(requester, OcrTemplate, "view_ocrtemplate"), + templates = restrict_queryset_to_visible( + templates, + requester, + "view_ocrtemplate", ) return templates.order_by("name", "pk").prefetch_related( "zones", diff --git a/src/paperless_ai/matching.py b/src/paperless_ai/matching.py index a5ed40f37..9887c4eeb 100644 --- a/src/paperless_ai/matching.py +++ b/src/paperless_ai/matching.py @@ -11,8 +11,7 @@ from documents.models import Correspondent from documents.models import DocumentType from documents.models import StoragePath from documents.models import Tag -from documents.permissions import permitted_object_ids -from documents.permissions import restrict_queryset_to_owner_visible +from documents.permissions import restrict_queryset_to_visible MATCH_THRESHOLD = 0.8 @@ -34,7 +33,7 @@ def _resolve_visible_ids( """ if not ids: return [] - queryset = restrict_queryset_to_owner_visible( + queryset = restrict_queryset_to_visible( model.objects.filter(pk__in=ids), user, perm, @@ -67,11 +66,9 @@ def _match_by_name( model: type[ModelT], perm: str, ) -> list[ModelT]: - # A workflow may have no user. In that case permitted_object_ids limits - # matching to unowned objects, avoiding another user's private taxonomy. - queryset = model.objects.filter( - pk__in=permitted_object_ids(user, model, perm), - ) + # A workflow may have no user. In that case only unowned objects are visible, + # which avoids another user's private taxonomy. + queryset = restrict_queryset_to_visible(model.objects.all(), user, perm) return _match_names_to_queryset(names, queryset) diff --git a/src/paperless_ai/taxonomy.py b/src/paperless_ai/taxonomy.py index be2edfab8..4e3f39271 100644 --- a/src/paperless_ai/taxonomy.py +++ b/src/paperless_ai/taxonomy.py @@ -13,7 +13,7 @@ from documents.models import Document from documents.models import DocumentType from documents.models import StoragePath from documents.models import Tag -from documents.permissions import restrict_queryset_to_owner_visible +from documents.permissions import restrict_queryset_to_visible from paperless_ai.prompts.context import TaxonomyBlockPromptContext from paperless_ai.prompts.render import render_prompt @@ -97,7 +97,7 @@ def _visible_ranked_candidates( """ if not weighted_ids: return [] - visible_queryset = restrict_queryset_to_owner_visible( + visible_queryset = restrict_queryset_to_visible( model.objects.filter(pk__in=weighted_ids), user, perm,