mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-12-04 10:14:24 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90b22246df |
No files matched your search
@@ -139,8 +139,6 @@ 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 }}
|
||||
@@ -173,7 +171,6 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
@@ -261,25 +258,3 @@ 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
|
||||
@@ -35,7 +35,7 @@ services:
|
||||
- "3143:3143" # IMAP
|
||||
restart: unless-stopped
|
||||
nginx:
|
||||
image: docker.io/nginx:1.31.9-alpine
|
||||
image: docker.io/nginx:1.31.7-alpine
|
||||
hostname: nginx
|
||||
container_name: nginx
|
||||
ports:
|
||||
|
||||
@@ -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 restrict_queryset_to_visible
|
||||
from documents.permissions import permitted_object_ids
|
||||
from documents.regex import safe_regex_search
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -55,10 +55,8 @@ def match_correspondents(document: Document, classifier: DocumentClassifier, use
|
||||
user = document.owner
|
||||
|
||||
if user is not None:
|
||||
correspondents = restrict_queryset_to_visible(
|
||||
Correspondent.objects.all(),
|
||||
user,
|
||||
"view_correspondent",
|
||||
correspondents = Correspondent.objects.filter(
|
||||
id__in=permitted_object_ids(user, Correspondent, "view_correspondent"),
|
||||
)
|
||||
else:
|
||||
correspondents = Correspondent.objects.all()
|
||||
@@ -86,10 +84,8 @@ def match_document_types(document: Document, classifier: DocumentClassifier, use
|
||||
user = document.owner
|
||||
|
||||
if user is not None:
|
||||
document_types = restrict_queryset_to_visible(
|
||||
DocumentType.objects.all(),
|
||||
user,
|
||||
"view_documenttype",
|
||||
document_types = DocumentType.objects.filter(
|
||||
id__in=permitted_object_ids(user, DocumentType, "view_documenttype"),
|
||||
)
|
||||
else:
|
||||
document_types = DocumentType.objects.all()
|
||||
@@ -116,10 +112,8 @@ def match_tags(document: Document, classifier: DocumentClassifier, user=None):
|
||||
user = document.owner
|
||||
|
||||
if user is not None:
|
||||
tags = restrict_queryset_to_visible(
|
||||
Tag.objects.all(),
|
||||
user,
|
||||
"view_tag",
|
||||
tags = Tag.objects.filter(
|
||||
id__in=permitted_object_ids(user, Tag, "view_tag"),
|
||||
)
|
||||
else:
|
||||
tags = Tag.objects.all()
|
||||
@@ -149,10 +143,8 @@ def match_storage_paths(document: Document, classifier: DocumentClassifier, user
|
||||
user = document.owner
|
||||
|
||||
if user is not None:
|
||||
storage_paths = restrict_queryset_to_visible(
|
||||
StoragePath.objects.all(),
|
||||
user,
|
||||
"view_storagepath",
|
||||
storage_paths = StoragePath.objects.filter(
|
||||
id__in=permitted_object_ids(user, StoragePath, "view_storagepath"),
|
||||
)
|
||||
else:
|
||||
storage_paths = StoragePath.objects.all()
|
||||
|
||||
@@ -435,33 +435,31 @@ def annotate_authorizing_fields(
|
||||
)
|
||||
|
||||
|
||||
def user_is_active_superuser(user: User | None) -> bool:
|
||||
def user_is_unrestricted(user: User | None) -> bool:
|
||||
"""
|
||||
True only for an active, authenticated superuser. ``None`` is not one.
|
||||
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.
|
||||
"""
|
||||
if user is None:
|
||||
return True
|
||||
return (
|
||||
user is not None
|
||||
and getattr(user, "is_authenticated", False)
|
||||
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,
|
||||
@@ -470,14 +468,38 @@ def restrict_queryset_to_visible(
|
||||
"""
|
||||
Restrict ``queryset`` to the rows ``user`` may see with ``perm``.
|
||||
|
||||
``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``.
|
||||
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.
|
||||
|
||||
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.
|
||||
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``.
|
||||
"""
|
||||
if user_is_active_superuser(user):
|
||||
return queryset
|
||||
|
||||
@@ -86,6 +86,7 @@ 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
|
||||
@@ -596,9 +597,7 @@ class TagSerializer(MatchingModelSerializer, OwnedObjectSerializer):
|
||||
.annotate(document_count=Count("documents", filter=filter_q))
|
||||
)
|
||||
user = getattr(request, "user", None) if request else self.user
|
||||
# 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")
|
||||
children = restrict_queryset_to_visible(children, user, "view_tag")
|
||||
|
||||
view = self.context.get("view")
|
||||
ordering = (
|
||||
@@ -1797,10 +1796,8 @@ class RunZoneOcrSerializer(serializers.Serializer[Any]):
|
||||
serializers.PrimaryKeyRelatedField,
|
||||
): # pragma: no cover
|
||||
return
|
||||
template_field.queryset = restrict_queryset_to_visible(
|
||||
OcrTemplate.objects.all(),
|
||||
user,
|
||||
"view_ocrtemplate",
|
||||
template_field.queryset = OcrTemplate.objects.filter(
|
||||
id__in=permitted_object_ids(user, OcrTemplate, "view_ocrtemplate"),
|
||||
).prefetch_related("zones", "zones__custom_field")
|
||||
|
||||
|
||||
@@ -3241,10 +3238,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)
|
||||
|
||||
@@ -3286,6 +3287,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)
|
||||
@@ -3337,6 +3366,22 @@ class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
|
||||
"ai_overwrite_existing",
|
||||
]
|
||||
|
||||
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)
|
||||
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)
|
||||
save_action_email_and_webhook(instance, email_data, webhook_data)
|
||||
return instance
|
||||
|
||||
def validate(self, attrs):
|
||||
if "assign_title" in attrs and attrs["assign_title"] is not None:
|
||||
if len(attrs["assign_title"]) == 0:
|
||||
@@ -3499,6 +3544,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:
|
||||
@@ -3531,8 +3580,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:
|
||||
@@ -3590,30 +3641,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)
|
||||
|
||||
@@ -85,14 +85,11 @@ DRF_DATETIME_FIELD = serializers.DateTimeField()
|
||||
|
||||
|
||||
def add_inbox_tags(sender, document: Document, logging_group=None, **kwargs) -> None:
|
||||
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",
|
||||
)
|
||||
inbox_tags = restrict_queryset_to_visible(
|
||||
Tag.objects.filter(is_inbox_tag=True),
|
||||
document.owner,
|
||||
"view_tag",
|
||||
)
|
||||
document.add_nested_tags(inbox_tags)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
import json
|
||||
|
||||
from django.http import HttpResponse
|
||||
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
|
||||
|
||||
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 send_json(client: APIClient, method: str, path: str, body: object) -> HttpResponse:
|
||||
return client.generic(
|
||||
method,
|
||||
path,
|
||||
data=json.dumps(body),
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
|
||||
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"]
|
||||
@@ -24,9 +24,7 @@ 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
|
||||
@@ -1287,34 +1285,25 @@ class TestBulkEditObjectsTagDescendantPartialPermission:
|
||||
@pytest.mark.django_db
|
||||
class TestRestrictQuerysetToVisible:
|
||||
"""restrict_queryset_to_visible() returns its queryset argument
|
||||
unchanged only for an active superuser, so the cases that may do that
|
||||
have to be kept narrow."""
|
||||
unchanged only for "no restriction at all", so the cases that may do
|
||||
that have to be kept narrow."""
|
||||
|
||||
def test_no_user_sees_only_unowned_rows(self) -> None:
|
||||
def test_no_user_means_no_restriction(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:
|
||||
- Only the unowned tag is visible, matching permitted_object_ids
|
||||
for None, never the whole queryset
|
||||
- The queryset is returned unfiltered, rather than
|
||||
permitted_object_ids(None, ...)'s narrower "unowned rows only"
|
||||
"""
|
||||
owner = UserFactory(username="vis_none_owner")
|
||||
owned = TagFactory(owner=owner)
|
||||
unowned = TagFactory(owner=None)
|
||||
tag = TagFactory(owner=owner)
|
||||
|
||||
visible_ids = set(
|
||||
restrict_queryset_to_visible(
|
||||
Tag.objects.all(),
|
||||
None,
|
||||
"view_tag",
|
||||
).values_list("pk", flat=True),
|
||||
)
|
||||
visible = restrict_queryset_to_visible(Tag.objects.all(), None, "view_tag")
|
||||
|
||||
assert unowned.pk in visible_ids
|
||||
assert owned.pk not in visible_ids
|
||||
assert tag.pk in visible.values_list("pk", flat=True)
|
||||
|
||||
def test_active_superuser_means_no_restriction(self) -> None:
|
||||
"""
|
||||
@@ -1483,89 +1472,3 @@ 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"] == []
|
||||
+7
-11
@@ -662,13 +662,11 @@ class TagViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Tag]):
|
||||
user = getattr(getattr(self, "request", None), "user", None)
|
||||
children_source = list(
|
||||
annotate_document_count_for_related_queryset(
|
||||
restrict_queryset_to_visible(
|
||||
Tag.objects.filter(
|
||||
pk__in=descendant_pks | {t.pk for t in all_tags},
|
||||
),
|
||||
user,
|
||||
"view_tag",
|
||||
).select_related("owner"),
|
||||
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"),
|
||||
through_model=self.document_count_through,
|
||||
related_object_field=self._get_document_count_source_field(),
|
||||
user=user,
|
||||
@@ -5333,10 +5331,8 @@ class BulkEditObjectsView(PassUserMixin):
|
||||
"document_types": DocumentTypeFilterSet,
|
||||
"storage_paths": StoragePathFilterSet,
|
||||
}[object_type]
|
||||
user_permitted_objects = restrict_queryset_to_visible(
|
||||
object_class.objects.all(),
|
||||
user,
|
||||
perm_codename,
|
||||
user_permitted_objects = object_class.objects.filter(
|
||||
id__in=permitted_object_ids(user, object_class, perm_codename),
|
||||
)
|
||||
objs = filterset_class(
|
||||
data=filters,
|
||||
|
||||
@@ -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 restrict_queryset_to_visible
|
||||
from documents.permissions import permitted_object_ids
|
||||
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 = restrict_queryset_to_visible(templates, owner, "view_ocrtemplate")
|
||||
templates = templates.filter(
|
||||
id__in=permitted_object_ids(owner, OcrTemplate, "view_ocrtemplate"),
|
||||
)
|
||||
if requester is not None:
|
||||
templates = restrict_queryset_to_visible(
|
||||
templates,
|
||||
requester,
|
||||
"view_ocrtemplate",
|
||||
templates = templates.filter(
|
||||
id__in=permitted_object_ids(requester, OcrTemplate, "view_ocrtemplate"),
|
||||
)
|
||||
return templates.order_by("name", "pk").prefetch_related(
|
||||
"zones",
|
||||
|
||||
@@ -11,7 +11,8 @@ from documents.models import Correspondent
|
||||
from documents.models import DocumentType
|
||||
from documents.models import StoragePath
|
||||
from documents.models import Tag
|
||||
from documents.permissions import restrict_queryset_to_visible
|
||||
from documents.permissions import permitted_object_ids
|
||||
from documents.permissions import restrict_queryset_to_owner_visible
|
||||
|
||||
MATCH_THRESHOLD = 0.8
|
||||
|
||||
@@ -33,7 +34,7 @@ def _resolve_visible_ids(
|
||||
"""
|
||||
if not ids:
|
||||
return []
|
||||
queryset = restrict_queryset_to_visible(
|
||||
queryset = restrict_queryset_to_owner_visible(
|
||||
model.objects.filter(pk__in=ids),
|
||||
user,
|
||||
perm,
|
||||
@@ -66,9 +67,11 @@ def _match_by_name(
|
||||
model: type[ModelT],
|
||||
perm: str,
|
||||
) -> list[ModelT]:
|
||||
# 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)
|
||||
# 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),
|
||||
)
|
||||
return _match_names_to_queryset(names, queryset)
|
||||
|
||||
|
||||
|
||||
@@ -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_visible
|
||||
from documents.permissions import restrict_queryset_to_owner_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_visible(
|
||||
visible_queryset = restrict_queryset_to_owner_visible(
|
||||
model.objects.filter(pk__in=weighted_ids),
|
||||
user,
|
||||
perm,
|
||||
|
||||
Reference in new issue
Block a user