Private
Public Access
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:
1 parent
56eb2bc498
commit
b52ba2be8a
4 files changed
+74
-7
No files matched your search
+23
-1
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user