Compare commits

..
Author SHA1 Message Date
stumpylog 8f18ede028 Chore: Sign the image manifests and include SBOm via buildx 2026-12-01 11:07:22 -08:00
stumpylog ceb82861bb 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.
2026-12-01 09:26:37 -08:00
dependabot[bot] 3c295be9b4 docker-compose(deps): Bump nginx in /docker/compose (#14928)
Bumps nginx from 1.31.7-alpine to 1.31.9-alpine.

---
updated-dependencies:
- dependency-name: nginx
  dependency-version: 1.31.9-alpine
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-01 07:54:03 -08:00
12 changed files with 218 additions and 192 deletions

No files matched your search

+25
View File
@@ -139,6 +139,8 @@ jobs:
file: ./Dockerfile
platforms: ${{ matrix.platform }}
labels: ${{ steps.docker-meta.outputs.labels }}
sbom: true
provenance: mode=max
build-args: |
PNGX_TAG_VERSION=${{ steps.docker-meta.outputs.version }}
outputs: type=image,name=${{ env.REGISTRY }}/${{ steps.repo.outputs.name }},push-by-digest=true,name-canonical=true,push=${{ steps.check-push.outputs.should-push }}
@@ -171,6 +173,7 @@ jobs:
permissions:
contents: read
packages: write
id-token: write
steps:
- name: Download digests
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
@@ -258,3 +261,25 @@ jobs:
echo "Copying ${tag} to ${quay_tag}"
skopeo copy --all "docker://${tag}" "docker://${quay_tag}"
done
- name: Install cosign
uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4
- name: Sign images (keyless)
env:
FIRST_TAG: ${{ fromJSON(steps.docker-meta.outputs.json).tags[0] }}
GHCR_REPO: ${{ env.REGISTRY }}/${{ needs.build-arch.outputs.repository }}
PUSH_EXTERNAL: ${{ needs.build-arch.outputs.push-external }}
run: |
digest=$(docker buildx imagetools inspect "${FIRST_TAG}" --format '{{json .Manifest}}' | jq -r '.digest')
echo "Signing manifest list ${digest}"
repos=("${GHCR_REPO}")
if [ "${PUSH_EXTERNAL}" == "true" ]; then
repos+=("docker.io/paperlessngx/paperless-ngx" "quay.io/paperlessngx/paperless-ngx")
fi
for repo in "${repos[@]}"; do
echo "Verifying digest in ${repo}"
docker buildx imagetools inspect "${repo}@${digest}" > /dev/null
echo "Signing ${repo}@${digest}"
cosign sign --yes "${repo}@${digest}"
done
+1 -1
View File
@@ -35,7 +35,7 @@ services:
- "3143:3143" # IMAP
restart: unless-stopped
nginx:
image: docker.io/nginx:1.31.7-alpine
image: docker.io/nginx:1.31.9-alpine
hostname: nginx
container_name: nginx
ports:
+17 -9
View File
@@ -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()
+26 -48
View File
@@ -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
+12 -16
View File
@@ -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 = (
@@ -1330,11 +1331,6 @@ class SavedViewFilterRuleSerializer(serializers.ModelSerializer[SavedViewFilterR
class SavedViewSerializer(OwnedObjectSerializer):
filter_rules = SavedViewFilterRuleSerializer(many=True)
display_fields = serializers.ListField(
child=serializers.CharField(),
required=False,
allow_null=True,
)
class Meta:
model = SavedView
@@ -1476,13 +1472,11 @@ class SavedViewSerializer(OwnedObjectSerializer):
attrs = super().validate(attrs)
if "display_fields" in attrs and attrs["display_fields"] is not None:
for field in attrs["display_fields"]:
# i.e. 'custom_field_' followed by the id of a custom field
custom_field = re.fullmatch(
rf"{re.escape(SavedView.DisplayFields.CUSTOM_FIELD[:-2])}(\d+)",
field,
)
if custom_field:
if not CustomField.objects.filter(id=custom_field[1]).exists():
if (
SavedView.DisplayFields.CUSTOM_FIELD[:-2] in field
): # i.e. check for 'custom_field_' prefix
field_id = int(re.search(r"\d+", field)[0])
if not CustomField.objects.filter(id=field_id).exists():
raise serializers.ValidationError(
f"Invalid field: {field}",
)
@@ -1803,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")
+8 -5
View File
@@ -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)
@@ -1,82 +0,0 @@
import pytest
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import CustomField
from documents.models import SavedView
class TestSavedViewDisplayFields:
@pytest.mark.parametrize(
"value",
[
pytest.param(["custom_field_abc"], id="no-id"),
pytest.param(["custom_field_"], id="empty-id"),
pytest.param(["xcustom_field_{id}"], id="prefixed"),
pytest.param(["custom_field_{id}x"], id="suffixed"),
pytest.param([1], id="not-a-string"),
],
)
def test_malformed_display_fields_are_a_400(
self,
admin_client: APIClient,
admin_user: User,
value: object,
) -> None:
"""
GIVEN:
- A saved view and a custom field
WHEN:
- Its display fields are patched to something that names no field
THEN:
- The response is a 400 and the stored display fields are unchanged
"""
custom_field = CustomField.objects.create(
name="cf",
data_type=CustomField.FieldDataType.STRING,
)
view = SavedView.objects.create(
name="view",
owner=admin_user,
sort_field="created",
display_fields=["title"],
)
if isinstance(value, list):
value = [
item.format(id=custom_field.pk) if isinstance(item, str) else item
for item in value
]
response = admin_client.patch(
f"/api/saved_views/{view.pk}/",
{"display_fields": value},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
view.refresh_from_db()
assert view.display_fields == ["title"]
def test_a_custom_field_display_name_is_accepted(
self,
admin_client: APIClient,
admin_user: User,
) -> None:
custom_field = CustomField.objects.create(
name="cf",
data_type=CustomField.FieldDataType.STRING,
)
view = SavedView.objects.create(
name="view",
owner=admin_user,
sort_field="created",
)
response = admin_client.patch(
f"/api/saved_views/{view.pk}/",
{"display_fields": ["title", f"custom_field_{custom_field.pk}"]},
format="json",
)
assert response.status_code == status.HTTP_200_OK
@@ -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"] == []
+11 -7
View File
@@ -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,
+6 -6
View File
@@ -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",
+5 -8
View File
@@ -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)
+2 -2
View File
@@ -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,