Warn when extra_field_kwargs includes fields explicitly declared related to #3460)
This PR adds an invariant check via a loud assert (as suggested here) to help with issue https://github.com/encode/django-rest-framework/issues/3460.
The goal is to notify people when they include fields in extra_kwargs (either directly or, more worryingly because of security, via read_only_fields). For example, I've seen this time and time again in production code:
class MySerializer(ModelSerializer):
my_sensitive_field = ...
...
class Meta:
fields = ('my_sensitive_field', ...)
read_only_fields = ('my_sensitive_field', )
I believe most people assume that my_sensitive_field is now readonly, without knowing that extra_kwargs, and, hence, read_only_fields, only apply to fields not explicitly declared.
The PR has a pretty serious oversight and bug. Please allow me some time to fix it. I will update the PR once it is corrected.
The latest commit fixes the oversight, but two tests are still failing. I'd like help debugging and fixing these, please.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
as @auvipy refrered from #3460 , I am facing the issue even the field is not explicitly declared.
e.g. I can update fields in read_only_fields, such as username, is_superuser and etc.
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = UserModel
fields = ['id', 'username', 'first_name', 'last_name', 'password',
'is_active', 'is_superuser', 'is_staff', 'date_joined',
'groups', 'user_permissions']
read_only_fields = ['username' 'is_superuser', 'is_staff', 'groups',
'user_permissions', 'date_joined']
depth = 1
extra_kwargs = {'password': {'write_only': True}}
class UserViewSet(mixins.ListModelMixin, mixins.CreateModelMixin,
mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
queryset = UserModel.objects.all()
serializer_class = UserSerializer
# permission_classes = [IsAuthenticated]
def get_queryset(self):
if self.request.user.is_staff:
return super().get_queryset()
else:
return super().get_queryset().filter(id=self.request.user.id)
def get_permissions(self):
if self.action in ['create']:
permission_classes = [IsAdminUser]
return [perm() for perm in permission_classes]
# ['list', 'retrieve', 'update', 'partial_udpate', 'destroy']
return super().get_permissions()
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
a rebase should make the CI green as the attr library related issue was fixed
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.