diff --git a/tasks/permissions.py b/tasks/permissions.py new file mode 100644 index 0000000..ccbce29 --- /dev/null +++ b/tasks/permissions.py @@ -0,0 +1,28 @@ +""" +Custom permissions for task-related views. +""" + +from rest_framework import permissions + + +class IsOwnerOrReadOnlyIfShared(permissions.BasePermission): + """ + Permission that allows: + - Owners: full access (read, update, delete) + - Shared users: read-only access + + SECURITY: Prevents users with shared access from modifying tasks/tags they don't own. + """ + + def has_object_permission(self, request, view, obj): + # Read permissions are allowed for shared tasks/tags + if request.method in permissions.SAFE_METHODS: + # Allow if user owns the object OR if it's shared with them + return ( + obj.user == request.user or + hasattr(obj, 'shares') and obj.shares.filter(shared_with=request.user).exists() or + hasattr(obj, 'task') and obj.task.shares.filter(shared_with=request.user).exists() + ) + + # Write permissions (PUT, PATCH, DELETE) only for owners + return obj.user == request.user diff --git a/tasks/serializers.py b/tasks/serializers.py index d123a2c..8710bd8 100644 --- a/tasks/serializers.py +++ b/tasks/serializers.py @@ -197,6 +197,16 @@ class TaskShareSerializer(serializers.ModelSerializer): raise serializers.ValidationError("Must share either a task or a tag.") if attrs.get('task') and attrs.get('tag'): raise serializers.ValidationError("Cannot share both a task and a tag.") + + # SECURITY: Verify that the task/tag belongs to the requesting user + user = self.context['request'].user + if attrs.get('task'): + if attrs['task'].user != user: + raise serializers.ValidationError("You can only share your own tasks.") + if attrs.get('tag'): + if attrs['tag'].user != user: + raise serializers.ValidationError("You can only share your own tags.") + return attrs def create(self, validated_data): diff --git a/tasks/views.py b/tasks/views.py index c752220..4aa3cfd 100644 --- a/tasks/views.py +++ b/tasks/views.py @@ -22,6 +22,7 @@ from .serializers import ( TimeEntrySerializer, TaskShareSerializer, ) +from .permissions import IsOwnerOrReadOnlyIfShared logger = logging.getLogger(__name__) @@ -66,7 +67,7 @@ class TaskDetailAPIView(generics.RetrieveUpdateDestroyAPIView): """API endpoint for task details.""" serializer_class = TaskSerializer - permission_classes = [permissions.IsAuthenticated] + permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnlyIfShared] def get_queryset(self): user = self.request.user @@ -94,7 +95,7 @@ class TagDetailAPIView(generics.RetrieveUpdateDestroyAPIView): """API endpoint for tag details.""" serializer_class = TagSerializer - permission_classes = [permissions.IsAuthenticated] + permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnlyIfShared] def get_queryset(self): user = self.request.user