Compare commits

..
Author SHA1 Message Date
Raphael Michel 7961c000d7 Guard against missing OF clause in SELECT .. FOR UPDATE 2026-11-22 17:06:34 +01:00
4 changed files with 126 additions and 1 deletions

No files matched your search

+2 -1
View File
@@ -28,6 +28,7 @@ from django.db import DatabaseError, connection
from django.utils.timezone import now
from pretix.base.models import Event, Membership, Quota, Seat, Voucher
from pretix.helpers import OF_SELF
from pretix.testutils.middleware import debugflags_var
logger = logging.getLogger('pretix.base.locking')
@@ -119,7 +120,7 @@ def lock_objects(objects, *, shared_lock_objects=None, replace_exclusive_with_sh
else:
for model, instances in groupby(objects, key=lambda o: type(o)):
model.objects.select_for_update().filter(pk__in=[o.pk for o in instances])
model.objects.select_for_update(of=OF_SELF).filter(pk__in=[o.pk for o in instances])
class NoLockManager:
+2
View File
@@ -30,6 +30,8 @@ class PretixHelpersConfig(AppConfig):
from .monkeypatching import monkeypatch_all_at_ready
monkeypatch_all_at_ready()
from .database import guard_select_for_update # noqa
# Ensure reportlab does not make any calls to the internet or the local disk
from reportlab import rl_config
rl_config.trustedHosts = []
+28
View File
@@ -20,22 +20,32 @@
# <https://www.gnu.org/licenses/>.
#
import contextlib
import logging
import re
from django.conf import settings
from django.contrib.postgres.indexes import BrinIndex
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
from django.db import connection, transaction
from django.db.backends.signals import connection_created
from django.db.models import (
Aggregate, Expression, F, Field, Func, IntegerField, JSONField, Lookup,
OrderBy, Value,
)
from django.dispatch import receiver
from django.utils.functional import lazy
logger = logging.getLogger(__name__)
class DummyRollbackException(Exception):
pass
class UnsafeSQLQueryException(Exception):
pass
@contextlib.contextmanager
def rolledback_transaction():
"""
@@ -324,3 +334,21 @@ class UnixTimestamp(Func):
def as_sqlite(self, compiler, connection):
return self.as_sql(compiler, connection, template="CAST(strftime('%%%%s', datetime(%(expressions)s)) AS INT)")
REGEX = re.compile(r'FOR (NO KEY )?UPDATE(?! OF)')
def query_wrapper_select_for_update(execute, sql, params, many, context):
if REGEX.search(sql) and "JOIN" in sql:
if settings.DEBUG:
raise UnsafeSQLQueryException("Never use 'FOR UPDATE' without 'OF' if query causes any JOINs")
else:
logger.warning("SQL used 'FOR UPDATE' without 'OF' if query causes any JOINs", stack_info=True)
return execute(sql, params, many, context)
@receiver(connection_created)
def guard_select_for_update(sender, connection, **kwargs):
if query_wrapper_select_for_update not in connection.execute_wrappers:
connection.execute_wrappers.append(query_wrapper_select_for_update)
+94
View File
@@ -0,0 +1,94 @@
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-today pretix GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free Software Foundation in version 3 of the License.
#
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
# this file, see <https://pretix.eu/about/en/license>.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <https://www.gnu.org/licenses/>.
#
import pytest
from django.conf import settings
from django.test import override_settings
from django_scopes import scope, scopes_disabled
from pretix.base.models import Organizer
from pretix.base.models.orders import Order, OrderPayment
from pretix.helpers import OF_SELF, UnsafeSQLQueryException
@pytest.fixture
def pg_only():
if 'postgres' not in settings.DATABASES['default']['ENGINE']:
pytest.skip("Test only runs on PostgreSQL")
@pytest.fixture
def organizer():
return Organizer.objects.create(name="Dummy", slug="dummy")
@pytest.mark.django_db
@override_settings(DEBUG=True)
def test_fail_on_debug(pg_only, organizer):
with scope(organizer=organizer):
with pytest.raises(UnsafeSQLQueryException):
list(OrderPayment.objects.select_for_update()) # join added by django-scopes
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.select_related("event").select_for_update())
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update())
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update(no_key=True))
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update(nowait=True))
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update(skip_locked=True))
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update(nowait=True, no_key=True))
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update(skip_locked=True, no_key=True))
@pytest.mark.django_db
@override_settings(DEBUG=True)
def test_ok_with_of(pg_only, organizer):
with scope(organizer=organizer):
list(OrderPayment.objects.select_for_update(of=OF_SELF)) # join added by django-scopes
list(Order.objects.select_related("event").select_for_update(of=OF_SELF))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, no_key=True))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, nowait=True))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, skip_locked=True))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, nowait=True, no_key=True))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, skip_locked=True, no_key=True))
@pytest.mark.django_db
@override_settings(DEBUG=True)
def test_ok_without_join(pg_only, organizer):
with scope(organizer=organizer):
assert list(Order.objects.select_for_update()) == []
with scopes_disabled():
assert list(OrderPayment.objects.select_for_update()) == []
@pytest.mark.django_db
@override_settings(DEBUG=False)
def test_fail_silently_without_debug(pg_only, organizer):
with scope(organizer=organizer):
list(OrderPayment.objects.select_for_update()) # join added by django-scopes
list(Order.objects.select_related("event").select_for_update())