Make first-run setup race-safe with an atomic SetupLock claim (S4)

The setup view's User.objects.exists() check and the admin account's
save() weren't in the same transaction, so two concurrent requests
during first deployment could both pass the check and both create an
admin account. SetupLock is a singleton row (pk=1); claiming it and
creating the admin now happen in one atomic block, so only the first
of any racing requests can succeed — the rest hit IntegrityError and
are sent to the login page instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
ksmithandClaude Sonnet 5 committed 2026-10-31 12:03:05 -06:00
1 parent 56eb2bc498
commit b52ba2be8a
4 files changed
+74 -7

No files matched your search

+17 -6
View File
@@ -1,11 +1,12 @@
from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.decorators import user_passes_test
from django.db import IntegrityError, transaction
from django.shortcuts import redirect, render
from .forms import CreateUserForm, SetupForm
from .middleware import SetupWizardMiddleware
from .models import User
from .models import SetupLock, User
is_admin = user_passes_test(lambda u: u.is_authenticated and u.is_staff)
@@ -16,11 +17,21 @@ def setup(request):
form = SetupForm(request.POST or None)
if request.method == "POST" and form.is_valid():
user = form.save(commit=False)
user.set_password(form.cleaned_data["password"])
user.is_staff = True
user.is_superuser = True
user.save()
try:
with transaction.atomic():
# Claims the one-time setup slot: the first of any
# concurrent requests to reach this INSERT wins it, and
# every other one raises IntegrityError instead of also
# creating an admin account. See SetupLock's docstring.
SetupLock.objects.create()
user = form.save(commit=False)
user.set_password(form.cleaned_data["password"])
user.is_staff = True
user.is_superuser = True
user.save()
except IntegrityError:
messages.info(request, "Setup was already completed. Log in with that account.")
return redirect("accounts:login")
SetupWizardMiddleware._a_user_exists = True
login(request, user)
messages.success(request, "Welcome to Evection! Your admin account is ready.")