From b52ba2be8a0b209985e061b38cccc76c53e764b0 Mon Sep 17 00:00:00 2001 From: Keith Smith Date: Sat, 31 Oct 2026 12:03:05 -0600 Subject: [PATCH] Make first-run setup race-safe with an atomic SetupLock claim (S4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- apps/accounts/migrations/0002_setuplock.py | 22 ++++++++++++++++++++ apps/accounts/models.py | 12 +++++++++++ apps/accounts/tests.py | 24 +++++++++++++++++++++- apps/accounts/views.py | 23 +++++++++++++++------ 4 files changed, 74 insertions(+), 7 deletions(-) create mode 100644 apps/accounts/migrations/0002_setuplock.py diff --git a/apps/accounts/migrations/0002_setuplock.py b/apps/accounts/migrations/0002_setuplock.py new file mode 100644 index 0000000..8c8d747 --- /dev/null +++ b/apps/accounts/migrations/0002_setuplock.py @@ -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), + ), + ], + ), + ] diff --git a/apps/accounts/models.py b/apps/accounts/models.py index f68d6c6..71e3078 100644 --- a/apps/accounts/models.py +++ b/apps/accounts/models.py @@ -5,3 +5,15 @@ from django.db import models class User(AbstractUser): timezone = models.CharField(max_length=64, default="UTC") 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) diff --git a/apps/accounts/tests.py b/apps/accounts/tests.py index 4d6a002..6d69103 100644 --- a/apps/accounts/tests.py +++ b/apps/accounts/tests.py @@ -1,7 +1,7 @@ import pytest 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 # 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 +@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 def test_setup_is_unreachable_once_a_user_exists(client): User.objects.create_user("existing", password="irrelevant") diff --git a/apps/accounts/views.py b/apps/accounts/views.py index 313189d..03b7a11 100644 --- a/apps/accounts/views.py +++ b/apps/accounts/views.py @@ -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.")