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
1 change: 1 addition & 0 deletions apps/api/plane/app/serializers/notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ class UserNotificationPreferenceSerializer(BaseSerializer):
class Meta:
model = UserNotificationPreference
fields = "__all__"
read_only_fields = ["user", "workspace", "project", "created_by", "updated_by", "deleted_at"]
16 changes: 15 additions & 1 deletion apps/api/plane/app/serializers/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from rest_framework import serializers

# Module import
from plane.db.models import Account, Profile, User, Workspace, WorkspaceMemberInvite
from plane.db.models import Account, FileAsset, Profile, User, Workspace, WorkspaceMemberInvite
from plane.utils.url import contains_url

from .base import BaseSerializer
Expand All @@ -23,6 +23,20 @@ def validate_last_name(self, value):
raise serializers.ValidationError("Last name cannot contain a URL.")
return value

def _validate_own_asset(self, value, entity_type):
# Only the user's own asset of the matching entity type (or null) can be linked
if value is not None and (
self.instance is None or value.user_id != self.instance.id or value.entity_type != entity_type
):
raise serializers.ValidationError("Invalid asset.")
return value

def validate_avatar_asset(self, value):
return self._validate_own_asset(value, FileAsset.EntityTypeContext.USER_AVATAR)

def validate_cover_image_asset(self, value):
return self._validate_own_asset(value, FileAsset.EntityTypeContext.USER_COVER)

class Meta:
model = User
# Exclude password field from the serializer
Expand Down
9 changes: 5 additions & 4 deletions apps/api/plane/app/views/asset/v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@
class UserAssetsV2Endpoint(BaseAPIView):
"""This endpoint is used to upload user profile images."""

def asset_delete(self, asset_id):
asset = FileAsset.objects.filter(id=asset_id).first()
def asset_delete(self, asset_id, user_id):
# Only delete an asset owned by the user it is unlinked from
asset = FileAsset.objects.filter(id=asset_id, user_id=user_id).first()
if asset is None:
return
asset.is_deleted = True
Expand All @@ -47,7 +48,7 @@ def entity_asset_save(self, asset_id, entity_type, asset, request):
user.avatar = ""
# Delete the previous avatar
if user.avatar_asset_id:
self.asset_delete(user.avatar_asset_id)
self.asset_delete(user.avatar_asset_id, user.id)
# Save the new avatar
user.avatar_asset_id = asset_id
user.save()
Expand All @@ -65,7 +66,7 @@ def entity_asset_save(self, asset_id, entity_type, asset, request):
user.cover_image = None
# Delete the previous cover image
if user.cover_image_asset_id:
self.asset_delete(user.cover_image_asset_id)
self.asset_delete(user.cover_image_asset_id, user.id)
# Save the new cover image
user.cover_image_asset_id = asset_id
user.save()
Expand Down
5 changes: 3 additions & 2 deletions apps/api/plane/authentication/adapter/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ def delete_old_avatar(self, user):
"""Delete the old avatar if it exists"""
try:
if user.avatar_asset:
asset = FileAsset.objects.get(pk=user.avatar_asset_id)
asset = FileAsset.objects.get(pk=user.avatar_asset_id, user_id=user.id)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (test gap): none of the new tests reach this branch. Reverting just this line leaves all 6 green. Suggest one test where user.avatar_asset points at another user's asset, with S3Storage patched: call Adapter.delete_old_avatar(user) and assert that storage.delete_files was not called and the other user's asset is not soft-deleted. That proves the user_id= filter keeps the provider-login path from deleting someone else's object in storage.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 64cd1e0 (stale foreign avatar link now cleared).

storage = S3Storage(request=self.request)
storage.delete_files(object_names=[asset.asset.name])

Expand All @@ -268,7 +268,8 @@ def delete_old_avatar(self, user):
user.save()
return
except FileAsset.DoesNotExist:
pass
# Not the user's own asset: drop the link without touching the asset
user.avatar_asset = None
except Exception as e:
log_exception(e)
return
Expand Down
137 changes: 137 additions & 0 deletions apps/api/plane/tests/contract/app/test_user_owned_fk_scope_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# Copyright (c) 2023-present Plane Software, Inc. and contributors
# SPDX-License-Identifier: AGPL-3.0-only
# See the LICENSE file for details.

"""Contract tests for user-scoped foreign keys on the ``users/me`` endpoints.

A user's notification preference row stays owned by that user, and a user's
avatar/cover can only link (and replace) the user's own asset of the matching
entity type.
"""

from unittest.mock import patch

import pytest
from rest_framework import status

from plane.authentication.adapter.base import Adapter
from plane.db.models import FileAsset, User, UserNotificationPreference

USER_URL = "/api/users/me/"
NOTIFICATION_PREFERENCE_URL = "/api/users/me/notification-preferences/"


def _user_asset_url(asset_id):
return f"/api/assets/v2/user-assets/{asset_id}/"


@pytest.fixture
def other_user(db):
return User.objects.create(email="other@plane.so", username="other_user")


def _asset(user, entity_type):
return FileAsset.objects.create(
attributes={"name": "image.png", "type": "image/png", "size": 1024},
asset="image.png",
size=1024,
user=user,
entity_type=entity_type,
storage_metadata={"size": 1024},
)


@pytest.mark.contract
@pytest.mark.django_db
class TestNotificationPreferenceOwner:
def test_patch_keeps_preference_owner(self, session_client, create_user, other_user):
"""The ``user`` FK is read-only; the boolean preferences still update."""
response = session_client.patch(
NOTIFICATION_PREFERENCE_URL, {"user": str(other_user.id), "comment": False}, format="json"
)

assert response.status_code == status.HTTP_200_OK
preference = UserNotificationPreference.objects.get(user=create_user)
assert preference.comment is False
assert UserNotificationPreference.objects.filter(user=other_user).count() == 1
assert session_client.get(NOTIFICATION_PREFERENCE_URL).status_code == status.HTTP_200_OK


@pytest.mark.contract
@pytest.mark.django_db
class TestUserAssetOwner:
def test_patch_refuses_asset_of_another_user(self, session_client, create_user, other_user):
# Matching entity types, so only the owner differs
for field, entity_type in (
("avatar_asset", FileAsset.EntityTypeContext.USER_AVATAR),
("cover_image_asset", FileAsset.EntityTypeContext.USER_COVER),
):
foreign = _asset(other_user, entity_type)
response = session_client.patch(USER_URL, {field: str(foreign.id)}, format="json")
assert response.status_code == status.HTTP_400_BAD_REQUEST

create_user.refresh_from_db()
assert create_user.avatar_asset_id is None
assert create_user.cover_image_asset_id is None

def test_patch_refuses_own_asset_of_other_entity_type(self, session_client, create_user):
cover = _asset(create_user, FileAsset.EntityTypeContext.USER_COVER)

response = session_client.patch(USER_URL, {"avatar_asset": str(cover.id)}, format="json")

assert response.status_code == status.HTTP_400_BAD_REQUEST
create_user.refresh_from_db()
assert create_user.avatar_asset_id is None

def test_patch_links_and_clears_own_asset(self, session_client, create_user):
cover = _asset(create_user, FileAsset.EntityTypeContext.USER_COVER)

response = session_client.patch(USER_URL, {"cover_image_asset": str(cover.id)}, format="json")
assert response.status_code == status.HTTP_200_OK
create_user.refresh_from_db()
assert create_user.cover_image_asset_id == cover.id

response = session_client.patch(USER_URL, {"cover_image": None, "cover_image_asset": None}, format="json")
assert response.status_code == status.HTTP_200_OK
create_user.refresh_from_db()
assert create_user.cover_image_asset_id is None

def test_avatar_replacement_respects_asset_owner(self, session_client, create_user, other_user):
"""Replacing the avatar only removes a previous avatar the user owns."""
foreign = _asset(other_user, FileAsset.EntityTypeContext.USER_AVATAR)
User.objects.filter(pk=create_user.pk).update(avatar_asset=foreign)
new_avatar = _asset(create_user, FileAsset.EntityTypeContext.USER_AVATAR)

response = session_client.patch(_user_asset_url(new_avatar.id), {}, format="json")

assert response.status_code == status.HTTP_204_NO_CONTENT
create_user.refresh_from_db()
assert create_user.avatar_asset_id == new_avatar.id
foreign.refresh_from_db()
assert foreign.is_deleted is False

def test_login_avatar_sync_unlinks_asset_of_another_user(self, create_user, other_user):
"""The provider-login avatar sync drops the link but leaves another user's asset alone."""
foreign = _asset(other_user, FileAsset.EntityTypeContext.USER_AVATAR)
User.objects.filter(pk=create_user.pk).update(avatar_asset=foreign)
create_user.refresh_from_db()

with patch("plane.authentication.adapter.base.S3Storage") as storage:
Adapter(request=None, provider="github").delete_old_avatar(create_user)

storage.return_value.delete_files.assert_not_called()
assert create_user.avatar_asset_id is None
foreign.refresh_from_db()
assert foreign.is_deleted is False

def test_avatar_upload_deletes_own_previous_avatar(self, session_client, create_user):
previous = _asset(create_user, FileAsset.EntityTypeContext.USER_AVATAR)
User.objects.filter(pk=create_user.pk).update(avatar_asset=previous)
new_avatar = _asset(create_user, FileAsset.EntityTypeContext.USER_AVATAR)

response = session_client.patch(_user_asset_url(new_avatar.id), {}, format="json")

assert response.status_code == status.HTTP_204_NO_CONTENT
create_user.refresh_from_db()
assert create_user.avatar_asset_id == new_avatar.id
assert FileAsset.all_objects.get(pk=previous.pk).is_deleted is True
Loading