From 012ae2fa1e32f54cf2ed4e386993c6afbd3f7d95 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 17 Nov 2026 09:30:48 -0500 Subject: [PATCH] refactor(user): confirm an email inside the single user update pr-ready step 3 (simplify). The confirmation now rides the one apply_user_update transaction, guarded by expected_email, so a later 400 or 403 rolls it back and the edit audit sees it without a post-write patch. update_user resets trust whenever it writes an email the caller doesn't vouch for, replacing trust_email. Tests share the dialog's apply, save and emailField helpers, and drop two redundant local imports. Co-Authored-By: Claude Opus 5.5 --- backend/endpoints/user.py | 25 ++++++----- backend/exceptions/database_exceptions.py | 9 ++++ backend/handler/auth/base_handler.py | 7 ++- backend/handler/database/users_handler.py | 43 +++++++++--------- backend/tests/endpoints/test_identity.py | 3 -- backend/tests/endpoints/test_user.py | 43 ++++++++++++++++++ .../handler/database/test_users_handler.py | 37 ++++++++++++---- .../Settings/EditUserDialog.test.ts | 44 +++++++------------ 8 files changed, 139 insertions(+), 72 deletions(-) diff --git a/backend/endpoints/user.py b/backend/endpoints/user.py index c65c349c8..019acbb69 100644 --- a/backend/endpoints/user.py +++ b/backend/endpoints/user.py @@ -11,7 +11,7 @@ from decorators.auth import protected_route from endpoints.forms.identity import UserForm from endpoints.permissions import emit_permissions_changed from endpoints.responses.identity import InviteLinkSchema, UserSchema -from exceptions.database_exceptions import LastAdminError +from exceptions.database_exceptions import EmailChangedError, LastAdminError from handler.audit_handler import ( AuditActor, AuditTarget, @@ -55,6 +55,8 @@ router = APIRouter( ) +_EMAIL_CHANGED: Final = "The user's email changed. Reload it and confirm again." + # What a user edit reports; ui_settings and avatars change too often to be news. _USER_EDIT_AUDIT_FIELDS: Final = ( "username", @@ -559,15 +561,16 @@ async def update_user( status_code=status.HTTP_403_FORBIDDEN, detail="Only an administrator can confirm an email", ) - confirmed = False + # The confirmation names the address the admin saw, so a user who changed it + # meanwhile doesn't get the new one trusted. + expected_email = None if confirm_email and not db_user.email_trusted: - # Matched against the stored row, in case the user changed it meanwhile. - if not db_user_handler.trust_email(id, confirm_email): + if confirm_email.lower() != (db_user.email or "").lower(): raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="The user's email changed. Reload it and confirm again.", + status_code=status.HTTP_409_CONFLICT, detail=_EMAIL_CHANGED ) - confirmed = True + cleaned_data["email_trusted"] = True + expected_email = confirm_email # You can't change your own role if form_data.role and request.user.id != id: @@ -636,7 +639,12 @@ async def update_user( cleaned_data, revoke_sessions_for=previous_username if creds_updated else None, keep_an_admin=True, + expected_email=expected_email, ) + except EmailChangedError as exc: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, detail=_EMAIL_CHANGED + ) from exc except LastAdminError as exc: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, @@ -663,9 +671,6 @@ async def update_user( db_client_token_handler.get_token_ids_by_users([id]) ) - if confirmed: - cleaned_data["email_trusted"] = True - before = db_user db_user = db_user_handler.get_user(id) if not db_user: diff --git a/backend/exceptions/database_exceptions.py b/backend/exceptions/database_exceptions.py index 01800892e..983099001 100644 --- a/backend/exceptions/database_exceptions.py +++ b/backend/exceptions/database_exceptions.py @@ -9,6 +9,15 @@ class RomFileOwnerChangedError(Exception): return self.message +class EmailChangedError(Exception): + def __init__(self, user_id: int) -> None: + self.message = f"User {user_id} no longer has the expected email" + super().__init__(self.message) + + def __repr__(self) -> str: + return self.message + + class LastAdminError(Exception): def __init__(self, user_id: int) -> None: self.message = f"User {user_id} is the last admin" diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index e1c47ee63..be8ee61da 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -327,6 +327,7 @@ class AuthHandler: data: dict[str, Any], revoke_sessions_for: str | None = None, keep_an_admin: bool = False, + expected_email: str | None = None, ) -> None: """ Write an update to a user, revoking the account's sessions and OAuth @@ -338,6 +339,8 @@ class AuthHandler: are keyed by, or None to write without revoking. keep_an_admin (bool): Refuse, with LastAdminError, a role change that would leave no admin. + expected_email (str | None): Refuse, with EmailChangedError, an + update to a user whose email no longer matches. """ from handler.database import db_user_handler from handler.database.base_handler import sync_session @@ -354,7 +357,9 @@ class AuthHandler: # rather than committing it with the account's sessions left live. await self._revoke_user_credentials(revoke_sessions_for) - db_user_handler.update_user(user_id, data, session=session) + db_user_handler.update_user( + user_id, data, expected_email=expected_email, session=session + ) if revoke_sessions_for: # After it, for a login the old password was still good for. diff --git a/backend/handler/database/users_handler.py b/backend/handler/database/users_handler.py index 3278c23e4..b6fafa359 100644 --- a/backend/handler/database/users_handler.py +++ b/backend/handler/database/users_handler.py @@ -7,7 +7,7 @@ from sqlalchemy.orm import QueryableAttribute, Session, load_only from sqlalchemy.sql import Delete, Select, Update from decorators.database import INJECTED_SESSION, begin_session -from exceptions.database_exceptions import LastAdminError +from exceptions.database_exceptions import EmailChangedError, LastAdminError from models.snapshot import Snapshot from models.user import Role, User @@ -118,33 +118,34 @@ class DBUsersHandler(DBBaseHandler): data: dict[str, Any], *, keep_an_admin: bool = False, + expected_email: str | None = None, session: Session = INJECTED_SESSION, ) -> User: + """Write `data` to the user. + + Args: + keep_an_admin: Raise LastAdminError if the write would leave no admin. + expected_email: Raise EmailChangedError unless the stored email still + matches, so a confirmation applies only to the address it names. + """ if keep_an_admin: self.refuse_removing_the_last_admin(id, data, session=session) - session.execute( - update(User) - .where(User.id == id) - .values(**data) - .execution_options(synchronize_session="evaluate") + # A new address is unconfirmed unless the caller vouches for it. + if "email" in data and "email_trusted" not in data: + data = {**data, "email_trusted": False} + query = self.filter( + update(User), + ids=[id], + emails=[expected_email] if expected_email is not None else (), ) - return session.scalars(select(User).filter_by(id=id)).one() - - @begin_session - def trust_email( - self, - id: int, - email: str, - session: Session = INJECTED_SESSION, - ) -> bool: - """Mark the user's email trusted only if it is still `email`.""" - query = self.filter(update(User), ids=[id], emails=[email]) + # "evaluate" can't run the case-insensitive email match in Python. + sync = "evaluate" if expected_email is None else "fetch" result = session.execute( - query.values(email_trusted=True).execution_options( - synchronize_session=False - ) + query.values(**data).execution_options(synchronize_session=sync) ) - return affected_rows(result) > 0 + if expected_email is not None and affected_rows(result) == 0: + raise EmailChangedError(id) + return session.scalars(select(User).filter_by(id=id)).one() @begin_session def set_ra_progression( diff --git a/backend/tests/endpoints/test_identity.py b/backend/tests/endpoints/test_identity.py index b496b6d3a..e361a8d76 100644 --- a/backend/tests/endpoints/test_identity.py +++ b/backend/tests/endpoints/test_identity.py @@ -99,8 +99,6 @@ def test_get_user(client, access_token: str, editor_user: User): def test_get_user_avatar( mock_validate_path, client, viewer_access_token: str, admin_user: User, tmp_path ): - from handler.database import db_user_handler - db_user_handler.update_user( admin_user.id, {"avatar_path": f"users/{admin_user.fs_safe_folder_name}/profile/avatar.png"}, @@ -405,7 +403,6 @@ def test_an_invitee_chosen_email_is_not_trusted(client, access_token: str): def test_overlapping_registrations_spend_one_invite_once(client, access_token: str): """Two registrations racing on one invite must not both create an account.""" - from handler.database import db_user_handler token = _invite_token(client, access_token) # Hold each request at the token check until the other arrives, so the only diff --git a/backend/tests/endpoints/test_user.py b/backend/tests/endpoints/test_user.py index d35e150a6..0d7ac9551 100644 --- a/backend/tests/endpoints/test_user.py +++ b/backend/tests/endpoints/test_user.py @@ -821,6 +821,49 @@ def test_an_admin_confirms_only_the_email_they_saw( assert not current.enabled +def test_a_confirmation_racing_an_email_change_is_refused( + client, access_token: str, viewer_user: User, mocker +): + db_user_handler.update_user(viewer_user.id, {"email": "viewer@example.com"}) + stale = db_user_handler.get_user(viewer_user.id) + # The user changes their email after the admin's request has read the old one. + db_user_handler.update_user(viewer_user.id, {"email": "taken@example.com"}) + get_user = db_user_handler.get_user + reads = iter([stale]) + mocker.patch.object( + db_user_handler, + "get_user", + side_effect=lambda id: next(reads, None) or get_user(id), + ) + + response = client.put( + f"/api/users/{viewer_user.id}", + data={"confirm_email": "viewer@example.com"}, + headers=bearer(access_token), + ) + + assert response.status_code == status.HTTP_409_CONFLICT + current = get_user(viewer_user.id) + assert current and current.email == "taken@example.com" + assert not current.email_trusted + + +def test_a_refused_edit_does_not_confirm_the_email( + client, access_token: str, viewer_user: User +): + db_user_handler.update_user(viewer_user.id, {"email": "viewer@example.com"}) + + response = client.put( + f"/api/users/{viewer_user.id}", + data={"confirm_email": "viewer@example.com", "ui_settings": "[]"}, + headers=bearer(access_token), + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + current = db_user_handler.get_user(viewer_user.id) + assert current and not current.email_trusted + + def test_a_password_less_account_cannot_set_a_password_with_a_token( client, viewer_access_token: str, viewer_user: User ): diff --git a/backend/tests/handler/database/test_users_handler.py b/backend/tests/handler/database/test_users_handler.py index e2ed26688..9c10aa816 100644 --- a/backend/tests/handler/database/test_users_handler.py +++ b/backend/tests/handler/database/test_users_handler.py @@ -3,7 +3,7 @@ from datetime import datetime, timedelta, timezone import pytest -from exceptions.database_exceptions import LastAdminError +from exceptions.database_exceptions import EmailChangedError, LastAdminError from handler.database import db_user_handler from handler.database.base_handler import sync_session from models.user import Role, User @@ -138,19 +138,40 @@ class TestUpdateLastActive: assert executed_statements == [] -class TestTrustEmail: - def test_trusts_the_email_the_user_still_holds(self, viewer_user: User): +class TestUpdateUserEmailTrust: + def test_a_new_email_is_untrusted_unless_the_caller_vouches( + self, viewer_user: User + ): + db_user_handler.update_user( + viewer_user.id, {"email": "old@example.com", "email_trusted": True} + ) + + updated = db_user_handler.update_user( + viewer_user.id, {"email": "new@example.com"} + ) + + assert not updated.email_trusted + + def test_writes_when_the_expected_email_still_matches(self, viewer_user: User): db_user_handler.update_user(viewer_user.id, {"email": "viewer@example.com"}) - assert db_user_handler.trust_email(viewer_user.id, "Viewer@Example.com") + updated = db_user_handler.update_user( + viewer_user.id, + {"email_trusted": True}, + expected_email="Viewer@Example.com", + ) - current = db_user_handler.get_user(viewer_user.id) - assert current and current.email_trusted + assert updated.email_trusted - def test_leaves_a_changed_email_untrusted(self, viewer_user: User): + def test_refuses_when_the_email_changed(self, viewer_user: User): db_user_handler.update_user(viewer_user.id, {"email": "taken@example.com"}) - assert not db_user_handler.trust_email(viewer_user.id, "viewer@example.com") + with pytest.raises(EmailChangedError): + db_user_handler.update_user( + viewer_user.id, + {"email_trusted": True}, + expected_email="viewer@example.com", + ) current = db_user_handler.get_user(viewer_user.id) assert current and not current.email_trusted diff --git a/frontend/src/components/Settings/EditUserDialog.test.ts b/frontend/src/components/Settings/EditUserDialog.test.ts index d22600989..7809eede6 100644 --- a/frontend/src/components/Settings/EditUserDialog.test.ts +++ b/frontend/src/components/Settings/EditUserDialog.test.ts @@ -112,6 +112,20 @@ async function pick( await input.trigger("change"); } +function apply(wrapper: VueWrapper) { + return wrapper.findAll("button").find((b) => b.text() === "common.apply"); +} + +async function save(wrapper: VueWrapper) { + await apply(wrapper)?.trigger("click"); + await flushPromises(); +} + +const emailField = (wrapper: VueWrapper) => + wrapper + .findAllComponents(RTextField) + .find((f) => f.props("type") === "email"); + describe("EditUserDialog avatar preview", () => { let urls = 0; @@ -157,14 +171,6 @@ describe("EditUserDialog age settings", () => { updateUserPermissions.mockResolvedValue({ data: {} }); }); - async function save(wrapper: VueWrapper) { - const apply = wrapper - .findAll("button") - .find((b) => b.text() === "common.apply"); - await apply?.trigger("click"); - await flushPromises(); - } - it("sends the age settings only once they change", async () => { const { wrapper } = await mountDialog("user"); const fields = wrapper.findComponent(AgeLimitFields); @@ -319,10 +325,6 @@ describe("EditUserDialog current password", () => { await flushPromises(); } - function apply(wrapper: VueWrapper) { - return wrapper.findAll("button").find((b) => b.text() === "common.apply"); - } - it("asks for it when changing your own password", async () => { storeAuth().setCurrentUser(userFixture({ id: 4 })); const { wrapper } = await mountDialog(); @@ -374,11 +376,6 @@ describe("EditUserDialog current password", () => { }); describe("EditUserDialog OIDC email", () => { - const emailField = (wrapper: VueWrapper) => - wrapper - .findAllComponents(RTextField) - .find((f) => f.props("type") === "email"); - it("locks your own email when the identity provider manages it", async () => { storeAuth().setCurrentUser( userFixture({ id: 4, email_managed_by_oidc: true }), @@ -415,14 +412,6 @@ describe("EditUserDialog email confirmation", () => { updateUser.mockResolvedValue({ data: userFixture({ id: 4 }) }); }); - async function save(wrapper: VueWrapper) { - const apply = wrapper - .findAll("button") - .find((b) => b.text() === "common.apply"); - await apply?.trigger("click"); - await flushPromises(); - } - it("confirms the saved email only when the admin turns the switch on", async () => { const { wrapper, open } = await mountDialog(); await open(4, unconfirmed); @@ -443,10 +432,7 @@ describe("EditUserDialog email confirmation", () => { await open(4, unconfirmed); expect(confirmSwitch(wrapper)).toBeDefined(); - const email = wrapper - .findAllComponents(RTextField) - .find((f) => f.props("type") === "email"); - email?.vm.$emit("update:modelValue", "other@example.com"); + emailField(wrapper)?.vm.$emit("update:modelValue", "other@example.com"); await flushPromises(); expect(confirmSwitch(wrapper)).toBeUndefined();