mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-20 03:10:34 +00:00
fix(auth): answer 400 when a new email is registered during change-password (#8319)
change-password checks that the new email is free, hashes the new password, then writes. A /register of the same address that commits in between makes update_user's commit hit the users.email unique index, and the IntegrityError reached the client as an unhandled 500. update_user now reports an email index violation as ValueError, like create_user does for the same race, and the route maps it to the existing 400 email_already_exists. Other integrity errors propagate.
This commit is contained in:
parent
f32570d539
commit
2cc30714c9
@ -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
|
||||
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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.
|
||||
|
||||
|
||||
@ -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` 会:
|
||||
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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")
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user