Collection saving: add another verification for collection UID uniqueness.

Even with the previous check, there could still be a race condition where two
collections with the same UID are created. Adding this extra check after
will prevent that from happening.
This commit is contained in:
Tom Hacohen 2020-11-01 10:40:47 +02:00
parent b097f3b8fa
commit f55ebeae7c

View File

@ -296,6 +296,7 @@ class CollectionSerializer(BetterErrorsMixin, serializers.ModelSerializer):
# FIXME: remove the None fallback once "collection-type-migration" is done # FIXME: remove the None fallback once "collection-type-migration" is done
collection_type = validated_data.pop('collectionType', None) collection_type = validated_data.pop('collectionType', None)
user = validated_data.get('owner')
main_item_data = validated_data.pop('main_item') main_item_data = validated_data.pop('main_item')
etag = main_item_data.pop('etag') etag = main_item_data.pop('etag')
revision_data = main_item_data.pop('content') revision_data = main_item_data.pop('content')
@ -303,6 +304,7 @@ class CollectionSerializer(BetterErrorsMixin, serializers.ModelSerializer):
instance = self.__class__.Meta.model(**validated_data) instance = self.__class__.Meta.model(**validated_data)
with transaction.atomic(): with transaction.atomic():
_ = self.__class__.Meta.model.objects.select_for_update().filter(owner=user)
if etag is not None: if etag is not None:
raise EtebaseValidationError('bad_etag', 'etag is not null') raise EtebaseValidationError('bad_etag', 'etag is not null')
@ -316,8 +318,6 @@ class CollectionSerializer(BetterErrorsMixin, serializers.ModelSerializer):
process_revisions_for_item(main_item, revision_data) process_revisions_for_item(main_item, revision_data)
user = validated_data.get('owner')
# FIXME: remove the if statement (and else branch) once "collection-type-migration" is done # FIXME: remove the if statement (and else branch) once "collection-type-migration" is done
if collection_type is not None: if collection_type is not None:
collection_type_obj, _ = models.CollectionType.objects.get_or_create(uid=collection_type, owner=user) collection_type_obj, _ = models.CollectionType.objects.get_or_create(uid=collection_type, owner=user)