1. Risk summary
Access control is correct. Every read, cancel and export goes through get_queryset(), which filters on customer=request.user, and customer and status cannot be set by the client, so I found no way for one customer to see another's name, phone or booking. The most serious problem is that perform_create accepts any time range with no overlap check. Any logged-in user, and since signup is open that means anyone, can book a sauna slot another customer already holds, or claim every slot. The other findings are weaker input validation issues.
2. Findings
| # | Severity | Location | Vulnerability | Who can exploit it |
|---|
| 1 | High | perform_create, BookingSerializer | No overlap check, so a slot another customer holds can be double-booked (CWE-840, CWE-362) | Any logged-in user |
| 2 | Medium | perform_create, no throttle | No limit on how many bookings one account can hold, so one user can reserve all 4 saunas for months (CWE-770) | Any logged-in user |
| 3 | Low | BookingSerializer (starts_at, ends_at, guests) | Times and guest count are not validated: end before start, bookings in the past, multi-day bookings, 0 or 10000 guests (CWE-20) | Any logged-in user |
| 4 | Low | export, writer.writerow([... b.note]) | CSV formula injection through note (CWE-1236) | Any logged-in user, against themselves or whoever opens their CSV |
| 5 | Low, Needs check | BookingSerializer.sauna | Writable foreign key accepts any Sauna pk, including inactive or retired saunas (CWE-20) | Any logged-in user |
| 6 | Low, Needs check | BookingSerializer.note | Size of note depends on the model. Stored XSS is possible if a frontend or custom admin template renders it unescaped (CWE-79, CWE-400) | Any logged-in user, aimed at staff or the frontend |
3. Details and fixes
1. Double-booking. A user sends POST /api/bookings/ with sauna, starts_at and ends_at matching another customer's confirmed booking, and gets a second confirmed booking for the same sauna and hour. A check in Python alone can still race, because two parallel POSTs both pass the check. Enforce it in PostgreSQL with an exclusion constraint and keep the serializer check only for a friendly error message. The constraint needs the btree_gist extension.
# bookings/models.py
from django.contrib.postgres.constraints import ExclusionConstraint
from django.contrib.postgres.fields import DateTimeRangeField, RangeBoundary, RangeOperators
from django.db.models import Func, Q
class TsTzRange(Func):
function = "TSTZRANGE"
output_field = DateTimeRangeField()
class Booking(models.Model):
...
class Meta:
constraints = [
ExclusionConstraint(
name="no_overlapping_confirmed_bookings",
expressions=[
(TsTzRange("starts_at", "ends_at", RangeBoundary()), RangeOperators.OVERLAPS),
("sauna", RangeOperators.EQUAL),
],
condition=Q(status="confirmed"),
),
]
# in the migration, before the AddConstraint operation:
from django.contrib.postgres.operations import BtreeGistExtension
operations = [BtreeGistExtension(), ...]
# bookings/views.py
from django.db import IntegrityError, transaction
def perform_create(self, serializer):
try:
with transaction.atomic():
serializer.save(customer=self.request.user, status="confirmed")
except IntegrityError:
raise serializers.ValidationError({"detail": "This sauna is already booked for that time."})
2. Inventory exhaustion. Even after fix 1, one account can script POSTs that take every free hour of every sauna. Registration is open, so the attacker can also spread this across several accounts. Cap active bookings per user and throttle creation.
# serializer
MAX_ACTIVE_BOOKINGS = 5
def validate(self, data):
user = self.context["request"].user
active = Booking.objects.filter(customer=user, status="confirmed", ends_at__gt=timezone.now()).count()
if active >= MAX_ACTIVE_BOOKINGS:
raise serializers.ValidationError("You have too many upcoming bookings.")
return data
# viewset
from rest_framework.throttling import UserRateThrottle
class BookingCreateThrottle(UserRateThrottle):
scope = "booking_create"
def get_throttles(self):
if self.action == "create":
return [BookingCreateThrottle()]
return super().get_throttles()
# settings.py
REST_FRAMEWORK["DEFAULT_THROTTLE_RATES"] = {"booking_create": "20/hour"}
3. Unvalidated times and guests. A user can post ends_at earlier than starts_at, a booking that ends in 2030, or guests: -5. Past bookings also can never be cancelled, because of the check in destroy. This assumes Sauna has a capacity field; if it doesn't, use a fixed maximum.
from datetime import timedelta
guests = serializers.IntegerField(min_value=1)
def validate(self, data):
# merge with the check from finding 2
now = timezone.now()
s, e = data["starts_at"], data["ends_at"]
if e <= s:
raise serializers.ValidationError("End must be after start.")
if s < now:
raise serializers.ValidationError("Cannot book in the past.")
if e - s > timedelta(hours=4):
raise serializers.ValidationError("Maximum booking length is 4 hours.")
if s > now + timedelta(days=180):
raise serializers.ValidationError("Too far in advance.")
if data["guests"] > data["sauna"].capacity:
raise serializers.ValidationError("Too many guests for this sauna.")
return data
4. CSV formula injection. If note is =HYPERLINK("http://evil.example","click") or starts with +, - or @, Excel or LibreOffice treat it as a formula when the export is opened. The impact is mostly on the user themselves. It matters more if staff ever reuse this export pattern for all bookings. Neutralize leading formula characters.
def csv_safe(value):
s = "" if value is None else str(value)
return "'" + s if s[:1] in ("=", "+", "-", "@", "\t", "\r") else s
writer.writerow([csv_safe(b.sauna.name), b.starts_at.isoformat(), b.ends_at.isoformat(),
b.guests, csv_safe(b.note)])
5. Any sauna pk accepted. ModelSerializer builds sauna as PrimaryKeyRelatedField(queryset=Sauna.objects.all()), so a user can POST the pk of a sauna you have taken offline. Check whether Sauna has an active or retired flag. This assumes it is called is_active.
sauna = serializers.PrimaryKeyRelatedField(queryset=Sauna.objects.filter(is_active=True))
6. note size and rendering. Check whether Booking.note is a TextField. If so, a user can store megabytes per booking. Also check whether any frontend inserts it with innerHTML or v-html, or whether an admin template uses |safe. The default Django admin escapes it. Bound the field in the API.
note = serializers.CharField(max_length=500, required=False, allow_blank=True)
4. Hardening
- Set
DEFAULT_PAGINATION_CLASS and PAGE_SIZE so GET /api/bookings/ cannot return an unbounded list, and use .select_related("sauna") in get_queryset() to avoid one query per row in export. - Throttle the signup and login endpoints, which are not in this file, and consider email verification. Per-user limits are only as strong as the cost of creating a new account.
- DRF throttles use Django's cache, and the default per-process LocMem cache doesn't work across gunicorn workers. Use Redis or the database cache, and add
limit_req in nginx as a backstop. - Add regression tests where user B gets 404 on
GET and DELETE /api/bookings/<A's id>/, and B's export contains none of A's rows. This locks in the access control that is currently correct. - Keep an audit trail of who created or cancelled each booking and when, for example with
django-simple-history or a log line in perform_create and destroy, so staff can resolve disputes. Leave out names and phones.