django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

pre_save skips validation check and can cause DB integrity errors.

Open nemesifier opened this issue 13 years ago • 22 comments

Suppose a case in which you have two fields that must be "unique_together", and one of these two fields can be null.

Now immagine the field that can be NULL would be automatically set by the pre_save method of the create method. What happens if pre_save sets the field to a value that is already present in the database? I get a 500 internal server error caused by the integrity error which is not caught.

See the comments in this code:

def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.DATA, files=request.FILES)

        if serializer.is_valid():
            # pre save changes the value of a field which causes the integrity error because the validation check is not done again before saving.
            self.pre_save(serializer.object)
            self.object = serializer.save(force_insert=True)
            self.post_save(self.object, created=True)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED,
                            headers=headers)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I think that it would be better to set values of certain fields before the validation check is done.

I don't know if this is possible, until now I haven't found a way in the docs.

At the moment i will just overwrite the create method and supply my hacked request.DATA to the serializer, but it would be much better if there was a cleaner way to accomplish this.

And maybe a validation check after pre_save should be done again anyway :)

nemesifier avatar May 11 '13 18:05 nemesifier

Since pre_save modifies the object, I would think you would want to move pre_save above the call to is_valid, so you modify the object, and then validate it in that state.

erickyellott avatar May 19 '13 16:05 erickyellott

@yellottyellott that cannot be done unless some stuff is modified because "serializer.object" becomes available only after the is_valid() call.. I find it a bit weird indeed.

nemesifier avatar May 19 '13 21:05 nemesifier

@nemesisdesign - Any chance you could supply a failing test case as a PR?

lovelydinosaur avatar May 21 '13 14:05 lovelydinosaur

i'll see what i can do.

nemesifier avatar May 22 '13 08:05 nemesifier

what should I do? Fork the repo and create a new test suite or what?

nemesifier avatar May 22 '13 08:05 nemesifier

Fork the repo and add a new test case, probably in serializer.py. When you're happy with it submit it as a pull request.

lovelydinosaur avatar May 22 '13 08:05 lovelydinosaur

Just cross this bug myself, unsure how to work around it at the moment, any suggestions would be welcome. I hope the test cases illustrates the issue clearly.

leonsmith avatar Jun 13 '13 10:06 leonsmith

I apologize for not having been able to produce the failing test, thank you @leonsmith

nemesifier avatar Jun 25 '13 17:06 nemesifier

I think we can just run serializer.object.full_clean() after the call to pre_save(). In my ad-hoc testing that seems to have done the trick.

ipdb> serializer.object.full_clean()
*** ValidationError: {'__all__': [u'Unique together model with this Driver and Restaurant already exists.']}

At this point we can just return a 400 response based off of the ValidationError contents.

Thoughts?

jfilipe avatar Sep 06 '13 17:09 jfilipe

Perhaps we can ensure the pre save fields are also validated by the serializer. I think we exclude any fields not explicitly on the serializer, so maybe we should be doing something like .is_valid(include=['slug',]). ?

lovelydinosaur avatar Sep 06 '13 17:09 lovelydinosaur

hi all I also come across this issue, hope a fix is possible :)

flankerhqd avatar Nov 21 '13 16:11 flankerhqd

@tomchristie I didn't understand your last comment

nemesifier avatar Nov 21 '13 16:11 nemesifier

I think I was trying to explain that serializer validation on validates fields that the serializer acts on, and that it should probably also include an interface for adding validated fields, and the the generic view should any fields that the generic pre_save method acts on. TBH the model validation stuff is a bit beyond me at times.

lovelydinosaur avatar Nov 21 '13 17:11 lovelydinosaur

I'll tend to think it's the dev who should be responsible about what he does when he interacts with a model in the pre_save. I don't think we prevent all the possible cases where things could turn bad. Maybe we should simply add a notice in the documentation stating that pre_save is called after the serializer has been validated.

xordoquy avatar Apr 30 '14 18:04 xordoquy

I think there has to be a hook in there to add the fields BEFORE validation.

Right now you have serializer_mixins.py

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.DATA, files=request.FILES)
        if serializer.is_valid():
            self.pre_save(serializer.object)
            self.object = serializer.save(force_insert=True)
            self.post_save(self.object, created=True)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED,
                            headers=headers)

I think it might make the most sense to put a pre_clean within the serializer, something like:

rest_framework/serializers.py

    def full_clean(self, instance):
        try:
            self.pre_full_clean(instance)     # Add this line to allow the derived class a hook
            instance.full_clean(exclude=self.get_validation_exclusions())
        except ValidationError as err:
            self._errors = err.message_dict
            return None
        return instance

For now I'm having to override this in my serializer and accomplish essentially the same thing. Having the hook would lend itself toward documentation and at least awareness of the problem by the user of the framework.

mark0978 avatar Jun 21 '14 02:06 mark0978

# pre save changes the value of a field which causes the integrity error because the validation check is not done again before saving. hints to a different problem - that of race conditions.

If you have two requests in (almost) parallel you can end up with this sequence:

  1. Request A does a select to check integrity, finds no validation
  2. Request B does a select to check integrity, finds no validation
  3. Request A inserts and receives no error
  4. Request B inserts and gets a DB error because request A inserted already.

Generally this is a hard problem and can only be dealt with by capturing the exception from the DB and detecting that it's an integrity constraint and returning a 400 instead of a 500 (structured exceptions from a DB make this much easier. Do we get those?)

(I don't know the specifics of how django-rest-framework works so sorry if I've got this completely wrong.)

ashb avatar Jul 03 '14 16:07 ashb

can only be dealt with by capturing the exception

Or by using transations, eg ATOMIC_REQUESTS setting, right?

lovelydinosaur avatar Jul 03 '14 16:07 lovelydinosaur

I don't think it does - the two selects would still return no error. It might change when the error is raised is all.

This snippet from the docs about atomic look interesting:

from django.db import IntegrityError, transaction

@transaction.atomic
def viewfunc(request):
    create_parent()

    try:
        with transaction.atomic():
            generate_relationships()
    except IntegrityError:
        handle_exception()

    add_children()

ashb avatar Jul 03 '14 16:07 ashb

I really like the suggestion provided by @mark0978. This means that everything has still passed validation by the time pre_save is executed, but also gives a developer the chance to make tweaks to the object before validation. This is helpful for setting a required field on an object that the client may not have access to (e.g. owner).

cedub avatar Jul 08 '14 13:07 cedub

Possible this will be resolved by 3.0 - the serializer changes will also mean some modification to the default pre_save implementation.

lovelydinosaur avatar Aug 18 '14 12:08 lovelydinosaur