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

@@ -0,0 +1,22 @@
# Generated by Django 5.2.18 on 2026-10-31 18:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("accounts", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="SetupLock",
fields=[
(
"id",
models.PositiveSmallIntegerField(default=1, primary_key=True, serialize=False),
),
],
),
]
+12
View File
@@ -5,3 +5,15 @@ from django.db import models
class User(AbstractUser): class User(AbstractUser):
timezone = models.CharField(max_length=64, default="UTC") timezone = models.CharField(max_length=64, default="UTC")
created_at = models.DateTimeField(auto_now_add=True) created_at = models.DateTimeField(auto_now_add=True)
class SetupLock(models.Model):
"""Singleton row that gates first-run setup against a race between
concurrent requests. The setup view always tries to INSERT the row
with pk=1 in the same transaction as creating the first admin user:
the database's primary-key uniqueness makes exactly one of those
INSERTs win even under concurrent requests, so only one admin account
can ever be created this way, instead of the User.objects.exists()
check alone (which has a window between the check and the save)."""
id = models.PositiveSmallIntegerField(primary_key=True, default=1)
+23 -1
View File
@@ -1,7 +1,7 @@
import pytest import pytest
from django.urls import reverse from django.urls import reverse
from .models import User from .models import SetupLock, User
# SetupWizardMiddleware's cache is reset around every test by the autouse # SetupWizardMiddleware's cache is reset around every test by the autouse
# fixture in the top-level conftest.py, not just here. # fixture in the top-level conftest.py, not just here.
@@ -43,6 +43,28 @@ def test_setup_creates_admin_and_logs_in(client):
assert stream_response.status_code == 200 assert stream_response.status_code == 200
@pytest.mark.django_db
def test_setup_refuses_a_second_concurrent_submission(client):
# Simulates two requests racing the setup form: the first claims the
# SetupLock row directly (standing in for a request that's already
# past the User.objects.exists() check), so a second submission's
# INSERT must lose instead of also creating an admin account.
SetupLock.objects.create()
response = client.post(
reverse("accounts:setup"),
{
"username": "raced",
"email": "raced@example.com",
"password": "correct-horse-battery",
"password_confirm": "correct-horse-battery",
},
)
assert response.status_code == 302
assert response.url == reverse("accounts:login")
assert not User.objects.filter(username="raced").exists()
@pytest.mark.django_db @pytest.mark.django_db
def test_setup_is_unreachable_once_a_user_exists(client): def test_setup_is_unreachable_once_a_user_exists(client):
User.objects.create_user("existing", password="irrelevant") User.objects.create_user("existing", password="irrelevant")
+17 -6
View File
@@ -1,11 +1,12 @@
from django.contrib import messages from django.contrib import messages
from django.contrib.auth import login from django.contrib.auth import login
from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.decorators import user_passes_test
from django.db import IntegrityError, transaction
from django.shortcuts import redirect, render from django.shortcuts import redirect, render
from .forms import CreateUserForm, SetupForm from .forms import CreateUserForm, SetupForm
from .middleware import SetupWizardMiddleware 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) 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) form = SetupForm(request.POST or None)
if request.method == "POST" and form.is_valid(): if request.method == "POST" and form.is_valid():
user = form.save(commit=False) try:
user.set_password(form.cleaned_data["password"]) with transaction.atomic():
user.is_staff = True # Claims the one-time setup slot: the first of any
user.is_superuser = True # concurrent requests to reach this INSERT wins it, and
user.save() # 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 SetupWizardMiddleware._a_user_exists = True
login(request, user) login(request, user)
messages.success(request, "Welcome to Evection! Your admin account is ready.") messages.success(request, "Welcome to Evection! Your admin account is ready.")