Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion isic/core/api/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def collection_share_to_users(request, id: int):
def collection_attribution_information(request, id: int):
qs = get_visible_objects(request.user, "core.view_collection")
collection = get_object_or_404(qs.distinct(), id=id)
images = get_visible_objects(request.user, "core.view_image", collection.images.distinct())
images = get_visible_objects(request.user, "core.view_image", collection.images.all())
counts = (
Accession.objects.filter(image__in=images)
.values("copyright_license", "attribution")
Expand Down
4 changes: 2 additions & 2 deletions isic/core/api/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from isic.core.search import build_elasticsearch_query, facets, get_elasticsearch_client
from isic.core.serializers import SearchQuerySerializer, StrictSerializer

default_qs = Image.objects.select_related("accession__cohort").distinct()
default_qs = Image.objects.select_related("accession__cohort")


def _file_url(image: Image, file: FieldFile) -> str:
Expand Down Expand Up @@ -299,7 +299,7 @@ def image_set_pinned(request, id: int):
pinned = payload.validated_data["pinned"]

qs = get_visible_objects(request.user, "core.view_image", Image.objects.all())
image = get_object_or_404(qs.distinct(), id=id)
image = get_object_or_404(qs, id=id)
if pinned:
if not image.public:
return Response(
Expand Down
65 changes: 38 additions & 27 deletions isic/core/models/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from django.contrib.postgres.indexes import GinIndex, OpClass
from django.db import models
from django.db.models.constraints import CheckConstraint
from django.db.models.expressions import F
from django.db.models.expressions import Exists, F, OuterRef
from django.db.models.functions import Upper
from django.db.models.query_utils import Q
from django.urls import reverse
Expand Down Expand Up @@ -293,39 +293,50 @@ def view_full_metadata_list(
def view_full_metadata(user_obj: User, obj: Image) -> bool:
return ImagePermissions.view_full_metadata_list(user_obj).contains(obj)

@staticmethod
def visible_image_q(user_obj: User) -> Q:
"""
Return the images a non-staff user can see, as a predicate on an Image queryset.

Each branch is a column test, a join that can't multiply rows or a correlated subquery, so
filtering by it never needs distinct(). build_elasticsearch_query mirrors it.
"""
if not user_obj.is_authenticated:
return Q(public=True)

image_visibility_requirements = Q(public=True)

# the contributor ids are inlined so the query carries no user id and users with the same
# privileges share the query cache. the list doubles as the check for whether the branch
# is needed, so there is no separate exists() query here. this stays a join: the accession
# is one-to-one and its cohort many-to-one, so it can't multiply rows, and as a subquery
# postgres would hash every accession the user owns before returning the first row.
owned_contributor_ids = list(
user_obj.owned_contributors.order_by().values_list("id", flat=True)
)
if owned_contributor_ids:
image_visibility_requirements |= Q(
accession__cohort__contributor_id__in=owned_contributor_ids
)

# the only branch that puts the user id into the query, so it's only added for users with
# shares; everyone else keeps sharing the cache. nothing from the shares is inlined, so an
# exists() is the cheapest way to find out.
if user_obj.image_shares_received.exists():
image_visibility_requirements |= Exists(
ImageShare.objects.filter(image_id=OuterRef("pk"), grantee=user_obj)
)

return image_visibility_requirements

@staticmethod
def view_image_list(user_obj: User, qs: QuerySet[Image] | None = None) -> QuerySet[Image]:
qs = qs if qs is not None else Image._default_manager.all()

if user_obj.is_staff:
return qs
elif user_obj.is_authenticated:
image_visibility_requirements = Q(public=True)

if user_obj.owned_contributors.exists():
image_visibility_requirements |= Q(
# this needs list coercion because otherwise it will be a subquery that contains
# the user_id, which doesn't allow users with identical privileges to share
# the query cache.
accession__cohort__contributor_id__in=list(
user_obj.owned_contributors.order_by().values_list("id", flat=True)
)
)

if user_obj.image_shares_received.exists():
# this is the worst case scenario where we have to put the specific user into the
# query, guaranteeing that they won't share the cache with others.
# this is also the only portion that demands a left join, forcing the
# caller to wrap the query in a distinct() call.
image_visibility_requirements |= Q(shares=user_obj)

# Note: permissions here must be also modified in build_elasticsearch_query and
# LesionPermissions.view_lesion_list.
return qs.filter(
image_visibility_requirements,
)
else:
return qs.public()
return qs.filter(ImagePermissions.visible_image_q(user_obj))

@staticmethod
def view_image(user_obj: User, obj: Image) -> bool:
Expand Down
6 changes: 3 additions & 3 deletions isic/core/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,18 +309,18 @@ def build_elasticsearch_query(
query_dict["bool"].setdefault("filter", [])
query_dict["bool"]["filter"].append({"terms": {"collections": visible_collection_pks}})

# Note: permissions here must be also modified in ImagePermissions.view_image_list
# Note: permissions here must be also modified in ImagePermissions.visible_image_q
if user.is_staff:
return query_dict
elif user.is_authenticated:
# the logic below of generalizing the query parameters to avoid user-specific data
# is identical to the logic in ImagePermissions.view_image_list.
# is identical to the logic in ImagePermissions.visible_image_q.
query_dict["bool"]["should"] = [{"term": {"public": "true"}}]
# https://www.elastic.co/docs/reference/query-languages/query-dsl/query-dsl-bool-query#bool-min-should-match
query_dict["bool"]["minimum_should_match"] = 1

# the logic below of generalizing the query parameters to avoid user-specific data
# is identical to the logic in ImagePermissions.view_image_list.
# is identical to the logic in ImagePermissions.visible_image_q.
# contributor_owner_ids holds the ids of the users who own an image's contributor
if user.owned_contributors.exists():
query_dict["bool"]["should"].append({"terms": {"contributor_owner_ids": [user.pk]}})
Expand Down
15 changes: 12 additions & 3 deletions isic/core/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
from typing import TYPE_CHECKING, cast

from django.contrib.auth.models import AnonymousUser, User
from django.db.models import Exists, OuterRef
from django.shortcuts import get_object_or_404
from pyparsing.exceptions import ParseException
from rest_framework import serializers

from isic.core.dsl import SearchQueryParseError, django_parser, es_parser, parse_query
from isic.core.models import Image
from isic.core.models.collection import Collection
from isic.core.models.collection import Collection, CollectionImage
from isic.core.permissions import get_visible_objects
from isic.core.search import build_elasticsearch_query

Expand Down Expand Up @@ -112,9 +113,17 @@ def to_queryset(
Collection.objects.filter(pk__in=collections),
).values_list("pk", flat=True)
)
qs = qs.filter(collections__in=visible_collections)
if not visible_collections:
return qs.none()
qs = qs.filter(
Exists(
CollectionImage.objects.filter(
image_id=OuterRef("pk"), collection_id__in=visible_collections
)
)
)

return get_visible_objects(user, "core.view_image", qs).distinct()
return get_visible_objects(user, "core.view_image", qs)

def to_es_query(self, user: User | AnonymousUser) -> dict:
query = self.validated_data["query"]
Expand Down
16 changes: 16 additions & 0 deletions isic/core/tests/test_image_shares.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,19 @@ def test_image_shares_idempotent(staff_user, user, private_image):
share_image(image=private_image, grantor=staff_user, grantee=user)
share_image(image=private_image, grantor=staff_user, grantee=user)
assert user.has_perm("core.view_image", private_image)


@pytest.mark.django_db
def test_image_shares_do_not_multiply_images(user, image_factory, image_share_factory):
private_image = image_factory(public=False)
public_image = image_factory(public=True)
# several share rows per image: two grantors for the user, and two other grantees
image_share_factory(image=private_image, grantee=user)
image_share_factory(image=private_image, grantee=user)
image_share_factory(image=public_image)
image_share_factory(image=public_image)

# the filter is applied without distinct()
qs = get_visible_objects(user, "core.view_image", Image.objects.all())
assert sorted(qs.values_list("pk", flat=True)) == sorted([private_image.pk, public_image.pk])
assert qs.count() == 2
2 changes: 1 addition & 1 deletion isic/core/views/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def collection_detail(request, pk):
images = get_visible_objects(
request.user,
"core.view_image",
collection.images.select_related("accession").order_by("created").distinct(),
collection.images.select_related("accession").order_by("created"),
)

# prevent the paginator from doing a slow count.
Expand Down
4 changes: 2 additions & 2 deletions isic/zip_download/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def zip_download_listing(request):
@permission_classes([AllowAny])
def zip_download_metadata_file(request):
user, search = SearchQuerySerializer.from_token_representation(request.auth)
qs = search.to_queryset(user, Image.objects.select_related("accession__cohort").distinct())
qs = search.to_queryset(user, Image.objects.select_related("accession__cohort"))

_, csv_rows = image_metadata_csv(qs=qs)

Expand All @@ -193,7 +193,7 @@ def zip_download_metadata_file(request):
@permission_classes([AllowAny])
def zip_download_attribution_file(request):
user, search = SearchQuerySerializer.from_token_representation(request.auth)
qs = search.to_queryset(user, Image.objects.select_related("accession__cohort").distinct())
qs = search.to_queryset(user, Image.objects.select_related("accession__cohort"))
attributions = get_attributions(qs.values_list("accession__attribution", flat=True))
return HttpResponse("\n\n".join(attributions), content_type="text/plain")

Expand Down