diff --git a/backend/app/gateway/auth/repositories/base.py b/backend/app/gateway/auth/repositories/base.py index 29f712103f..8259b0b314 100644 --- a/backend/app/gateway/auth/repositories/base.py +++ b/backend/app/gateway/auth/repositories/base.py @@ -144,6 +144,9 @@ class UserRepository(ABC): UserNotFoundError: If no row exists for ``user.id``. This is a hard failure (not a no-op) so callers cannot mistake a concurrent-delete race for a successful update. + ValueError: If the new email is already registered to another + user, including one that committed after the caller's + pre-check. Nothing is written. """ raise NotImplementedError diff --git a/backend/app/gateway/auth/repositories/sqlite.py b/backend/app/gateway/auth/repositories/sqlite.py index 1551adf65c..0348b5901a 100644 --- a/backend/app/gateway/auth/repositories/sqlite.py +++ b/backend/app/gateway/auth/repositories/sqlite.py @@ -406,7 +406,16 @@ class SQLiteUserRepository(UserRepository): row.oauth_id = user.oauth_id row.needs_setup = user.needs_setup row.token_version = user.token_version - await session.commit() + try: + await session.commit() + except IntegrityError as exc: + # The caller's email pre-check cannot see an insert or update + # of the same address that commits before this one. Report the + # lost race the way create_user does; any other violation + # propagates unchanged. + if _is_email_violation(exc): + raise ValueError(f"Email already registered: {user.email}") from exc + raise return user async def count_users(self) -> int: diff --git a/backend/app/gateway/routers/auth.py b/backend/app/gateway/routers/auth.py index 2e099ab5fd..f1bcb9e245 100644 --- a/backend/app/gateway/routers/auth.py +++ b/backend/app/gateway/routers/auth.py @@ -579,7 +579,12 @@ async def change_password(request: Request, response: Response, body: ChangePass if user.needs_setup and body.new_email is not None: user.needs_setup = False - await provider.update_user(user) + try: + await provider.update_user(user) + except ValueError: + # The address was registered between the pre-check above and this + # write; the repository rejected it and wrote nothing. + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=AuthErrorResponse(code=AuthErrorCode.EMAIL_ALREADY_EXISTS, message="Email already in use").model_dump()) # Re-issue cookie with new token_version token = create_access_token(str(user.id), token_version=user.token_version) diff --git a/backend/docs/API.md b/backend/docs/API.md index 515f66f12f..bb9dec403a 100644 --- a/backend/docs/API.md +++ b/backend/docs/API.md @@ -1986,7 +1986,7 @@ DeerFlow enforces authentication for all non-public HTTP routes. Public routes a The authenticated auth endpoints are: - `GET /api/v1/auth/me` returns the current user. -- `POST /api/v1/auth/change-password` changes password, optionally changes email during setup, increments `token_version`, and reissues the cookie. +- `POST /api/v1/auth/change-password` changes password, optionally changes email during setup, increments `token_version`, and reissues the cookie. A `new_email` that another account already uses returns `400` `email_already_exists`, including an address registered while the request runs, and changes nothing. Protected state-changing requests also require the CSRF double-submit token: send the `csrf_token` cookie value as the `X-CSRF-Token` header. Login/register/initialize/logout are bootstrap auth endpoints: they are exempt from the double-submit token but still reject hostile browser `Origin` headers. diff --git a/backend/docs/AUTH_DESIGN.md b/backend/docs/AUTH_DESIGN.md index 4fc6991cd8..8968a86ffc 100644 --- a/backend/docs/AUTH_DESIGN.md +++ b/backend/docs/AUTH_DESIGN.md @@ -127,6 +127,7 @@ enum UserScope: - `token_version += 1`,使旧 JWT 立即失效。 - 重新签发 cookie。 - 如果 `needs_setup=true` 且传了 `new_email`,则更新邮箱并清除 `needs_setup`。 +- `new_email` 已被其他账号使用时返回 `400` `email_already_exists`,不做任何修改;请求进行期间被并发注册的邮箱同样如此。 `python -m app.gateway.auth.reset_admin` 会: diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py index 2f693551c7..832cdbebf5 100644 --- a/backend/tests/test_auth.py +++ b/backend/tests/test_auth.py @@ -897,6 +897,69 @@ def test_update_user_normalizes_email(tmp_path): asyncio.run(_run()) +def test_update_user_to_a_registered_email_raises_value_error(tmp_path): + """An email change that collides at commit reports the conflict like create_user. + + The caller's pre-check cannot see an address registered after it ran, so + the unique index is what catches the collision. The update must then + raise the documented ``ValueError`` and leave the row as it was. + """ + import asyncio + + from app.gateway.auth.repositories.sqlite import SQLiteUserRepository + + async def _run() -> None: + from deerflow.persistence.engine import close_engine, get_session_factory, init_engine + + url = f"sqlite+aiosqlite:///{tmp_path}/scratch.db" + await init_engine("sqlite", url=url, sqlite_dir=str(tmp_path)) + try: + repo = SQLiteUserRepository(get_session_factory()) + await repo.create_user(User(email="alice@x.com", password_hash="h", system_role="user")) + bob = await repo.create_user(User(email="bob@x.com", password_hash="bob-hash", system_role="user")) + bob.email = "Alice@X.com" + bob.password_hash = "new-hash" + bob.token_version += 1 + + with pytest.raises(ValueError, match="Email already registered: alice@x.com"): + await repo.update_user(bob) + + stored = await repo.get_user_by_id(str(bob.id)) + assert stored is not None + assert (stored.email, stored.password_hash, stored.token_version) == ("bob@x.com", "bob-hash", 0) + finally: + await close_engine() + + asyncio.run(_run()) + + +def test_update_user_non_email_integrity_error_propagates(tmp_path): + """Only the email index maps to ValueError; another unique violation is not an email conflict.""" + import asyncio + + from sqlalchemy.exc import IntegrityError + + from app.gateway.auth.repositories.sqlite import SQLiteUserRepository + + async def _run() -> None: + from deerflow.persistence.engine import close_engine, get_session_factory, init_engine + + url = f"sqlite+aiosqlite:///{tmp_path}/scratch.db" + await init_engine("sqlite", url=url, sqlite_dir=str(tmp_path)) + try: + repo = SQLiteUserRepository(get_session_factory()) + await repo.create_user(User(email="alice@x.com", password_hash=None, system_role="user", oauth_provider="oidc", oauth_id="sub-1")) + bob = await repo.create_user(User(email="bob@x.com", password_hash="h", system_role="user")) + bob.oauth_provider, bob.oauth_id = "oidc", "sub-1" + + with pytest.raises(IntegrityError): + await repo.update_user(bob) + finally: + await close_engine() + + asyncio.run(_run()) + + def test_distinct_emails_remain_distinct(tmp_path): """Case-folding must not collapse genuinely different addresses.""" import asyncio diff --git a/backend/tests/test_auth_type_system.py b/backend/tests/test_auth_type_system.py index 21132a43d5..54593f3949 100644 --- a/backend/tests/test_auth_type_system.py +++ b/backend/tests/test_auth_type_system.py @@ -976,6 +976,54 @@ def test_change_password_reissues_access_and_csrf_in_lockstep_when_preference_ch assert "max-age=604800" in csrf_cookies[0] +def test_change_password_new_email_registered_after_the_precheck_is_400(monkeypatch): + """An address registered between the uniqueness pre-check and the write is a 400, not a 500. + + The route checks the new email, then hashes the password before it writes, + so a concurrent /register of the same address can commit first. The + unique index then rejects the update, and nothing about the account changes. + """ + from app.gateway.deps import get_local_provider + + _setup_config() + client = TestClient(_make_auth_app(), base_url="https://deerflow.example") + email = _unique_email("change-password-race") + new_email = _unique_email("change-password-race-target") + client.post("/api/v1/auth/register", json={"email": email, "password": "Tr0ub4dor3a"}) + client.post("/api/v1/auth/login/local", data={"username": email, "password": "Tr0ub4dor3a"}) + csrf_token = client.cookies.get("csrf_token") + + provider = get_local_provider() + precheck = provider.get_user_by_email + prechecked: list[str] = [] + + async def precheck_then_concurrent_register(address: str): + found = await precheck(address) + prechecked.append(address) + await provider.create_user(email=address, password="Rac1ngSignupPwd!", system_role="user") + return found + + monkeypatch.setattr(provider, "get_user_by_email", precheck_then_concurrent_register) + resp = client.post( + "/api/v1/auth/change-password", + json={"current_password": "Tr0ub4dor3a", "new_password": "An0therStrongPwd!", "new_email": new_email}, + headers={"X-CSRF-Token": csrf_token}, + ) + monkeypatch.undo() + + assert prechecked == [new_email] + assert resp.status_code == 400, resp.text + assert resp.json()["detail"]["code"] == AuthErrorCode.EMAIL_ALREADY_EXISTS + # Nothing was written: the session still works, the email is unchanged, + # and only the old password logs in. + me = client.get("/api/v1/auth/me") + assert me.status_code == 200 + assert me.json()["email"] == email + fresh = TestClient(_make_auth_app(), base_url="https://deerflow.example") + assert fresh.post("/api/v1/auth/login/local", data={"username": email, "password": "Tr0ub4dor3a"}).status_code == 200 + assert fresh.post("/api/v1/auth/login/local", data={"username": email, "password": "An0therStrongPwd!"}).status_code == 401 + + def test_initialize_remember_me_false_keeps_access_and_csrf_session_only(): _setup_config() client = TestClient(_make_auth_app(), base_url="https://deerflow.example")