Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix: return 409, not 500, when two admin creates race on one email (CHOO-3855) (#1079)

Christian McDermott662fbb726699
diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.py
index cb799157a..0c52befe0 100644
--- a/core/switch_core/db/stores/user_store.py
+++ b/core/switch_core/db/stores/user_store.py
@@ -26,6 +26,20 @@ _MAX_ATTEMPTS = 2
_LAST_TENANT_KEY = "last_tenant_id"
+# Postgres's default name for `users.email`'s unique constraint, from the
+# migration that created the table.
+_EMAIL_CONSTRAINT = "users_email_key"
+
+
+def email_taken(err: IntegrityError) -> bool:
+ """Whether `err` is another account already holding the email, rather than
+ any other integrity failure, which is a bug to let propagate and not a
+ conflict to report."""
+ # asyncpg's own exception, which carries the constraint name, is the
+ # cause of the DBAPI adapter's.
+ cause = getattr(err.orig, "__cause__", None)
+ return getattr(cause, "constraint_name", None) == _EMAIL_CONSTRAINT
+
class OidcIdentityConflictError(Exception):
"""An unverified OIDC login's email already belongs to a different account.
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.py
index 5d29120f2..5a7a542c9 100644
--- a/core/switch_core/gateway/auth_routes.py
+++ b/core/switch_core/gateway/auth_routes.py
@@ -26,7 +26,7 @@ from switch_core.db.stores.hosted_machine_store import (
owner_stopped,
)
from switch_core.db.stores.template_store import TemplateStore
-from switch_core.db.stores.user_store import UserStore
+from switch_core.db.stores.user_store import UserStore, email_taken
from switch_core.gateway.auth import (
AuthenticatedCaller,
AuthenticatedSession,
@@ -259,7 +259,9 @@ async def signup(
try:
async with session.begin_nested():
await user_store.create(session, user)
- except IntegrityError:
+ except IntegrityError as err:
+ if not email_taken(err):
+ raise
await session.rollback()
raise HTTPException(
status_code=409, detail="Email already registered"
@@ -518,7 +520,18 @@ async def create_user(
role=req.role,
password_hash=password_hash,
)
- await user_store.create(session, user)
+ # The check above ran before bcrypt, so a concurrent request for the same
+ # address can have inserted since; the unique constraint is what decides.
+ try:
+ async with session.begin_nested():
+ await user_store.create(session, user)
+ except IntegrityError as err:
+ if not email_taken(err):
+ raise
+ await session.rollback()
+ raise HTTPException(
+ status_code=409, detail="Email already registered"
+ ) from None
await session.commit()
logger.info("Created user: %s (%s)", user.email, user.id)
diff --git a/core/tests/switch_core/gateway/test_create_user.py b/core/tests/switch_core/gateway/test_create_user.py
index 306b3c09d..2a868befd 100644
--- a/core/tests/switch_core/gateway/test_create_user.py
+++ b/core/tests/switch_core/gateway/test_create_user.py
@@ -14,6 +14,7 @@ The HTTP tests drive the real auth router against real Postgres, as
from __future__ import annotations
+import asyncio
from types import SimpleNamespace
import httpx
@@ -21,10 +22,12 @@ import pytest
from fastapi import FastAPI
from pydantic import ValidationError
from sqlalchemy import func, select
+from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.db.models import User
from switch_core.db.stores.user_store import UserStore
+from switch_core.gateway import auth_routes
from switch_core.gateway import dependencies as gw_deps
from switch_core.gateway.auth import create_jwt
from switch_core.gateway.auth_routes import router
@@ -77,6 +80,15 @@ async def _admin_client(
)
+class _NamelessUserStore(UserStore):
+ """Writes the user with no name, which `users.name` refuses: an integrity
+ failure that is not the email being taken."""
+
+ async def create(self, session: AsyncSession, user: User) -> None:
+ user.name = None # type: ignore[assignment]
+ await super().create(session, user)
+
+
async def _emails_like(
session_factory: async_sessionmaker[AsyncSession], address: str
) -> list[str]:
@@ -173,6 +185,69 @@ class TestCreateUserOverHttp:
]
+ async def test_concurrent_creates_of_one_address_are_one_user_and_a_conflict(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ # A double-click. Holding each request at bcrypt until both reach it
+ # puts both past the existence check before either inserts, so the
+ # insert, not the check, is what refuses the second.
+ both_checked = asyncio.Barrier(2)
+ hash_password = auth_routes.hash_password_off_loop
+
+ async def hash_once_both_have_checked(password: str) -> str:
+ async with asyncio.timeout(10):
+ await both_checked.wait()
+ return await hash_password(password)
+
+ monkeypatch.setattr(
+ auth_routes, "hash_password_off_loop", hash_once_both_have_checked
+ )
+ app = _app(session_factory)
+ async with await _admin_client(session_factory, app) as client:
+ responses = await asyncio.gather(
+ *(
+ client.post(
+ "/users",
+ json={
+ "name": f"Ed {n}",
+ "email": "[email protected]",
+ "password": "good-pass-1",
+ },
+ )
+ for n in range(2)
+ )
+ )
+
+ assert sorted(r.status_code for r in responses) == [200, 409], [
+ r.text for r in responses
+ ]
+ assert next(r for r in responses if r.status_code == 409).json() == {
+ "detail": "Email already registered"
+ }
+ assert await _emails_like(session_factory, "[email protected]") == [
+ ]
+
+ async def test_an_integrity_failure_other_than_the_email_is_not_a_conflict(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ app = _app(session_factory)
+ app.dependency_overrides[gw_deps.get_user_store] = _NamelessUserStore
+ async with await _admin_client(session_factory, app) as client:
+ with pytest.raises(IntegrityError, match='null value in column "name"'):
+ await client.post(
+ "/users",
+ json={
+ "name": "Flo",
+ "email": "[email protected]",
+ "password": "good-pass-1",
+ },
+ )
+
+ assert await _emails_like(session_factory, "[email protected]") == []
+
class TestCreateUserSchemaValidation:
def test_email_is_normalised(self) -> None:
diff --git a/core/tests/switch_core/gateway/test_signup.py b/core/tests/switch_core/gateway/test_signup.py
index 05f9bc815..a4315e671 100644
--- a/core/tests/switch_core/gateway/test_signup.py
+++ b/core/tests/switch_core/gateway/test_signup.py
@@ -10,6 +10,7 @@ import httpx
import pytest
from fastapi import FastAPI
from sqlalchemy import func, select, text
+from sqlalchemy.exc import IntegrityError
from switch_core.config import SwitchConfig
from switch_core.db.models import TENANT_ZERO_ID, CloudMachine, TenantMember, User
@@ -240,6 +241,26 @@ async def test_duplicate_email_is_a_conflict(signup_app):
assert len(await _machines(app)) == 1
+class _NamelessUserStore(UserStore):
+ """Writes the user with no name, which `users.name` refuses: an integrity
+ failure that is not the email being taken."""
+
+ async def create(self, session, user: User) -> None:
+ user.name = None # type: ignore[assignment]
+ await super().create(session, user)
+
+
+async def test_an_integrity_failure_other_than_the_email_is_not_a_conflict(
+ signup_app,
+):
+ app = signup_app
+ app.app.dependency_overrides[get_user_store] = _NamelessUserStore
+ with pytest.raises(IntegrityError, match='null value in column "name"'):
+ await _signup(app)
+ async with app.factory() as session:
+ assert await UserStore().get_by_email(session, "[email protected]") is None
+
+
@pytest.mark.parametrize(
"payload",
[