From cf46b01ff54866cf7cc49f3995e2b8a010541b58 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 17 Nov 2026 09:25:11 -0500 Subject: [PATCH] fix(user): confirm a user's email only through an explicit admin action pr-ready step 2 follow-up. The frontend resends the email on every save, so trusting it on any admin save let enabling an invitee vouch for an address nobody checked. An admin now sends confirm_email (the address they saw) from a switch in the edit dialog; a changed address answers 409. UserSchema exposes email_trusted and the edit audit records it. Co-Authored-By: Claude Opus 5.5 --- backend/endpoints/forms/identity.py | 2 + backend/endpoints/responses/identity.py | 1 + backend/endpoints/user.py | 27 ++++-- backend/tests/endpoints/test_user.py | 87 ++++++++++++++----- frontend/src/__generated__/models/UserForm.ts | 1 + .../src/__generated__/models/UserSchema.ts | 1 + .../Settings/EditUserDialog.test.ts | 72 ++++++++++++++- .../components/Settings/EditUserDialog.vue | 36 ++++++++ frontend/src/locales/bg_BG/audit.json | 1 + frontend/src/locales/bg_BG/settings.json | 2 + frontend/src/locales/cs_CZ/audit.json | 1 + frontend/src/locales/cs_CZ/settings.json | 2 + frontend/src/locales/de_DE/audit.json | 1 + frontend/src/locales/de_DE/settings.json | 2 + frontend/src/locales/en_GB/audit.json | 1 + frontend/src/locales/en_GB/settings.json | 2 + frontend/src/locales/en_US/audit.json | 1 + frontend/src/locales/en_US/settings.json | 2 + frontend/src/locales/es_ES/audit.json | 1 + frontend/src/locales/es_ES/settings.json | 2 + frontend/src/locales/fr_FR/audit.json | 1 + frontend/src/locales/fr_FR/settings.json | 2 + frontend/src/locales/hu_HU/audit.json | 1 + frontend/src/locales/hu_HU/settings.json | 2 + frontend/src/locales/it_IT/audit.json | 1 + frontend/src/locales/it_IT/settings.json | 2 + frontend/src/locales/ja_JP/audit.json | 1 + frontend/src/locales/ja_JP/settings.json | 2 + frontend/src/locales/ko_KR/audit.json | 1 + frontend/src/locales/ko_KR/settings.json | 2 + frontend/src/locales/pl_PL/audit.json | 1 + frontend/src/locales/pl_PL/settings.json | 2 + frontend/src/locales/pt_BR/audit.json | 1 + frontend/src/locales/pt_BR/settings.json | 2 + frontend/src/locales/ro_RO/audit.json | 1 + frontend/src/locales/ro_RO/settings.json | 2 + frontend/src/locales/ru_RU/audit.json | 1 + frontend/src/locales/ru_RU/settings.json | 2 + frontend/src/locales/sv_SE/audit.json | 1 + frontend/src/locales/sv_SE/settings.json | 2 + frontend/src/locales/tr_TR/audit.json | 1 + frontend/src/locales/tr_TR/settings.json | 2 + frontend/src/locales/zh_CN/audit.json | 1 + frontend/src/locales/zh_CN/settings.json | 2 + frontend/src/locales/zh_TW/audit.json | 1 + frontend/src/locales/zh_TW/settings.json | 2 + frontend/src/services/api/user.ts | 2 + frontend/src/utils/user.fixtures.ts | 1 + 48 files changed, 250 insertions(+), 37 deletions(-) diff --git a/backend/endpoints/forms/identity.py b/backend/endpoints/forms/identity.py index 4610143b5..cb9aad2a3 100644 --- a/backend/endpoints/forms/identity.py +++ b/backend/endpoints/forms/identity.py @@ -10,6 +10,8 @@ class UserForm(BaseModel): password: str | None = None current_password: str | None = None email: str | None = None + # The address an admin confirms; it must still be the user's current email. + confirm_email: str | None = None role: str | None = None enabled: bool | None = None ra_username: str | None = Field(default=None, max_length=TEXT_FIELD_LENGTH) diff --git a/backend/endpoints/responses/identity.py b/backend/endpoints/responses/identity.py index faffea50e..0ad97f8e5 100644 --- a/backend/endpoints/responses/identity.py +++ b/backend/endpoints/responses/identity.py @@ -29,6 +29,7 @@ class UserSchema(BaseModel): oauth_scopes: list[str] has_password: bool email_managed_by_oidc: bool + email_trusted: bool avatar_path: str last_login: UTCDatetime | None last_active: UTCDatetime | None diff --git a/backend/endpoints/user.py b/backend/endpoints/user.py index 5be535356..c65c349c8 100644 --- a/backend/endpoints/user.py +++ b/backend/endpoints/user.py @@ -59,6 +59,7 @@ router = APIRouter( _USER_EDIT_AUDIT_FIELDS: Final = ( "username", "email", + "email_trusted", "hashed_password", "role", "enabled", @@ -552,13 +553,21 @@ async def update_user( cleaned_data["email"] = new_email.lower() or None cleaned_data["email_trusted"] = by_admin - # Saving an unchanged email as an admin vouches for it, but only for the - # address the admin saw, in case the user changed it meanwhile. - vouch_for = ( - email - if by_admin and new_email is None and email and not db_user.email_trusted - else None - ) + confirm_email = form_data.confirm_email if new_email is None else None + if confirm_email and not by_admin: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Only an administrator can confirm an email", + ) + confirmed = False + 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): + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="The user's email changed. Reload it and confirm again.", + ) + confirmed = True # You can't change your own role if form_data.role and request.user.id != id: @@ -654,8 +663,8 @@ async def update_user( db_client_token_handler.get_token_ids_by_users([id]) ) - if vouch_for: - db_user_handler.trust_email(id, vouch_for) + if confirmed: + cleaned_data["email_trusted"] = True before = db_user db_user = db_user_handler.get_user(id) diff --git a/backend/tests/endpoints/test_user.py b/backend/tests/endpoints/test_user.py index da2ccd1ad..d35e150a6 100644 --- a/backend/tests/endpoints/test_user.py +++ b/backend/tests/endpoints/test_user.py @@ -3,6 +3,7 @@ from datetime import timedelta import pytest from fastapi import status +from tests.audit_events import recorded_events from tests.auth_helpers import bearer from endpoints import user as user_endpoints @@ -736,50 +737,88 @@ def test_a_user_a_delegated_user_manager_creates_has_an_untrusted_email( assert created and not created.email_trusted -@pytest.mark.parametrize( - "email", ["viewer@example.com", "new@example.com"], ids=["unchanged", "changed"] -) -def test_an_admin_saving_a_users_email_trusts_it( - client, access_token: str, viewer_user: User, email: str +def test_an_admin_setting_a_new_email_trusts_it( + 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={"email": email}, + data={"email": "new@example.com"}, + headers=bearer(access_token), + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["email_trusted"] is True + + +def test_an_admin_save_that_resends_the_email_does_not_trust_it( + client, access_token: str, viewer_user: User +): + db_user_handler.update_user( + viewer_user.id, {"email": "viewer@example.com", "enabled": False} + ) + + response = client.put( + f"/api/users/{viewer_user.id}", + data={"email": "viewer@example.com", "enabled": "true"}, headers=bearer(access_token), ) assert response.status_code == status.HTTP_200_OK updated = db_user_handler.get_user(viewer_user.id) - assert updated and updated.email_trusted + assert updated and updated.enabled and not updated.email_trusted -def test_an_admin_vouches_only_for_the_email_they_saved( - client, access_token: str, viewer_user: User, mocker -): +def test_an_admin_confirms_a_users_email(client, access_token: str, viewer_user: User): 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={"email": "viewer@example.com"}, + data={"email": "viewer@example.com", "confirm_email": "Viewer@Example.com"}, headers=bearer(access_token), ) assert response.status_code == status.HTTP_200_OK - current = get_user(viewer_user.id) - assert current and current.email == "taken@example.com" - assert not current.email_trusted + assert response.json()["email_trusted"] is True + edit = next(e for e in recorded_events() if e.action == "user.edit") + assert edit.data == {"changed": ["email_trusted"]} + + +def test_a_delegated_user_manager_cannot_confirm_an_email( + client, admin_user: User, viewer_user: User, editor_user: User +): + db_user_handler.update_user(editor_user.id, {"email": "editor@example.com"}) + token = _delegated_user_manager_token(viewer_user) + + response = client.put( + f"/api/users/{editor_user.id}", + data={"confirm_email": "editor@example.com"}, + headers=bearer(token), + ) + + assert response.status_code == status.HTTP_403_FORBIDDEN + updated = db_user_handler.get_user(editor_user.id) + assert updated and not updated.email_trusted + + +def test_an_admin_confirms_only_the_email_they_saw( + client, access_token: str, viewer_user: User +): + db_user_handler.update_user( + viewer_user.id, {"email": "taken@example.com", "enabled": False} + ) + + response = client.put( + f"/api/users/{viewer_user.id}", + data={"confirm_email": "viewer@example.com", "enabled": "true"}, + headers=bearer(access_token), + ) + + assert response.status_code == status.HTTP_409_CONFLICT + current = db_user_handler.get_user(viewer_user.id) + assert current and not current.email_trusted + assert not current.enabled def test_a_password_less_account_cannot_set_a_password_with_a_token( diff --git a/frontend/src/__generated__/models/UserForm.ts b/frontend/src/__generated__/models/UserForm.ts index b02951871..3ed14ca53 100644 --- a/frontend/src/__generated__/models/UserForm.ts +++ b/frontend/src/__generated__/models/UserForm.ts @@ -7,6 +7,7 @@ export type UserForm = { password?: (string | null); current_password?: (string | null); email?: (string | null); + confirm_email?: (string | null); role?: (string | null); enabled?: (boolean | null); ra_username?: (string | null); diff --git a/frontend/src/__generated__/models/UserSchema.ts b/frontend/src/__generated__/models/UserSchema.ts index eb98e9088..a9a5b51cf 100644 --- a/frontend/src/__generated__/models/UserSchema.ts +++ b/frontend/src/__generated__/models/UserSchema.ts @@ -14,6 +14,7 @@ export type UserSchema = { oauth_scopes: Array; has_password: boolean; email_managed_by_oidc: boolean; + email_trusted: boolean; avatar_path: string; last_login: (string | null); last_active: (string | null); diff --git a/frontend/src/components/Settings/EditUserDialog.test.ts b/frontend/src/components/Settings/EditUserDialog.test.ts index 2ebcdecc7..d22600989 100644 --- a/frontend/src/components/Settings/EditUserDialog.test.ts +++ b/frontend/src/components/Settings/EditUserDialog.test.ts @@ -1,9 +1,10 @@ import { type VueWrapper, flushPromises, mount } from "@vue/test-utils"; import mitt, { type Emitter } from "mitt"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { UserPermissionsSchema } from "@/__generated__"; -import { RTextField } from "@/lib"; +import type { UserPermissionsSchema, UserSchema } from "@/__generated__"; +import { RSwitch, RTextField } from "@/lib"; import storeAuth from "@/stores/auth"; +import storeHeartbeat from "@/stores/heartbeat"; import type { Events } from "@/types/emitter"; import { userFixture } from "@/utils/user.fixtures"; import AgeLimitFields from "./AgeLimitFields.vue"; @@ -92,8 +93,8 @@ async function mountDialog(role: "admin" | "user" = "admin") { }, }, }); - const open = (id = 4) => { - emitter.emit("showEditUserDialog", userFixture({ id, role })); + const open = (id = 4, overrides: Partial = {}) => { + emitter.emit("showEditUserDialog", userFixture({ id, role, ...overrides })); return flushPromises(); }; await open(); @@ -396,3 +397,66 @@ describe("EditUserDialog OIDC email", () => { expect(emailField(wrapper)?.props("readonly")).toBe(false); }); }); + +describe("EditUserDialog email confirmation", () => { + const unconfirmed = { email: "invitee@example.com", email_trusted: false }; + const confirmSwitch = (wrapper: VueWrapper) => + wrapper + .findAllComponents(RSwitch) + .find((s) => s.props("label") === "settings.confirm-email"); + + beforeEach(() => { + const heartbeat = storeHeartbeat(); + heartbeat.value = { + ...heartbeat.value, + OIDC: { ...heartbeat.value.OIDC, ENABLED: true }, + }; + storeAuth().setCurrentUser(userFixture({ id: 1 })); + 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); + + await save(wrapper); + expect(updateUser.mock.lastCall?.[0].confirm_email).toBeUndefined(); + + await open(4, unconfirmed); + confirmSwitch(wrapper)?.vm.$emit("update:modelValue", true); + await save(wrapper); + expect(updateUser.mock.lastCall?.[0].confirm_email).toBe( + "invitee@example.com", + ); + }); + + it("hides the switch once the email is edited", async () => { + const { wrapper, open } = await mountDialog(); + 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"); + await flushPromises(); + + expect(confirmSwitch(wrapper)).toBeUndefined(); + }); + + it("hides the switch from a delegated user manager", async () => { + storeAuth().setCurrentUser(userFixture({ id: 1, role: "user" })); + const { wrapper, open } = await mountDialog(); + await open(4, unconfirmed); + + expect(confirmSwitch(wrapper)).toBeUndefined(); + }); +}); diff --git a/frontend/src/components/Settings/EditUserDialog.vue b/frontend/src/components/Settings/EditUserDialog.vue index ac8661418..10c5da856 100644 --- a/frontend/src/components/Settings/EditUserDialog.vue +++ b/frontend/src/components/Settings/EditUserDialog.vue @@ -17,6 +17,7 @@ import permissionsApi from "@/services/api/permissions"; import platformApi from "@/services/api/platform"; import userApi from "@/services/api/user"; import storeAuth from "@/stores/auth"; +import storeHeartbeat from "@/stores/heartbeat"; import storePermissionGroups from "@/stores/permissionGroups"; import type { Platform } from "@/stores/platforms"; import storeUsers from "@/stores/users"; @@ -34,6 +35,7 @@ defineOptions({ inheritAttrs: false }); const { t } = useI18n(); const auth = storeAuth(); +const heartbeat = storeHeartbeat(); const usersStore = storeUsers(); const groupsStore = storePermissionGroups(); const emitter = inject>("emitter"); @@ -44,6 +46,8 @@ const submitting = ref(false); const user = ref(null); const confirmPassword = ref(""); const currentPassword = ref(""); +const savedEmail = ref(null); +const confirmEmail = ref(false); const imagePreviewUrl = useObjectUrl(() => user.value?.avatar); const fileInputRef = ref(null); @@ -101,6 +105,18 @@ const emailLocked = computed( () => editingSelf.value && !!auth.user?.email_managed_by_oidc, ); +// A first OIDC sign-in links an account by email only once an admin confirms +// it. A changed email is trusted on save, so the switch covers the saved one. +const canConfirmEmail = computed( + () => + heartbeat.value.OIDC.ENABLED && + auth.user?.role === "admin" && + !!user.value && + !user.value.email_trusted && + !!savedEmail.value && + (user.value.email ?? "").toLowerCase() === savedEmail.value.toLowerCase(), +); + const requiresCurrentPassword = computed( () => editingSelf.value && @@ -134,6 +150,8 @@ async function open(toEdit: Events["showEditUserDialog"]) { user.value = { ...toEdit, password: "", avatar: undefined }; confirmPassword.value = ""; currentPassword.value = ""; + savedEmail.value = toEdit.email; + confirmEmail.value = false; isAdmin.value = toEdit.role === "admin"; showAdvanced.value = false; accessLoaded.value = false; @@ -305,6 +323,10 @@ async function save() { current_password: requiresCurrentPassword.value ? currentPassword.value : undefined, + confirm_email: + confirmEmail.value && canConfirmEmail.value + ? (savedEmail.value ?? undefined) + : undefined, }); let nextUser = data; @@ -422,6 +444,15 @@ function close() { {{ t("settings.email") }} + ( `/users/${id}`, @@ -77,6 +78,7 @@ async function updateUser({ password: attrs.password, current_password: attrs.current_password, email: attrs.email, + confirm_email: attrs.confirm_email, enabled: attrs.enabled, role: attrs.role, ra_username: attrs.ra_username, diff --git a/frontend/src/utils/user.fixtures.ts b/frontend/src/utils/user.fixtures.ts index 050a39017..d74ebd1b9 100644 --- a/frontend/src/utils/user.fixtures.ts +++ b/frontend/src/utils/user.fixtures.ts @@ -12,6 +12,7 @@ export function userFixture(overrides: Partial = {}): UserSchema { oauth_scopes: [], has_password: true, email_managed_by_oidc: false, + email_trusted: true, avatar_path: "", last_login: null, last_active: null,