Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(api): extract change email state machine (#40439)
Byron.wanga52adef203dd
diff --git a/api/.importlinter b/api/.importlinterindex 193e8cc4a7b..55e265a03cf 100644--- a/api/.importlinter+++ b/api/.importlinter@@ -98,6 +98,8 @@ name = Account application services and contracts are framework and persistencetype = forbiddensource_modules =services.account_avatar_service+ services.account_change_email_ports+ services.account_change_email_serviceservices.account_deletion_serviceservices.account_errorsservices.account_initialization_servicediff --git a/api/controllers/console/workspace/account.py b/api/controllers/console/workspace/account.pyindex 833161e5bfb..08a92a39f86 100644--- a/api/controllers/console/workspace/account.py+++ b/api/controllers/console/workspace/account.py@@ -23,6 +23,7 @@ from controllers.console import console_nsfrom controllers.console.auth.error import (EmailAlreadyInUseError,EmailChangeLimitError,+ EmailChangeRateLimitExceededError,EmailCodeAccountDeletionRateLimitExceededError,EmailCodeError,InvalidEmailError,@@ -53,7 +54,6 @@ from controllers.console.wraps import (with_current_user,)from extensions.ext_application_services import application_services-from extensions.ext_database import dbfrom fields.base import ResponseModelfrom fields.member_fields import AccountResponsefrom libs.helper import EmailStr, dump_response, extract_remote_ip, timezone, to_timestamp@@ -61,15 +61,8 @@ from libs.login import login_requiredfrom machinery.context import RequestContextfrom models import Accountfrom services import account_errors-from services.account_service import AccountServicefrom services.billing_service import BillingServicefrom services.entities.account_entities import AccountProfileChanges-from services.entities.auth_entities import (- ChangeEmailNewEmailToken,- ChangeEmailNewEmailVerifiedToken,- ChangeEmailOldEmailToken,- ChangeEmailOldEmailVerifiedToken,-)class AccountInitPayload(BaseModel):@@ -606,58 +599,32 @@ class ChangeEmailSendEmailApi(Resource):@console_ns.expect(console_ns.models[ChangeEmailSendPayload.__name__])@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SimpleResultDataResponse.__name__])@enable_change_email- @setup_required- @login_required- @account_initialization_required- @with_current_user- def post(self, current_user: Account):+ @console_account_admission()+ def post(self, request_context: RequestContext):payload = console_ns.payload or {}args = ChangeEmailSendPayload.model_validate(payload)ip_address = extract_remote_ip(request)- if AccountService.is_email_send_ip_limit(ip_address):- raise EmailSendIpLimitError()-- if args.language is not None and args.language == "zh-Hans":- language = "zh-Hans"- else:- language = "en-US"- account = current_user- user_email = current_user.email- email_for_sending = args.email.lower()- # Default to the initial phase; any legacy/unexpected client input is- # coerced back to `old_email` so we never trust the caller to declare- # later phases without a verified predecessor token.- send_phase = AccountService.CHANGE_EMAIL_PHASE_OLD- if args.phase is not None and args.phase == AccountService.CHANGE_EMAIL_PHASE_NEW:- send_phase = AccountService.CHANGE_EMAIL_PHASE_NEW- if args.token is None:- raise InvalidTokenError()-- reset_data = AccountService.get_change_email_data(args.token)- if reset_data is None:- raise InvalidTokenError()-- if not isinstance(reset_data, ChangeEmailOldEmailVerifiedToken):- raise InvalidTokenError()- if not reset_data.is_bound_to_account(current_user.id):- raise InvalidTokenError()- user_email = reset_data.email-- if user_email.lower() != current_user.email.lower():- raise InvalidEmailError()- else:- if email_for_sending != current_user.email.lower():- raise InvalidEmailError()- email_for_sending = current_user.email-- token = AccountService.send_change_email_email(- account=account,- email=email_for_sending,- old_email=user_email,- language=language,- phase=send_phase,- )+ language = "zh-Hans" if args.language == "zh-Hans" else "en-US"+ try:+ token = application_services().accounts.change_email.send_code(+ request_context,+ requested_email=args.email,+ language=language,+ phase=args.phase,+ predecessor_token=args.token,+ ip_address=ip_address,+ )+ except account_errors.ChangeEmailSendIPLimitedError:+ raise EmailSendIpLimitError() from None+ except account_errors.ChangeEmailSendRateLimitError as error:+ raise EmailChangeRateLimitExceededError(error.retry_after_minutes) from None+ except account_errors.InvalidChangeEmailTokenError:+ raise InvalidTokenError() from None+ except account_errors.InvalidChangeEmailAddressError:+ raise InvalidEmailError() from None+ except account_errors.AccountNotFoundError:+ raise AccountNotFound() from Nonereturn SimpleResultDataResponse(result="success", data=token).model_dump(mode="json")@@ -666,46 +633,27 @@ class ChangeEmailCheckApi(Resource):@console_ns.expect(console_ns.models[ChangeEmailValidityPayload.__name__])@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[VerificationTokenResponse.__name__])@enable_change_email- @setup_required- @login_required- @account_initialization_required- @with_current_user- def post(self, current_user: Account):+ @console_account_admission()+ def post(self, request_context: RequestContext):payload = console_ns.payload or {}args = ChangeEmailValidityPayload.model_validate(payload)- user_email = args.email.lower()-- is_change_email_error_rate_limit = AccountService.is_change_email_error_rate_limit(user_email)- if is_change_email_error_rate_limit:- raise EmailChangeLimitError()-- token_data = AccountService.get_change_email_data(args.token)- if token_data is None:- raise InvalidTokenError()- if not token_data.is_bound_to_account(current_user.id):- raise InvalidTokenError()-- normalized_token_email = token_data.email.lower()- if user_email != normalized_token_email:- raise InvalidEmailError()-- if args.code != token_data.code:- AccountService.add_change_email_error_rate_limit(user_email)- raise EmailCodeError()-- if isinstance(token_data, ChangeEmailOldEmailToken | ChangeEmailNewEmailToken):- refreshed_token_data = token_data.promote()- else:- raise InvalidTokenError()-- # Verified, revoke the first token- AccountService.revoke_change_email_token(args.token)-- new_token = AccountService.generate_change_email_token(refreshed_token_data, current_user)-- AccountService.reset_change_email_error_rate_limit(user_email)- return VerificationTokenResponse(is_valid=True, email=normalized_token_email, token=new_token).model_dump(+ try:+ verification = application_services().accounts.change_email.verify_code(+ request_context,+ email=args.email,+ code=args.code,+ token=args.token,+ )+ except account_errors.ChangeEmailVerificationLimitError:+ raise EmailChangeLimitError() from None+ except account_errors.InvalidChangeEmailTokenError:+ raise InvalidTokenError() from None+ except account_errors.InvalidChangeEmailAddressError:+ raise InvalidEmailError() from None+ except account_errors.InvalidChangeEmailCodeError:+ raise EmailCodeError() from None+ return VerificationTokenResponse(is_valid=True, email=verification.email, token=verification.token).model_dump(mode="json")@@ -714,53 +662,27 @@ class ChangeEmailCheckApi(Resource):class ChangeEmailResetApi(Resource):@console_ns.expect(console_ns.models[ChangeEmailResetPayload.__name__])@enable_change_email- @setup_required- @login_required- @account_initialization_required@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AccountResponse.__name__])- @with_current_user- def post(self, current_user: Account):+ @console_account_admission()+ def post(self, request_context: RequestContext):payload = console_ns.payload or {}args = ChangeEmailResetPayload.model_validate(payload)- normalized_new_email = args.new_email.lower()-- freeze_type = AccountService.get_account_freeze_type(normalized_new_email)- if freeze_type:- if freeze_type == "email_domain_suspended":- raise EmailDomainSuspendedError()- raise AccountInFreezeError()-- if not AccountService.check_email_unique(normalized_new_email, session=db.session()):- raise EmailAlreadyInUseError()-- reset_data = AccountService.get_change_email_data(args.token)- if not reset_data:- raise InvalidTokenError()- if not reset_data.is_bound_to_account(current_user.id):- raise InvalidTokenError()-- if not isinstance(reset_data, ChangeEmailNewEmailVerifiedToken):- raise InvalidTokenError()-- # Bind the new email to the token that was mailed and verified, so a- # verified token cannot be reused with a different `new_email` value.- if reset_data.email.lower() != normalized_new_email:- raise InvalidTokenError()-- if current_user.email.lower() != reset_data.old_email.lower():- raise AccountNotFound()-- # Revoke only after all checks pass so failed attempts don't burn a- # legitimately verified token.- AccountService.revoke_change_email_token(args.token)-- updated_account = AccountService.update_account_email(- current_user, email=normalized_new_email, session=db.session()- )-- AccountService.send_change_email_completed_notify_email(- email=normalized_new_email,- )+ try:+ updated_account = application_services().accounts.change_email.reset(+ request_context,+ new_email=args.new_email,+ token=args.token,+ )+ except account_errors.AccountEmailDomainSuspendedError:+ raise EmailDomainSuspendedError() from None+ except account_errors.AccountEmailFrozenError:+ raise AccountInFreezeError() from None+ except account_errors.AccountEmailAlreadyInUseError:+ raise EmailAlreadyInUseError() from None+ except account_errors.InvalidChangeEmailTokenError:+ raise InvalidTokenError() from None+ except account_errors.AccountNotFoundError:+ raise AccountNotFound() from Nonereturn dump_response(AccountResponse, updated_account)@@ -773,12 +695,12 @@ class CheckEmailUnique(Resource):def post(self):payload = console_ns.payload or {}args = CheckEmailUniquePayload.model_validate(payload)- normalized_email = args.email.lower()- freeze_type = AccountService.get_account_freeze_type(normalized_email)- if freeze_type:- if freeze_type == "email_domain_suspended":- raise EmailDomainSuspendedError()- raise AccountInFreezeError()- if not AccountService.check_email_unique(normalized_email, session=db.session()):- raise EmailAlreadyInUseError()+ try:+ application_services().accounts.change_email.ensure_available(args.email)+ except account_errors.AccountEmailDomainSuspendedError:+ raise EmailDomainSuspendedError() from None+ except account_errors.AccountEmailFrozenError:+ raise AccountInFreezeError() from None+ except account_errors.AccountEmailAlreadyInUseError:+ raise EmailAlreadyInUseError() from Nonereturn SimpleResultResponse(result="success").model_dump(mode="json")diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.pyindex 2e5b68fb09d..9035f5a6580 100644--- a/api/extensions/ext_application_services.py+++ b/api/extensions/ext_application_services.py@@ -40,6 +40,15 @@ from services.account_activation_adapters import (from services.account_activation_service import AccountActivationServicefrom services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGatewayfrom services.account_avatar_service import AccountAvatarService+from services.account_change_email_adapters import (+ BillingAccountEmailPolicyGateway,+ CeleryChangeEmailNotificationGateway,+ RateLimiterChangeEmailSendLimiter,+ RedisChangeEmailSecurityGateway,+ SecureChangeEmailCodeGenerator,+ TokenManagerChangeEmailTokenGateway,+)+from services.account_change_email_service import AccountChangeEmailServicefrom services.account_deletion_adapters import (CeleryAccountDeletionScheduler,CeleryAccountDeletionVerificationNotifier,@@ -111,6 +120,7 @@ def _is_user_allowed_to_access_webapp(user_id: str, app_id: str) -> bool:@dataclass(frozen=True, slots=True)class AccountServices:avatar: AccountAvatarService+ change_email: AccountChangeEmailServicedeletion: AccountDeletionServiceinitialization: AccountInitializationServiceintegrations: AccountIntegrationService@@ -166,6 +176,29 @@ def build_application_services(avatar=AccountAvatarService(files=SQLAlchemyAccountAvatarFileGateway(session_factory=database_client),),+ change_email=AccountChangeEmailService(+ accounts=accounts,+ tokens=TokenManagerChangeEmailTokenGateway(),+ codes=SecureChangeEmailCodeGenerator(),+ notifications=CeleryChangeEmailNotificationGateway(),+ send_limits=RateLimiterChangeEmailSendLimiter(+ rate_limiter=RateLimiter(+ prefix="change_email_rate_limit",+ max_attempts=1,+ time_window=60,+ redis_client=redis,+ )+ ),+ security=RedisChangeEmailSecurityGateway(+ redis=redis,+ email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,+ verification_failure_limit=5,+ verification_lockout_duration=dify_config.CHANGE_EMAIL_LOCKOUT_DURATION,+ ),+ email_policy=BillingAccountEmailPolicyGateway(+ billing_enabled=deployment_edition == DeploymentEdition.CLOUD,+ ),+ ),deletion=AccountDeletionService(accounts=accounts,memberships=workspace_query_repository,diff --git a/api/libs/helper.py b/api/libs/helper.pyindex 7610b834d31..98a593cbe34 100644--- a/api/libs/helper.py+++ b/api/libs/helper.py@@ -500,16 +500,13 @@ class TokenManager:def generate_token(cls,token_type: str,- account: "Account | None" = None,+ account_id: str | None = None,email: str | None = None,additional_data: dict[str, Any] | None = None,) -> str:- if account is None and email is None:+ if account_id is None and email is None:raise ValueError("Account or email must be provided")- account_id = account.id if account else None- account_email = email if email is not None else account.email if account else None-if account_id:old_token = cls._get_current_token_for_account(account_id, token_type)if old_token:@@ -518,7 +515,7 @@ class TokenManager:cls.revoke_token(old_token, token_type)token = str(uuid.uuid4())- token_data = {"account_id": account_id, "email": account_email, "token_type": token_type}+ token_data = {"account_id": account_id, "email": email, "token_type": token_type}if additional_data:token_data.update(additional_data)diff --git a/api/repositories/account_repository.py b/api/repositories/account_repository.pyindex bd0c34d1d01..495eee1998d 100644--- a/api/repositories/account_repository.py+++ b/api/repositories/account_repository.py@@ -2,13 +2,15 @@from typing import override-from sqlalchemy import select+from sqlalchemy import delete, selectfrom sqlalchemy.orm import Session, sessionmaker-from models.account import Account, AccountStatus, InvitationCode, InvitationCodeStatus+from models.account import Account, AccountIntegrate, AccountStatus, InvitationCode, InvitationCodeStatusfrom services.account_ports import AccountRepositoryfrom services.entities.account_entities import (AccountCredentials,+ AccountEmailResetResult,+ AccountEmailResetStatus,AccountInitialization,AccountInitializationResult,AccountInitializationStatus,@@ -112,6 +114,36 @@ class SQLAlchemyAccountRepository(AccountRepository):account=self._to_snapshot(account),)+ @override+ def email_exists(self, email: str) -> bool:+ with self._session_factory() as session:+ return session.scalar(select(Account.id).where(Account.email == email).limit(1)) is not None++ @override+ def reset_email(+ self,+ account_id: str,+ *,+ expected_old_email: str,+ new_email: str,+ ) -> AccountEmailResetResult:+ with self._session_factory.begin() as session:+ account = session.get(Account, account_id)+ if account is None:+ return AccountEmailResetResult(status=AccountEmailResetStatus.ACCOUNT_NOT_FOUND)+ if account.email.lower() != expected_old_email.lower():+ return AccountEmailResetResult(status=AccountEmailResetStatus.EMAIL_CHANGED)+ if session.scalar(select(Account.id).where(Account.email == new_email).limit(1)) is not None:+ return AccountEmailResetResult(status=AccountEmailResetStatus.EMAIL_IN_USE)++ account.email = new_email+ session.execute(delete(AccountIntegrate).where(AccountIntegrate.account_id == account_id))+ session.flush()+ return AccountEmailResetResult(+ status=AccountEmailResetStatus.UPDATED,+ account=self._to_snapshot(account),+ )+@staticmethoddef _to_snapshot(account: Account) -> AccountSnapshot:return AccountSnapshot(diff --git a/api/services/account_change_email_adapters.py b/api/services/account_change_email_adapters.pynew file mode 100644index 00000000000..cf1f255594b--- /dev/null+++ b/api/services/account_change_email_adapters.py@@ -0,0 +1,194 @@+"""Infrastructure adapters for the account change-email application service."""++import secrets+from typing import override++from pydantic import TypeAdapter, ValidationError+from redis import RedisError++from extensions.ext_redis import RedisClientWrapper+from libs.helper import RateLimiter, TokenManager+from services.account_change_email_ports import (+ AccountEmailPolicyGateway,+ ChangeEmailCodeGenerator,+ ChangeEmailNotificationGateway,+ ChangeEmailSecurityGateway,+ ChangeEmailSendLimiter,+ ChangeEmailTokenGateway,+)+from services.billing_service import BillingService+from services.entities.account_entities import (+ AccountChangeEmailNewEmailToken,+ AccountChangeEmailNewEmailVerifiedToken,+ AccountChangeEmailOldEmailToken,+ AccountChangeEmailOldEmailVerifiedToken,+ AccountChangeEmailPhase,+ AccountChangeEmailTokenData,+)+from services.entities.auth_entities import (+ ChangeEmailNewEmailToken,+ ChangeEmailNewEmailVerifiedToken,+ ChangeEmailOldEmailToken,+ ChangeEmailOldEmailVerifiedToken,+ ChangeEmailTokenData,+)+from tasks.mail_change_mail_task import send_change_mail_completed_notification_task, send_change_mail_task++_token_adapter: TypeAdapter[ChangeEmailTokenData] = TypeAdapter(ChangeEmailTokenData)+++class TokenManagerChangeEmailTokenGateway(ChangeEmailTokenGateway):+ @override+ def get(self, token: str) -> AccountChangeEmailTokenData | None:+ payload = TokenManager.get_token_data(token, "change_email")+ if payload is None:+ return None+ try:+ token_data = _token_adapter.validate_python(payload)+ except ValidationError:+ return None+ token_kwargs = {+ "account_id": token_data.account_id,+ "email": str(token_data.email),+ "old_email": str(token_data.old_email),+ "code": token_data.code,+ }+ if isinstance(token_data, ChangeEmailOldEmailToken):+ return AccountChangeEmailOldEmailToken(**token_kwargs)+ if isinstance(token_data, ChangeEmailOldEmailVerifiedToken):+ return AccountChangeEmailOldEmailVerifiedToken(**token_kwargs)+ if isinstance(token_data, ChangeEmailNewEmailToken):+ return AccountChangeEmailNewEmailToken(**token_kwargs)+ if isinstance(token_data, ChangeEmailNewEmailVerifiedToken):+ return AccountChangeEmailNewEmailVerifiedToken(**token_kwargs)+ return None++ @override+ def issue(self, token_data: AccountChangeEmailTokenData) -> str:+ return TokenManager.generate_token(+ account_id=token_data.account_id,+ email=token_data.email,+ token_type="change_email",+ additional_data={+ "old_email": token_data.old_email,+ "code": token_data.code,+ "email_change_phase": token_data.phase.value,+ },+ )++ @override+ def revoke(self, token: str) -> None:+ TokenManager.revoke_token(token, "change_email")+++class SecureChangeEmailCodeGenerator(ChangeEmailCodeGenerator):+ @override+ def generate(self) -> str:+ return "".join(str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6))+++class CeleryChangeEmailNotificationGateway(ChangeEmailNotificationGateway):+ @override+ def send_code(self, *, email: str, code: str, language: str, phase: AccountChangeEmailPhase) -> None:+ send_change_mail_task.delay(language=language, to=email, code=code, phase=phase)++ @override+ def send_completed(self, *, email: str, language: str) -> None:+ send_change_mail_completed_notification_task.delay(language=language, to=email)+++class RateLimiterChangeEmailSendLimiter(ChangeEmailSendLimiter):+ def __init__(self, *, rate_limiter: RateLimiter) -> None:+ self._rate_limiter = rate_limiter++ @override+ def is_limited(self, email: str) -> bool:+ return self._rate_limiter.is_rate_limited(email)++ @override+ def record(self, email: str) -> None:+ self._rate_limiter.increment_rate_limit(email)++ @property+ @override+ def retry_after_minutes(self) -> int:+ return int(self._rate_limiter.time_window / 60)+++class RedisChangeEmailSecurityGateway(ChangeEmailSecurityGateway):+ def __init__(+ self,+ *,+ redis: RedisClientWrapper,+ email_send_ip_limit_per_minute: int,+ verification_failure_limit: int,+ verification_lockout_duration: int,+ ) -> None:+ self._redis = redis+ self._email_send_ip_limit_per_minute = email_send_ip_limit_per_minute+ self._verification_failure_limit = verification_failure_limit+ self._verification_lockout_duration = verification_lockout_duration++ @override+ def is_ip_limited(self, ip_address: str) -> bool:+ minute_key = f"email_send_ip_limit_minute:{ip_address}"+ freeze_key = f"email_send_ip_limit_freeze:{ip_address}"+ hour_limit_key = f"email_send_ip_limit_hour:{ip_address}"+ try:+ if self._redis.get(freeze_key):+ return True++ current_minute_count = int(self._redis.get(minute_key) or 0)+ if current_minute_count > self._email_send_ip_limit_per_minute:+ hour_limit_count = int(self._redis.get(hour_limit_key) or 0)+ if hour_limit_count >= 1:+ self._redis.setex(freeze_key, 60 * 60, 1)+ return True+ if not self._redis.set(hour_limit_key, 1, ex=60 * 10, nx=True):+ self._redis.setex(freeze_key, 60 * 60, 1)+ return True++ self._redis.setex(minute_key, 60, current_minute_count + 1)+ self._redis.expire(minute_key, 60)+ return False+ except RedisError:+ return False++ @override+ def is_verification_limited(self, email: str) -> bool:+ try:+ count = self._redis.get(self._verification_key(email))+ return count is not None and int(count) > self._verification_failure_limit+ except RedisError:+ return False++ @override+ def record_verification_failure(self, email: str) -> None:+ try:+ key = self._verification_key(email)+ count = int(self._redis.get(key) or 0) + 1+ self._redis.setex(key, self._verification_lockout_duration, count)+ except RedisError:+ return None++ @override+ def reset_verification_failures(self, email: str) -> None:+ try:+ self._redis.delete(self._verification_key(email))+ except RedisError:+ return None++ @staticmethod+ def _verification_key(email: str) -> str:+ return f"change_email_error_rate_limit:{email}"+++class BillingAccountEmailPolicyGateway(AccountEmailPolicyGateway):+ def __init__(self, *, billing_enabled: bool) -> None:+ self._billing_enabled = billing_enabled++ @override+ def is_frozen(self, email: str) -> str | None:+ if not self._billing_enabled or not BillingService.is_email_in_freeze(email):+ return None+ return BillingService.get_email_freeze_type(email) or "freeze"diff --git a/api/services/account_change_email_ports.py b/api/services/account_change_email_ports.pynew file mode 100644index 00000000000..1ab48b57703--- /dev/null+++ b/api/services/account_change_email_ports.py@@ -0,0 +1,46 @@+"""External ports used by the change-email application service."""++from typing import Protocol++from services.entities.account_entities import AccountChangeEmailPhase, AccountChangeEmailTokenData+++class ChangeEmailTokenGateway(Protocol):+ def get(self, token: str) -> AccountChangeEmailTokenData | None: ...++ def issue(self, token_data: AccountChangeEmailTokenData) -> str: ...++ def revoke(self, token: str) -> None: ...+++class ChangeEmailCodeGenerator(Protocol):+ def generate(self) -> str: ...+++class ChangeEmailNotificationGateway(Protocol):+ def send_code(self, *, email: str, code: str, language: str, phase: AccountChangeEmailPhase) -> None: ...++ def send_completed(self, *, email: str, language: str) -> None: ...+++class ChangeEmailSendLimiter(Protocol):+ def is_limited(self, email: str) -> bool: ...++ def record(self, email: str) -> None: ...++ @property+ def retry_after_minutes(self) -> int: ...+++class ChangeEmailSecurityGateway(Protocol):+ def is_ip_limited(self, ip_address: str) -> bool: ...++ def is_verification_limited(self, email: str) -> bool: ...++ def record_verification_failure(self, email: str) -> None: ...++ def reset_verification_failures(self, email: str) -> None: ...+++class AccountEmailPolicyGateway(Protocol):+ def is_frozen(self, email: str) -> str | None: ...diff --git a/api/services/account_change_email_service.py b/api/services/account_change_email_service.pynew file mode 100644index 00000000000..e7e18d6f9c3--- /dev/null+++ b/api/services/account_change_email_service.py@@ -0,0 +1,201 @@+"""Application service implementing the account change-email state machine."""++from machinery.context import RequestContext+from services.account_change_email_ports import (+ AccountEmailPolicyGateway,+ ChangeEmailCodeGenerator,+ ChangeEmailNotificationGateway,+ ChangeEmailSecurityGateway,+ ChangeEmailSendLimiter,+ ChangeEmailTokenGateway,+)+from services.account_errors import (+ AccountEmailAlreadyInUseError,+ AccountEmailDomainSuspendedError,+ AccountEmailFrozenError,+ AccountNotFoundError,+ ChangeEmailSendIPLimitedError,+ ChangeEmailSendRateLimitError,+ ChangeEmailVerificationLimitError,+ InvalidChangeEmailAddressError,+ InvalidChangeEmailCodeError,+ InvalidChangeEmailTokenError,+)+from services.account_ports import AccountRepository+from services.entities.account_entities import (+ AccountChangeEmailNewEmailToken,+ AccountChangeEmailNewEmailVerifiedToken,+ AccountChangeEmailOldEmailToken,+ AccountChangeEmailOldEmailVerifiedToken,+ AccountChangeEmailPhase,+ AccountEmailResetStatus,+ AccountSnapshot,+ ChangeEmailVerification,+)+++class AccountChangeEmailService:+ def __init__(+ self,+ *,+ accounts: AccountRepository,+ tokens: ChangeEmailTokenGateway,+ codes: ChangeEmailCodeGenerator,+ notifications: ChangeEmailNotificationGateway,+ send_limits: ChangeEmailSendLimiter,+ security: ChangeEmailSecurityGateway,+ email_policy: AccountEmailPolicyGateway,+ ) -> None:+ self._accounts = accounts+ self._tokens = tokens+ self._codes = codes+ self._notifications = notifications+ self._send_limits = send_limits+ self._security = security+ self._email_policy = email_policy++ def send_code(+ self,+ context: RequestContext,+ *,+ requested_email: str,+ language: str,+ phase: str | None,+ predecessor_token: str | None,+ ip_address: str,+ ) -> str:+ if self._security.is_ip_limited(ip_address):+ raise ChangeEmailSendIPLimitedError++ account = self._accounts.get(context.account_id)+ if account is None:+ raise AccountNotFoundError++ email_for_sending = requested_email.lower()+ old_email = account.email+ send_phase = AccountChangeEmailPhase.OLD_EMAIL+ if phase == AccountChangeEmailPhase.NEW_EMAIL:+ send_phase = AccountChangeEmailPhase.NEW_EMAIL+ if predecessor_token is None:+ raise InvalidChangeEmailTokenError+ predecessor = self._tokens.get(predecessor_token)+ if not isinstance(predecessor, AccountChangeEmailOldEmailVerifiedToken):+ raise InvalidChangeEmailTokenError+ if not predecessor.is_bound_to_account(context.account_id):+ raise InvalidChangeEmailTokenError+ old_email = predecessor.email+ if old_email.lower() != account.email.lower():+ raise InvalidChangeEmailAddressError+ else:+ if email_for_sending != account.email.lower():+ raise InvalidChangeEmailAddressError+ email_for_sending = account.email++ if self._send_limits.is_limited(email_for_sending):+ raise ChangeEmailSendRateLimitError(self._send_limits.retry_after_minutes)++ code = self._codes.generate()+ token_data: AccountChangeEmailOldEmailToken | AccountChangeEmailNewEmailToken+ if send_phase == AccountChangeEmailPhase.OLD_EMAIL:+ token_data = AccountChangeEmailOldEmailToken(+ account_id=context.account_id,+ email=email_for_sending,+ old_email=old_email,+ code=code,+ )+ else:+ token_data = AccountChangeEmailNewEmailToken(+ account_id=context.account_id,+ email=email_for_sending,+ old_email=old_email,+ code=code,+ )+ token = self._tokens.issue(token_data)+ self._notifications.send_code(+ email=email_for_sending,+ code=code,+ language=language,+ phase=send_phase,+ )+ self._send_limits.record(email_for_sending)+ return token++ def verify_code(+ self,+ context: RequestContext,+ *,+ email: str,+ code: str,+ token: str,+ ) -> ChangeEmailVerification:+ normalized_email = email.lower()+ if self._security.is_verification_limited(normalized_email):+ raise ChangeEmailVerificationLimitError++ token_data = self._tokens.get(token)+ if token_data is None or not token_data.is_bound_to_account(context.account_id):+ raise InvalidChangeEmailTokenError+ normalized_token_email = token_data.email.lower()+ if normalized_email != normalized_token_email:+ raise InvalidChangeEmailAddressError+ if code != token_data.code:+ self._security.record_verification_failure(normalized_email)+ raise InvalidChangeEmailCodeError++ if isinstance(token_data, AccountChangeEmailOldEmailToken | AccountChangeEmailNewEmailToken):+ promoted = token_data.promote()+ else:+ raise InvalidChangeEmailTokenError++ self._tokens.revoke(token)+ promoted_token = self._tokens.issue(promoted)+ self._security.reset_verification_failures(normalized_email)+ return ChangeEmailVerification(email=normalized_token_email, token=promoted_token)++ def reset(+ self,+ context: RequestContext,+ *,+ new_email: str,+ token: str,+ ) -> AccountSnapshot:+ normalized_new_email = new_email.lower()+ freeze_type = self._email_policy.is_frozen(normalized_new_email)+ if freeze_type == "email_domain_suspended":+ raise AccountEmailDomainSuspendedError+ if freeze_type:+ raise AccountEmailFrozenError++ token_data = self._tokens.get(token)+ if not isinstance(token_data, AccountChangeEmailNewEmailVerifiedToken):+ raise InvalidChangeEmailTokenError+ if not token_data.is_bound_to_account(context.account_id):+ raise InvalidChangeEmailTokenError+ if token_data.email.lower() != normalized_new_email:+ raise InvalidChangeEmailTokenError++ result = self._accounts.reset_email(+ context.account_id,+ expected_old_email=token_data.old_email,+ new_email=normalized_new_email,+ )+ if result.status == AccountEmailResetStatus.EMAIL_IN_USE:+ raise AccountEmailAlreadyInUseError+ if result.status in {AccountEmailResetStatus.ACCOUNT_NOT_FOUND, AccountEmailResetStatus.EMAIL_CHANGED}:+ raise AccountNotFoundError+ if result.account is None:+ raise RuntimeError("Account repository returned an updated result without an account")++ self._tokens.revoke(token)+ self._notifications.send_completed(email=normalized_new_email, language="en-US")+ return result.account++ def ensure_available(self, email: str) -> None:+ normalized_email = email.lower()+ freeze_type = self._email_policy.is_frozen(normalized_email)+ if freeze_type == "email_domain_suspended":+ raise AccountEmailDomainSuspendedError+ if freeze_type:+ raise AccountEmailFrozenError+ if self._accounts.email_exists(normalized_email):+ raise AccountEmailAlreadyInUseErrordiff --git a/api/services/account_deletion_adapters.py b/api/services/account_deletion_adapters.pyindex cf22354ab9d..bcf705c5924 100644--- a/api/services/account_deletion_adapters.py+++ b/api/services/account_deletion_adapters.py@@ -2,8 +2,7 @@import secretsfrom collections.abc import Sequence-from dataclasses import dataclass-from typing import TYPE_CHECKING, cast, override+from typing import overridefrom libs.helper import RateLimiter, TokenManagerfrom services.account_errors import AccountDeletionRateLimitError@@ -18,22 +17,14 @@ from services.entities.account_entities import AccountDeletionChallengefrom tasks.delete_account_task import delete_account_taskfrom tasks.mail_account_deletion_task import send_account_deletion_verification_code-if TYPE_CHECKING:- from models.account import Account---@dataclass(frozen=True, slots=True)-class _TokenAccount:- id: str- email: str-class TokenManagerAccountDeletionVerificationGateway(AccountDeletionVerificationGateway):@overridedef create(self, *, account_id: str, email: str) -> AccountDeletionChallenge:code = "".join(str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6))token = TokenManager.generate_token(- account=cast("Account", _TokenAccount(id=account_id, email=email)),+ account_id=account_id,+ email=email,token_type="account_deletion",additional_data={"code": code},)diff --git a/api/services/account_errors.py b/api/services/account_errors.pyindex bd251f2cff4..1146fab3ff3 100644--- a/api/services/account_errors.py+++ b/api/services/account_errors.py@@ -43,3 +43,43 @@ class AccountDeletionRateLimitError(AccountApplicationError):def __init__(self, retry_after_minutes: int) -> None:super().__init__(retry_after_minutes)self.retry_after_minutes = retry_after_minutes+++class ChangeEmailSendIPLimitedError(AccountApplicationError):+ """The caller IP exceeded the email-send policy."""+++class ChangeEmailSendRateLimitError(AccountApplicationError):+ """Too many change-email messages were requested for the address."""++ def __init__(self, retry_after_minutes: int) -> None:+ super().__init__(retry_after_minutes)+ self.retry_after_minutes = retry_after_minutes+++class InvalidChangeEmailTokenError(AccountApplicationError):+ """The token is absent, malformed, in the wrong phase, or bound elsewhere."""+++class InvalidChangeEmailAddressError(AccountApplicationError):+ """The request address does not match the account or token state."""+++class ChangeEmailVerificationLimitError(AccountApplicationError):+ """Too many invalid verification-code attempts were made."""+++class InvalidChangeEmailCodeError(AccountApplicationError):+ """The verification code does not match the current token."""+++class AccountEmailFrozenError(AccountApplicationError):+ """The target email is temporarily frozen by account policy."""+++class AccountEmailDomainSuspendedError(AccountEmailFrozenError):+ """The target email belongs to a suspended domain."""+++class AccountEmailAlreadyInUseError(AccountApplicationError):+ """The target email already belongs to an account."""diff --git a/api/services/account_ports.py b/api/services/account_ports.pyindex 04b99afa568..39afd92bd1f 100644--- a/api/services/account_ports.py+++ b/api/services/account_ports.py@@ -6,6 +6,7 @@ from typing import Protocolfrom services.entities.account_entities import (AccountCredentials,AccountDeletionChallenge,+ AccountEmailResetResult,AccountInitialization,AccountInitializationResult,AccountIntegrationSnapshot,@@ -33,6 +34,10 @@ class AccountRepository(Protocol):workspace_id: str | None,) -> AccountInitializationResult: ...+ def email_exists(self, email: str) -> bool: ...++ def reset_email(self, account_id: str, *, expected_old_email: str, new_email: str) -> AccountEmailResetResult: ...+class AccountIntegrationRepository(Protocol):def list_for_account(self, account_id: str) -> list[AccountIntegrationSnapshot]: ...diff --git a/api/services/account_service.py b/api/services/account_service.pyindex b0fbfbaf557..61ebc324f23 100644--- a/api/services/account_service.py+++ b/api/services/account_service.py@@ -830,7 +830,10 @@ class AccountService:code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])additional_data["code"] = codetoken = TokenManager.generate_token(- account=account, email=email, token_type="reset_password", additional_data=additional_data+ account_id=account.id if account else None,+ email=email,+ token_type="reset_password",+ additional_data=additional_data,)return code, token@@ -854,7 +857,7 @@ class AccountService:account: Account,) -> str:token = TokenManager.generate_token(- account=account,+ account_id=account.id,email=token_data.email,token_type="change_email",additional_data=token_data.to_token_manager_payload(),@@ -873,7 +876,10 @@ class AccountService:code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])additional_data["code"] = codetoken = TokenManager.generate_token(- account=account, email=email, token_type="owner_transfer", additional_data=additional_data+ account_id=account.id if account else None,+ email=email,+ token_type="owner_transfer",+ additional_data=additional_data,)return code, tokendiff --git a/api/services/entities/account_entities.py b/api/services/entities/account_entities.pyindex 21a4d9c802d..7d80c122817 100644--- a/api/services/entities/account_entities.py+++ b/api/services/entities/account_entities.py@@ -1,5 +1,7 @@"""Framework-neutral contracts for Console account use cases."""+from __future__ import annotations+from dataclasses import dataclassfrom datetime import datetimefrom enum import StrEnum@@ -93,3 +95,84 @@ class AccountInitializationResult:class AccountDeletionChallenge:token: strcode: str+++@dataclass(frozen=True, slots=True)+class ChangeEmailVerification:+ email: str+ token: str+++class AccountEmailResetStatus(StrEnum):+ UPDATED = "updated"+ ACCOUNT_NOT_FOUND = "account_not_found"+ EMAIL_CHANGED = "email_changed"+ EMAIL_IN_USE = "email_in_use"+++@dataclass(frozen=True, slots=True)+class AccountEmailResetResult:+ status: AccountEmailResetStatus+ account: AccountSnapshot | None = None+++class AccountChangeEmailPhase(StrEnum):+ OLD_EMAIL = "old_email"+ OLD_EMAIL_VERIFIED = "old_email_verified"+ NEW_EMAIL = "new_email"+ NEW_EMAIL_VERIFIED = "new_email_verified"+++@dataclass(frozen=True, slots=True)+class AccountChangeEmailToken:+ account_id: str+ email: str+ old_email: str+ code: str++ def is_bound_to_account(self, account_id: str) -> bool:+ return self.account_id == account_id+++@dataclass(frozen=True, slots=True)+class AccountChangeEmailOldEmailToken(AccountChangeEmailToken):+ phase = AccountChangeEmailPhase.OLD_EMAIL++ def promote(self) -> AccountChangeEmailOldEmailVerifiedToken:+ return AccountChangeEmailOldEmailVerifiedToken(+ account_id=self.account_id,+ email=self.email,+ old_email=self.old_email,+ code=self.code,+ )+++@dataclass(frozen=True, slots=True)+class AccountChangeEmailOldEmailVerifiedToken(AccountChangeEmailToken):+ phase = AccountChangeEmailPhase.OLD_EMAIL_VERIFIED+++@dataclass(frozen=True, slots=True)+class AccountChangeEmailNewEmailToken(AccountChangeEmailToken):+ phase = AccountChangeEmailPhase.NEW_EMAIL++ def promote(self) -> AccountChangeEmailNewEmailVerifiedToken:+ return AccountChangeEmailNewEmailVerifiedToken(+ account_id=self.account_id,+ email=self.email,+ old_email=self.old_email,+ code=self.code,+ )+++@dataclass(frozen=True, slots=True)+class AccountChangeEmailNewEmailVerifiedToken(AccountChangeEmailToken):+ phase = AccountChangeEmailPhase.NEW_EMAIL_VERIFIED+++type AccountChangeEmailTokenData = (+ AccountChangeEmailOldEmailToken+ | AccountChangeEmailOldEmailVerifiedToken+ | AccountChangeEmailNewEmailToken+ | AccountChangeEmailNewEmailVerifiedToken+)diff --git a/api/services/webapp_auth_service.py b/api/services/webapp_auth_service.pyindex 3373a5ddf66..d05f04f7dd4 100644--- a/api/services/webapp_auth_service.py+++ b/api/services/webapp_auth_service.py@@ -74,7 +74,10 @@ class WebAppAuthService:code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])token = TokenManager.generate_token(- account=account, email=email, token_type="email_code_login", additional_data={"code": code}+ account_id=account.id if account else None,+ email=email,+ token_type="email_code_login",+ additional_data={"code": code},)send_email_code_login_mail_task.delay(language=language,diff --git a/api/tests/test_containers_integration_tests/services/test_webapp_auth_service.py b/api/tests/test_containers_integration_tests/services/test_webapp_auth_service.pyindex 52d1fde7927..d47eaa0f8c5 100644--- a/api/tests/test_containers_integration_tests/services/test_webapp_auth_service.py+++ b/api/tests/test_containers_integration_tests/services/test_webapp_auth_service.py@@ -497,7 +497,7 @@ class TestWebAppAuthService:# Verify token generation parameterstoken_call_args = mock_external_service_dependencies["token_manager"].generate_token.call_args- assert token_call_args[1]["account"] == account+ assert token_call_args[1]["account_id"] == account.idassert token_call_args[1]["email"] == account.emailassert token_call_args[1]["token_type"] == "email_code_login"assert "code" in token_call_args[1]["additional_data"]@@ -537,7 +537,7 @@ class TestWebAppAuthService:# Verify token generation parameterstoken_call_args = mock_external_service_dependencies["token_manager"].generate_token.call_args- assert token_call_args[1]["account"] is None+ assert token_call_args[1]["account_id"] is Noneassert token_call_args[1]["email"] == test_emailassert token_call_args[1]["token_type"] == "email_code_login"assert "code" in token_call_args[1]["additional_data"]diff --git a/api/tests/unit_tests/controllers/console/test_workspace_account.py b/api/tests/unit_tests/controllers/console/test_workspace_account.pyindex 68a1b4dc397..fa61aed18db 100644--- a/api/tests/unit_tests/controllers/console/test_workspace_account.py+++ b/api/tests/unit_tests/controllers/console/test_workspace_account.py@@ -1,13 +1,13 @@import inspect-from contextlib import contextmanagerfrom types import SimpleNamespacefrom unittest.mock import MagicMock, patchfrom uuid import NAMESPACE_URL, uuid5import pytestfrom flask import Flask-from sqlalchemy.orm import Session, scoped_session, sessionmaker+from sqlalchemy.orm import Session+from controllers.console.auth.error import InvalidTokenErrorfrom controllers.console.error import EmailDomainSuspendedErrorfrom controllers.console.workspace.account import (AccountDeleteUpdateFeedbackApi,@@ -17,9 +17,12 @@ from controllers.console.workspace.account import (CheckEmailUnique,EducationApi,)-from models import Account, AccountIntegrate, AccountStatus, Tenant, TenantAccountJoin+from machinery.context import RequestContext+from models import Account, AccountStatus, Tenant, TenantAccountJoinfrom models.account import TenantAccountRole+from services import account_errorsfrom services.account_service import AccountService+from services.entities.account_entities import ChangeEmailVerificationfrom services.entities.auth_entities import (ChangeEmailNewEmailToken,ChangeEmailNewEmailVerifiedToken,@@ -74,16 +77,6 @@ def _persist_account_with_tenant(session: Session, email: str, account_name: strreturn account, tenant-@contextmanager-def _bind_database_session(session: Session):- database_session = scoped_session(sessionmaker(bind=session.get_bind(), expire_on_commit=False))- try:- with patch("extensions.ext_database.db.session", database_session):- yield database_session- finally:- database_session.remove()--def _build_change_email_token(phase: str,*,@@ -128,528 +121,147 @@ class TestEducationApi:mock_activate.assert_called_once_with(account, "education-token", "Dify University", "Student")-class TestChangeEmailSend:- @patch("controllers.console.workspace.account.AccountService.send_change_email_email")- @patch("controllers.console.workspace.account.AccountService.is_email_send_ip_limit", return_value=False)- @patch("controllers.console.workspace.account.extract_remote_ip", return_value="127.0.0.1")- def test_should_reject_old_email_phase_when_request_email_does_not_match_current_user(- self,- mock_extract_ip,- mock_is_ip_limit,- mock_send_email,- app: Flask,- ):- from controllers.console.auth.error import InvalidEmailError-- current_user = _build_account("[email protected]", "acc1")-- with app.test_request_context(- "/account/change-email",- method="POST",- json={"email": "[email protected]", "language": "en-US", "phase": "old_email"},- ):- method = inspect.unwrap(ChangeEmailSendEmailApi().post)- with pytest.raises(InvalidEmailError):- method(ChangeEmailSendEmailApi(), current_user)+def _change_email_context(account_id: str = "acc") -> RequestContext:+ return RequestContext(+ request_id="request-1",+ trace_id="trace-1",+ account_id=account_id,+ active_workspace_id="workspace-1",+ )- mock_send_email.assert_not_called()- @patch("controllers.console.workspace.account.AccountService.get_change_email_data")- @patch("controllers.console.workspace.account.AccountService.send_change_email_email")- @patch("controllers.console.workspace.account.AccountService.is_email_send_ip_limit", return_value=False)- @patch("controllers.console.workspace.account.extract_remote_ip", return_value="127.0.0.1")- def test_should_normalize_new_email_phase(- self,- mock_extract_ip: MagicMock,- mock_is_ip_limit: MagicMock,- mock_send_email: MagicMock,- mock_get_change_data: MagicMock,- app: Flask,- ):- mock_account = _build_account("[email protected]", "acc1")- mock_get_change_data.return_value = _build_change_email_token(- ChangeEmailPhase.OLD_EMAIL_VERIFIED,- account_id="acc1",- email="[email protected]",- old_email="[email protected]",- )- mock_send_email.return_value = "token-abc"+class TestChangeEmailControllers:+ def test_send_delegates_parsed_request_to_application_service(self, app: Flask):+ change_email = MagicMock()+ change_email.send_code.return_value = "change-token"+ context = _change_email_context()+ payload = {+ "email": "[email protected]",+ "language": "zh-Hans",+ "phase": "new_email",+ "token": "verified-old-token",+ }- with app.test_request_context(- "/account/change-email",- method="POST",- json={"email": "[email protected]", "language": "en-US", "phase": "new_email", "token": "token-123"},+ with (+ app.test_request_context(+ "/account/change-email",+ method="POST",+ json=payload,+ environ_base={"REMOTE_ADDR": "127.0.0.1"},+ ),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),+ ),):api = ChangeEmailSendEmailApi()- method = inspect.unwrap(api.post)- response = method(api, mock_account)-- assert response == {"result": "success", "data": "token-abc"}- mock_send_email.assert_called_once_with(- account=mock_account,- email="[email protected]",- old_email="[email protected]",- language="en-US",- phase=AccountService.CHANGE_EMAIL_PHASE_NEW,- )- mock_extract_ip.assert_called_once()- mock_is_ip_limit.assert_called_once_with("127.0.0.1")-- @patch("controllers.console.workspace.account.AccountService.get_change_email_data")- @patch("controllers.console.workspace.account.AccountService.send_change_email_email")- @patch("controllers.console.workspace.account.AccountService.is_email_send_ip_limit", return_value=False)- @patch("controllers.console.workspace.account.extract_remote_ip", return_value="127.0.0.1")- def test_should_reject_new_email_phase_when_token_phase_is_not_old_verified(- self,- mock_extract_ip: MagicMock,- mock_is_ip_limit: MagicMock,- mock_send_email: MagicMock,- mock_get_change_data: MagicMock,- app: Flask,- ):- """GHSA-4q3w-q5mc-45rq: a phase-1 token must not unlock the new-email send step."""- from controllers.console.auth.error import InvalidTokenError-- mock_account = _build_account("[email protected]", "acc1")- mock_get_change_data.return_value = _build_change_email_token(- AccountService.CHANGE_EMAIL_PHASE_OLD,- account_id="acc1",- email="[email protected]",- old_email="[email protected]",+ response = inspect.unwrap(api.post)(api, context)++ assert response == {"result": "success", "data": "change-token"}+ change_email.send_code.assert_called_once_with(+ context,+ requested_email="[email protected]",+ language="zh-Hans",+ phase="new_email",+ predecessor_token="verified-old-token",+ ip_address="127.0.0.1",)- with app.test_request_context(- "/account/change-email",- method="POST",- json={"email": "[email protected]", "language": "en-US", "phase": "new_email", "token": "token-123"},- ):- api = ChangeEmailSendEmailApi()- method = inspect.unwrap(api.post)- with pytest.raises(InvalidTokenError):- method(api, mock_account)-- mock_send_email.assert_not_called()-- @patch("controllers.console.workspace.account.AccountService.get_change_email_data")- @patch("controllers.console.workspace.account.AccountService.send_change_email_email")- @patch("controllers.console.workspace.account.AccountService.is_email_send_ip_limit", return_value=False)- @patch("controllers.console.workspace.account.extract_remote_ip", return_value="127.0.0.1")- def test_should_reject_new_email_phase_when_token_account_id_does_not_match_current_user(- self,- mock_extract_ip: MagicMock,- mock_is_ip_limit: MagicMock,- mock_send_email: MagicMock,- mock_get_change_data: MagicMock,- app: Flask,- ):- from controllers.console.auth.error import InvalidTokenError-- mock_account = _build_account("[email protected]", "acc1")- mock_get_change_data.return_value = _build_change_email_token(- ChangeEmailPhase.OLD_EMAIL_VERIFIED,- account_id="other-account",- email="[email protected]",- old_email="[email protected]",- )+ def test_send_maps_invalid_state_to_http_error(self, app: Flask):+ change_email = MagicMock()+ change_email.send_code.side_effect = account_errors.InvalidChangeEmailTokenError- with app.test_request_context(- "/account/change-email",- method="POST",- json={"email": "[email protected]", "language": "en-US", "phase": "new_email", "token": "token-123"},+ with (+ app.test_request_context(+ "/account/change-email",+ method="POST",+ json={"email": "[email protected]", "phase": "new_email"},+ ),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),+ ),):api = ChangeEmailSendEmailApi()method = inspect.unwrap(api.post)with pytest.raises(InvalidTokenError):- method(api, mock_account)-- mock_send_email.assert_not_called()---class TestChangeEmailValidity:- @patch("controllers.console.workspace.account.AccountService.reset_change_email_error_rate_limit")- @patch("controllers.console.workspace.account.AccountService.generate_change_email_token")- @patch("controllers.console.workspace.account.AccountService.revoke_change_email_token")- @patch("controllers.console.workspace.account.AccountService.add_change_email_error_rate_limit")- @patch("controllers.console.workspace.account.AccountService.get_change_email_data")- @patch("controllers.console.workspace.account.AccountService.is_change_email_error_rate_limit")- def test_should_validate_with_normalized_email(- self,- mock_is_rate_limit,- mock_get_data,- mock_add_rate,- mock_revoke_token,- mock_generate_token,- mock_reset_rate,- app: Flask,- ):- mock_account = _build_account("[email protected]", "acc2")- mock_is_rate_limit.return_value = False- mock_get_data.return_value = _build_change_email_token(- AccountService.CHANGE_EMAIL_PHASE_OLD,- account_id="acc2",- email="[email protected]",- old_email="[email protected]",- )- mock_generate_token.return_value = "new-token"-- with app.test_request_context(- "/account/change-email/validity",- method="POST",- json={"email": "[email protected]", "code": "1234", "token": "token-123"},- ):- api = ChangeEmailCheckApi()- method = inspect.unwrap(api.post)- response = method(api, mock_account)+ method(api, _change_email_context())- assert response == {"is_valid": True, "email": "[email protected]", "token": "new-token"}- mock_is_rate_limit.assert_called_once_with("[email protected]")- mock_add_rate.assert_not_called()- mock_revoke_token.assert_called_once_with("token-123")- mock_generate_token.assert_called_once_with(- _build_change_email_token(- ChangeEmailPhase.OLD_EMAIL_VERIFIED,- account_id="acc2",- email="[email protected]",- old_email="[email protected]",- ),- mock_account,- )- mock_reset_rate.assert_called_once_with("[email protected]")-- @patch("controllers.console.workspace.account.AccountService.reset_change_email_error_rate_limit")- @patch("controllers.console.workspace.account.AccountService.generate_change_email_token")- @patch("controllers.console.workspace.account.AccountService.revoke_change_email_token")- @patch("controllers.console.workspace.account.AccountService.add_change_email_error_rate_limit")- @patch("controllers.console.workspace.account.AccountService.get_change_email_data")- @patch("controllers.console.workspace.account.AccountService.is_change_email_error_rate_limit")- def test_should_upgrade_new_phase_token_to_new_verified(- self,- mock_is_rate_limit,- mock_get_data,- mock_add_rate,- mock_revoke_token,- mock_generate_token,- mock_reset_rate,- app: Flask,- ):- current_user = _build_account("[email protected]", "acc")- mock_is_rate_limit.return_value = False- mock_get_data.return_value = _build_change_email_token(- AccountService.CHANGE_EMAIL_PHASE_NEW,- account_id="acc",+ def test_validity_serializes_promoted_token(self, app: Flask):+ change_email = MagicMock()+ change_email.verify_code.return_value = ChangeEmailVerification(email="[email protected]",- old_email="[email protected]",+ token="verified-token",)- mock_generate_token.return_value = "new-verified-token"+ context = _change_email_context()- with app.test_request_context(- "/account/change-email/validity",- method="POST",- json={"email": "[email protected]", "code": "1234", "token": "token-123"},- ):- api = ChangeEmailCheckApi()- method = inspect.unwrap(api.post)- response = method(api, current_user)-- assert response == {"is_valid": True, "email": "[email protected]", "token": "new-verified-token"}- mock_generate_token.assert_called_once_with(- _build_change_email_token(- ChangeEmailPhase.NEW_EMAIL_VERIFIED,- account_id="acc",- email="[email protected]",- old_email="[email protected]",+ with (+ app.test_request_context(+ "/account/change-email/validity",+ method="POST",+ json={"email": "[email protected]", "code": "123456", "token": "pending-token"},+ ),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),),- current_user,- )-- @patch("controllers.console.workspace.account.AccountService.reset_change_email_error_rate_limit")- @patch("controllers.console.workspace.account.AccountService.generate_change_email_token")- @patch("controllers.console.workspace.account.AccountService.revoke_change_email_token")- @patch("controllers.console.workspace.account.AccountService.add_change_email_error_rate_limit")- @patch("controllers.console.workspace.account.AccountService.get_change_email_data")- @patch("controllers.console.workspace.account.AccountService.is_change_email_error_rate_limit")- def test_should_reject_validity_when_token_is_already_verified(- self,- mock_is_rate_limit,- mock_get_data,- mock_add_rate,- mock_revoke_token,- mock_generate_token,- mock_reset_rate,- app: Flask,- ):- from controllers.console.auth.error import InvalidTokenError-- current_user = _build_account("[email protected]", "acc")- mock_is_rate_limit.return_value = False- mock_get_data.return_value = _build_change_email_token(- ChangeEmailPhase.OLD_EMAIL_VERIFIED,- account_id="acc",- email="[email protected]",- old_email="[email protected]",- )-- with app.test_request_context(- "/account/change-email/validity",- method="POST",- json={"email": "[email protected]", "code": "1234", "token": "token-123"},):api = ChangeEmailCheckApi()- method = inspect.unwrap(api.post)- with pytest.raises(InvalidTokenError):- method(api, current_user)-- mock_revoke_token.assert_not_called()- mock_generate_token.assert_not_called()-- @patch("controllers.console.workspace.account.AccountService.reset_change_email_error_rate_limit")- @patch("controllers.console.workspace.account.AccountService.generate_change_email_token")- @patch("controllers.console.workspace.account.AccountService.revoke_change_email_token")- @patch("controllers.console.workspace.account.AccountService.add_change_email_error_rate_limit")- @patch("controllers.console.workspace.account.AccountService.get_change_email_data")- @patch("controllers.console.workspace.account.AccountService.is_change_email_error_rate_limit")- def test_should_reject_validity_when_token_account_id_does_not_match_current_user(- self,- mock_is_rate_limit,- mock_get_data,- mock_add_rate,- mock_revoke_token,- mock_generate_token,- mock_reset_rate,- app: Flask,- ):- from controllers.console.auth.error import InvalidTokenError-- current_user = _build_account("[email protected]", "acc")- mock_is_rate_limit.return_value = False- mock_get_data.return_value = _build_change_email_token(- AccountService.CHANGE_EMAIL_PHASE_NEW,- account_id="other-account",- email="[email protected]",- old_email="[email protected]",+ response = inspect.unwrap(api.post)(api, context)++ assert response == {"is_valid": True, "email": "[email protected]", "token": "verified-token"}+ change_email.verify_code.assert_called_once_with(+ context,+ email="[email protected]",+ code="123456",+ token="pending-token",)- with app.test_request_context(- "/account/change-email/validity",- method="POST",- json={"email": "[email protected]", "code": "1234", "token": "token-123"},- ):- api = ChangeEmailCheckApi()- method = inspect.unwrap(api.post)- with pytest.raises(InvalidTokenError):- method(api, current_user)-- mock_revoke_token.assert_not_called()- mock_generate_token.assert_not_called()-+ def test_reset_returns_updated_account(self, app: Flask):+ change_email = MagicMock()+ updated_account = _build_account("[email protected]", "acc")+ change_email.reset.return_value = updated_account+ context = _change_email_context()-class TestChangeEmailReset:- @patch(- "controllers.console.workspace.account.AccountService.get_account_freeze_type",- return_value="email_domain_suspended",- )- def test_should_reject_suspended_email_domain(self, mock_get_freeze_type, app: Flask):- current_user = _build_account("[email protected]", "email-reset-account")-- with app.test_request_context(- "/account/change-email/reset",- method="POST",- json={"new_email": "[email protected]", "token": "token-123"},- ):- api = ChangeEmailResetApi()- method = inspect.unwrap(api.post)- with pytest.raises(EmailDomainSuspendedError):- method(api, current_user)-- mock_get_freeze_type.assert_called_once_with("[email protected]")-- @patch("controllers.console.workspace.account.AccountService.send_change_email_completed_notify_email")- @patch("controllers.console.workspace.account.AccountService.revoke_change_email_token")- @patch("controllers.console.workspace.account.AccountService.get_change_email_data")- @patch("controllers.console.workspace.account.AccountService.get_account_freeze_type")- @pytest.mark.parametrize(- "sqlite_session",- [(Account, Tenant, TenantAccountJoin, AccountIntegrate)],- indirect=True,- )- def test_should_normalize_new_email_before_update(- self,- mock_is_freeze: MagicMock,- mock_get_data: MagicMock,- mock_revoke_token: MagicMock,- mock_send_notify: MagicMock,- app: Flask,- sqlite_session: Session,- ):- mock_is_freeze.return_value = False-- with _bind_database_session(sqlite_session) as database_session:- current_user, _ = _persist_account_with_tenant(- database_session(),- "[email protected]",- "email-reset-account",- )- account_integration = AccountIntegrate(- account_id=current_user.id,- provider="google",- open_id="google-user",- encrypted_token="encrypted-token",- )- database_session.add(account_integration)- database_session.commit()- mock_get_data.return_value = _build_change_email_token(- ChangeEmailPhase.NEW_EMAIL_VERIFIED,- account_id=current_user.id,- email="[email protected]",- old_email="[email protected]",- )-- with app.test_request_context(+ with (+ app.test_request_context("/account/change-email/reset",method="POST",- json={"new_email": "[email protected]", "token": "token-123"},- ):- api = ChangeEmailResetApi()- method = inspect.unwrap(api.post)- response = method(api, current_user)-- sqlite_session.expire_all()- persisted_account = sqlite_session.get(Account, current_user.id)- assert response["email"] == "[email protected]"- assert persisted_account is not None- assert persisted_account.email == "[email protected]"- assert sqlite_session.get(AccountIntegrate, account_integration.id) is None- mock_is_freeze.assert_called_once_with("[email protected]")- mock_revoke_token.assert_called_once_with("token-123")- mock_send_notify.assert_called_once_with(email="[email protected]")-- @patch("controllers.console.workspace.account.AccountService.send_change_email_completed_notify_email")- @patch("controllers.console.workspace.account.AccountService.update_account_email")- @patch("controllers.console.workspace.account.AccountService.revoke_change_email_token")- @patch("controllers.console.workspace.account.AccountService.get_change_email_data")- @patch("controllers.console.workspace.account.AccountService.check_email_unique")- @patch("controllers.console.workspace.account.AccountService.get_account_freeze_type")- def test_should_reject_reset_when_token_phase_is_not_new_verified(- self,- mock_is_freeze: MagicMock,- mock_check_unique: MagicMock,- mock_get_data: MagicMock,- mock_revoke_token: MagicMock,- mock_update_account: MagicMock,- mock_send_notify: MagicMock,- app: Flask,- ):- """GHSA-4q3w-q5mc-45rq PoC: phase-1 token must not be usable against /reset."""- from controllers.console.auth.error import InvalidTokenError-- current_user = _build_account("[email protected]", "acc3")- mock_is_freeze.return_value = False- mock_check_unique.return_value = True- mock_get_data.return_value = _build_change_email_token(- AccountService.CHANGE_EMAIL_PHASE_OLD,- account_id="acc3",- email="[email protected]",- old_email="[email protected]",- )-- with app.test_request_context(- "/account/change-email/reset",- method="POST",- json={"new_email": "[email protected]", "token": "token-from-step1"},+ json={"new_email": "[email protected]", "token": "verified-token"},+ ),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),+ ),):api = ChangeEmailResetApi()- method = inspect.unwrap(api.post)- with pytest.raises(InvalidTokenError):- method(api, current_user)-- mock_revoke_token.assert_not_called()- mock_update_account.assert_not_called()- mock_send_notify.assert_not_called()-- @patch("controllers.console.workspace.account.AccountService.send_change_email_completed_notify_email")- @patch("controllers.console.workspace.account.AccountService.update_account_email")- @patch("controllers.console.workspace.account.AccountService.revoke_change_email_token")- @patch("controllers.console.workspace.account.AccountService.get_change_email_data")- @patch("controllers.console.workspace.account.AccountService.check_email_unique")- @patch("controllers.console.workspace.account.AccountService.get_account_freeze_type")- def test_should_reject_reset_when_token_email_differs_from_payload_new_email(- self,- mock_is_freeze: MagicMock,- mock_check_unique: MagicMock,- mock_get_data: MagicMock,- mock_revoke_token: MagicMock,- mock_update_account: MagicMock,- mock_send_notify: MagicMock,- app: Flask,- ):- """A verified token for address A must not be replayed to change to address B."""- from controllers.console.auth.error import InvalidTokenError+ response = inspect.unwrap(api.post)(api, context)- current_user = _build_account("[email protected]", "acc3")- mock_is_freeze.return_value = False- mock_check_unique.return_value = True- mock_get_data.return_value = _build_change_email_token(- ChangeEmailPhase.NEW_EMAIL_VERIFIED,- account_id="acc3",- email="[email protected]",- old_email="[email protected]",+ assert response["email"] == "[email protected]"+ change_email.reset.assert_called_once_with(+ context,+ new_email="[email protected]",+ token="verified-token",)- with app.test_request_context(- "/account/change-email/reset",- method="POST",- json={"new_email": "[email protected]", "token": "token-verified"},- ):- api = ChangeEmailResetApi()- method = inspect.unwrap(api.post)- with pytest.raises(InvalidTokenError):- method(api, current_user)-- mock_revoke_token.assert_not_called()- mock_update_account.assert_not_called()- mock_send_notify.assert_not_called()-- @patch("controllers.console.workspace.account.AccountService.send_change_email_completed_notify_email")- @patch("controllers.console.workspace.account.AccountService.update_account_email")- @patch("controllers.console.workspace.account.AccountService.revoke_change_email_token")- @patch("controllers.console.workspace.account.AccountService.get_change_email_data")- @patch("controllers.console.workspace.account.AccountService.check_email_unique")- @patch("controllers.console.workspace.account.AccountService.get_account_freeze_type")- def test_should_reject_reset_when_token_account_id_does_not_match_current_user(- self,- mock_is_freeze: MagicMock,- mock_check_unique: MagicMock,- mock_get_data: MagicMock,- mock_revoke_token: MagicMock,- mock_update_account: MagicMock,- mock_send_notify: MagicMock,- app: Flask,- ):- from controllers.console.auth.error import InvalidTokenError-- current_user = _build_account("[email protected]", "acc3")- mock_is_freeze.return_value = False- mock_check_unique.return_value = True- mock_get_data.return_value = _build_change_email_token(- ChangeEmailPhase.NEW_EMAIL_VERIFIED,- account_id="other-account",- email="[email protected]",- old_email="[email protected]",- )+ def test_reset_maps_suspended_email_domain(self, app: Flask):+ change_email = MagicMock()+ change_email.reset.side_effect = account_errors.AccountEmailDomainSuspendedError- with app.test_request_context(- "/account/change-email/reset",- method="POST",- json={"new_email": "[email protected]", "token": "token-verified"},+ with (+ app.test_request_context(+ "/account/change-email/reset",+ method="POST",+ json={"new_email": "[email protected]", "token": "verified-token"},+ ),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),+ ),):api = ChangeEmailResetApi()- method = inspect.unwrap(api.post)- with pytest.raises(InvalidTokenError):- method(api, current_user)-- mock_revoke_token.assert_not_called()- mock_update_account.assert_not_called()- mock_send_notify.assert_not_called()+ with pytest.raises(EmailDomainSuspendedError):+ inspect.unwrap(api.post)(api, _change_email_context())class TestAccountServiceSendChangeEmailEmail:@@ -757,33 +369,44 @@ class TestAccountDeletionFeedback:class TestCheckEmailUnique:- @patch("controllers.console.workspace.account.AccountService.get_account_freeze_type")- @pytest.mark.parametrize(- "sqlite_session",- [(Account, Tenant, TenantAccountJoin)],- indirect=True,- )- def test_should_normalize_email(- self,- mock_is_freeze: MagicMock,- app: Flask,- sqlite_session: Session,- ):- mock_is_freeze.return_value = False+ def test_delegates_to_email_availability_policy(self, app: Flask):+ change_email = MagicMock()- with _bind_database_session(sqlite_session) as database_session:- _persist_account_with_tenant(database_session(), "[email protected]", "uniqueness-account")- with app.test_request_context(+ with (+ app.test_request_context("/account/change-email/check-email-unique",method="POST",json={"email": "[email protected]"},- ):- api = CheckEmailUnique()- method = inspect.unwrap(api.post)- response = method(api)+ ),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),+ ),+ ):+ api = CheckEmailUnique()+ response = inspect.unwrap(api.post)(api)assert response == {"result": "success"}- mock_is_freeze.assert_called_once_with("[email protected]")+ change_email.ensure_available.assert_called_once_with("[email protected]")++ def test_maps_suspended_email_domain(self, app: Flask):+ change_email = MagicMock()+ change_email.ensure_available.side_effect = account_errors.AccountEmailDomainSuspendedError++ with (+ app.test_request_context(+ "/account/change-email/check-email-unique",+ method="POST",+ json={"email": "[email protected]"},+ ),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),+ ),+ ):+ api = CheckEmailUnique()+ with pytest.raises(EmailDomainSuspendedError):+ inspect.unwrap(api.post)(api)@pytest.mark.parametrize(diff --git a/api/tests/unit_tests/controllers/console/workspace/test_accounts.py b/api/tests/unit_tests/controllers/console/workspace/test_accounts.pyindex f473f882a8d..d0178451eb2 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_accounts.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_accounts.py@@ -48,10 +48,14 @@ from models.account import AccountStatus, TenantAccountRolefrom services.account_errors import (AccountAlreadyInitializedError,AccountDeletionRateLimitError,+ AccountEmailAlreadyInUseError,+ AccountEmailDomainSuspendedError,+ AccountEmailFrozenError,AvatarFileNotFoundError,CurrentAccountPasswordIncorrectError,InvalidAccountDeletionVerificationError,InvalidAccountPasswordError,+ InvalidChangeEmailCodeError,MissingInvitationCodeError,)from services.entities.account_entities import AccountIntegrationStatus, AccountProfileChanges@@ -661,6 +665,14 @@ class TestChangeEmailApis:payload = {"email": "[email protected]", "code": "x", "token": "t"}user = make_account("acc-1")+ request_context = RequestContext(+ request_id="request-1",+ trace_id=None,+ account_id=user.id,+ active_workspace_id="workspace-1",+ )+ change_email = MagicMock()+ change_email.verify_code.side_effect = InvalidChangeEmailCodeErrorwith (app.test_request_context("/", json=payload),@@ -671,20 +683,12 @@ class TestChangeEmailApis:return_value=payload,),patch(- "controllers.console.workspace.account.AccountService.is_change_email_error_rate_limit",- return_value=False,- ),- patch(- "controllers.console.workspace.account.AccountService.get_change_email_data",- return_value=MagicMock(- email="[email protected]",- code="y",- is_bound_to_account=MagicMock(return_value=True),- ),+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),),):with pytest.raises(EmailCodeError):- method(api, user)+ method(api, request_context)def test_reset_email_already_used(self, app: Flask):api = ChangeEmailResetApi()@@ -692,6 +696,14 @@ class TestChangeEmailApis:payload = {"new_email": "[email protected]", "token": "t"}user = make_account()+ request_context = RequestContext(+ request_id="request-1",+ trace_id=None,+ account_id=user.id,+ active_workspace_id="workspace-1",+ )+ change_email = MagicMock()+ change_email.reset.side_effect = AccountEmailAlreadyInUseErrorwith (app.test_request_context("/", json=payload),@@ -701,11 +713,13 @@ class TestChangeEmailApis:new_callable=PropertyMock,return_value=payload,),- patch("controllers.console.workspace.account.AccountService.get_account_freeze_type", return_value=None),- patch("controllers.console.workspace.account.AccountService.check_email_unique", return_value=False),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),+ ),):with pytest.raises(EmailAlreadyInUseError):- method(api, user)+ method(api, request_context)class TestCheckEmailUniqueApi:@@ -714,6 +728,7 @@ class TestCheckEmailUniqueApi:method = inspect.unwrap(api.post)payload = {"email": "[email protected]"}+ change_email = MagicMock()with (app.test_request_context("/", json=payload),@@ -723,8 +738,10 @@ class TestCheckEmailUniqueApi:new_callable=PropertyMock,return_value=payload,),- patch("controllers.console.workspace.account.AccountService.get_account_freeze_type", return_value=None),- patch("controllers.console.workspace.account.AccountService.check_email_unique", return_value=True),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),+ ),):result = method(api)@@ -735,6 +752,8 @@ class TestCheckEmailUniqueApi:method = inspect.unwrap(api.post)payload = {"email": "[email protected]"}+ change_email = MagicMock()+ change_email.ensure_available.side_effect = AccountEmailFrozenErrorwith (app.test_request_context("/", json=payload),@@ -745,8 +764,8 @@ class TestCheckEmailUniqueApi:return_value=payload,),patch(- "controllers.console.workspace.account.AccountService.get_account_freeze_type",- return_value="freeze",+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),),):with pytest.raises(AccountInFreezeError):@@ -757,6 +776,8 @@ class TestCheckEmailUniqueApi:method = inspect.unwrap(api.post)payload = {"email": "[email protected]"}+ change_email = MagicMock()+ change_email.ensure_available.side_effect = AccountEmailDomainSuspendedErrorwith (app.test_request_context("/", json=payload),@@ -767,8 +788,8 @@ class TestCheckEmailUniqueApi:return_value=payload,),patch(- "controllers.console.workspace.account.AccountService.get_account_freeze_type",- return_value="email_domain_suspended",+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(change_email=change_email)),),):with pytest.raises(EmailDomainSuspendedError):diff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.pyindex 32bb9da5970..82f11568a25 100644--- a/api/tests/unit_tests/extensions/test_ext_application_services.py+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py@@ -187,6 +187,7 @@ def test_build_application_services_wires_account_profile_repository(assert services.accounts.password._accounts is accountsassert services.accounts.initialization._accounts is accountsassert not services.accounts.initialization._invitation_required+ assert services.accounts.change_email._accounts is accountsassert services.accounts.deletion._accounts is accountsassert services.accounts.deletion._memberships is services.workspace_queries._workspacesintegrations = services.accounts.integrations._integrationsdiff --git a/api/tests/unit_tests/libs/test_token_manager.py b/api/tests/unit_tests/libs/test_token_manager.pyindex e8f975ae974..35d28efbbda 100644--- a/api/tests/unit_tests/libs/test_token_manager.py+++ b/api/tests/unit_tests/libs/test_token_manager.py@@ -15,7 +15,6 @@ from pydantic import ValidationErrorimport libs.helper as helper_modulefrom libs.helper import TokenManager-from models.account import Accountdef _build_fake_redis(storage: dict[str, str]):@@ -62,20 +61,16 @@ def test_token_manager_roundtrip_preserves_untyped_metadata_keys(monkeypatch: pyassert data.get("custom_marker") == "preserve-me"-def test_token_manager_roundtrip_uses_explicit_email_with_account(monkeypatch: pytest.MonkeyPatch) -> None:- """When both `account` and `email` are supplied, the token should bind the- stable `account_id` from the account and the target email from the explicit- email argument.+def test_token_manager_roundtrip_uses_explicit_account_id(monkeypatch: pytest.MonkeyPatch) -> None:+ """When both `account_id` and `email` are supplied, the token should bind+ both primitive values without depending on an account model."""storage: dict[str, str] = {}monkeypatch.setattr(helper_module, "redis_client", _build_fake_redis(storage))- account = Account(name="Test User", email="[email protected]")- account.id = "acc-1"-token = TokenManager.generate_token(- account=account,+ account_id="acc-1",email="[email protected]",token_type="change_email",additional_data={diff --git a/api/tests/unit_tests/repositories/test_account_repository.py b/api/tests/unit_tests/repositories/test_account_repository.pyindex 6e338d2f61c..e319e89e194 100644--- a/api/tests/unit_tests/repositories/test_account_repository.py+++ b/api/tests/unit_tests/repositories/test_account_repository.py@@ -157,3 +157,35 @@ def test_account_repository_initializes_account_and_consumes_invitation_atomicalassert persisted_invitation.status == InvitationCodeStatus.USEDassert persisted_invitation.used_by_account_id == "account-1"assert persisted_invitation.used_by_tenant_id == "workspace-1"+++def test_account_repository_updates_email_and_removes_integrations_atomically(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _persist_account(sqlite_session)+ integration = AccountIntegrate(+ account_id="account-1",+ provider="google",+ open_id="google-user",+ encrypted_token="encrypted-token",+ )+ sqlite_session.add(integration)+ sqlite_session.commit()+ integration_id = integration.id+ repository = SQLAlchemyAccountRepository(sqlite_session_factory)++ assert repository.email_exists("[email protected]") is False+ result = repository.reset_email(+ "account-1",+ expected_old_email="[email protected]",+ new_email="[email protected]",+ )++ assert result.account is not None+ assert result.account.email == "[email protected]"+ sqlite_session.expire_all()+ persisted = sqlite_session.get(Account, "account-1")+ assert persisted is not None+ assert persisted.email == "[email protected]"+ assert sqlite_session.get(AccountIntegrate, integration_id) is Nonediff --git a/api/tests/unit_tests/services/test_account_change_email_adapters.py b/api/tests/unit_tests/services/test_account_change_email_adapters.pynew file mode 100644index 00000000000..1b59e53f278--- /dev/null+++ b/api/tests/unit_tests/services/test_account_change_email_adapters.py@@ -0,0 +1,93 @@+from unittest.mock import MagicMock, patch++from extensions.ext_redis import RedisClientWrapper+from services.account_change_email_adapters import (+ BillingAccountEmailPolicyGateway,+ RedisChangeEmailSecurityGateway,+ TokenManagerChangeEmailTokenGateway,+)+from services.entities.account_entities import AccountChangeEmailNewEmailToken+++def test_billing_email_policy_preserves_suspended_domain_reason() -> None:+ gateway = BillingAccountEmailPolicyGateway(billing_enabled=True)++ with (+ patch("services.account_change_email_adapters.BillingService.is_email_in_freeze", return_value=True),+ patch(+ "services.account_change_email_adapters.BillingService.get_email_freeze_type",+ return_value="email_domain_suspended",+ ),+ ):+ assert gateway.is_frozen("[email protected]") == "email_domain_suspended"+++def test_token_gateway_rejects_payload_without_account_binding() -> None:+ gateway = TokenManagerChangeEmailTokenGateway()++ with patch(+ "services.account_change_email_adapters.TokenManager.get_token_data",+ return_value={+ "token_type": "change_email",+ "email": "[email protected]",+ "old_email": "[email protected]",+ "code": "123456",+ "email_change_phase": "new_email",+ },+ ):+ assert gateway.get("token") is None+++def test_token_gateway_issues_account_bound_state() -> None:+ gateway = TokenManagerChangeEmailTokenGateway()+ token_data = AccountChangeEmailNewEmailToken(+ account_id="account-1",+ email="[email protected]",+ old_email="[email protected]",+ code="123456",+ )++ with patch(+ "services.account_change_email_adapters.TokenManager.generate_token",+ return_value="token",+ ) as generate_token:+ assert gateway.issue(token_data) == "token"++ assert generate_token.call_args.kwargs["account_id"] == "account-1"+ assert generate_token.call_args.kwargs["email"] == "[email protected]"+ assert generate_token.call_args.kwargs["additional_data"] == {+ "old_email": "[email protected]",+ "code": "123456",+ "email_change_phase": "new_email",+ }+++def test_security_gateway_counts_normal_ip_request() -> None:+ redis = MagicMock(spec=RedisClientWrapper)+ redis.get.side_effect = [None, None]+ gateway = RedisChangeEmailSecurityGateway(+ redis=redis,+ email_send_ip_limit_per_minute=60,+ verification_failure_limit=5,+ verification_lockout_duration=600,+ )++ assert gateway.is_ip_limited("127.0.0.1") is False++ redis.setex.assert_called_once_with("email_send_ip_limit_minute:127.0.0.1", 60, 1)+ redis.expire.assert_called_once_with("email_send_ip_limit_minute:127.0.0.1", 60)+++def test_security_gateway_freezes_second_over_limit_ip_strike() -> None:+ redis = MagicMock(spec=RedisClientWrapper)+ redis.get.side_effect = [None, 2, 1]+ gateway = RedisChangeEmailSecurityGateway(+ redis=redis,+ email_send_ip_limit_per_minute=1,+ verification_failure_limit=5,+ verification_lockout_duration=600,+ )++ assert gateway.is_ip_limited("127.0.0.1") is True++ redis.setex.assert_called_once_with("email_send_ip_limit_freeze:127.0.0.1", 3600, 1)diff --git a/api/tests/unit_tests/services/test_account_change_email_service.py b/api/tests/unit_tests/services/test_account_change_email_service.pynew file mode 100644index 00000000000..3fb3e8d6837--- /dev/null+++ b/api/tests/unit_tests/services/test_account_change_email_service.py@@ -0,0 +1,310 @@+from __future__ import annotations++from datetime import datetime+from unittest.mock import Mock++import pytest++from machinery.context import RequestContext+from services.account_change_email_ports import (+ AccountEmailPolicyGateway,+ ChangeEmailCodeGenerator,+ ChangeEmailNotificationGateway,+ ChangeEmailSecurityGateway,+ ChangeEmailSendLimiter,+ ChangeEmailTokenGateway,+)+from services.account_change_email_service import AccountChangeEmailService+from services.account_errors import (+ AccountEmailAlreadyInUseError,+ AccountEmailDomainSuspendedError,+ AccountNotFoundError,+ InvalidChangeEmailCodeError,+ InvalidChangeEmailTokenError,+)+from services.account_ports import AccountRepository+from services.entities.account_entities import (+ AccountChangeEmailNewEmailToken,+ AccountChangeEmailNewEmailVerifiedToken,+ AccountChangeEmailOldEmailToken,+ AccountChangeEmailOldEmailVerifiedToken,+ AccountChangeEmailPhase,+ AccountEmailResetResult,+ AccountEmailResetStatus,+ AccountSnapshot,+)+++def _context() -> RequestContext:+ return RequestContext(+ request_id="request-1",+ trace_id="trace-1",+ account_id="account-1",+ active_workspace_id="workspace-1",+ )+++def _account(*, email: str = "[email protected]") -> AccountSnapshot:+ return AccountSnapshot(+ id="account-1",+ name="Account",+ email=email,+ avatar=None,+ is_password_set=True,+ interface_language="en-US",+ interface_theme="light",+ timezone="UTC",+ last_login_at=None,+ last_login_ip=None,+ status="active",+ initialized_at=datetime(2026, 1, 1),+ created_at=datetime(2026, 1, 1),+ )+++def _service() -> tuple[AccountChangeEmailService, dict[str, Mock]]:+ dependencies = {+ "accounts": Mock(spec=AccountRepository),+ "tokens": Mock(spec=ChangeEmailTokenGateway),+ "codes": Mock(spec=ChangeEmailCodeGenerator),+ "notifications": Mock(spec=ChangeEmailNotificationGateway),+ "send_limits": Mock(spec=ChangeEmailSendLimiter),+ "security": Mock(spec=ChangeEmailSecurityGateway),+ "email_policy": Mock(spec=AccountEmailPolicyGateway),+ }+ service = AccountChangeEmailService(+ accounts=dependencies["accounts"],+ tokens=dependencies["tokens"],+ codes=dependencies["codes"],+ notifications=dependencies["notifications"],+ send_limits=dependencies["send_limits"],+ security=dependencies["security"],+ email_policy=dependencies["email_policy"],+ )+ dependencies["accounts"].get.return_value = _account()+ dependencies["codes"].generate.return_value = "123456"+ dependencies["tokens"].issue.return_value = "token"+ dependencies["send_limits"].is_limited.return_value = False+ dependencies["security"].is_ip_limited.return_value = False+ dependencies["security"].is_verification_limited.return_value = False+ dependencies["email_policy"].is_frozen.return_value = False+ return service, dependencies+++def test_send_old_email_code_coerces_unexpected_phase_to_initial_state() -> None:+ service, dependencies = _service()++ token = service.send_code(+ _context(),+ requested_email="[email protected]",+ language="en-US",+ phase="unexpected",+ predecessor_token=None,+ ip_address="127.0.0.1",+ )++ assert token == "token"+ issued = dependencies["tokens"].issue.call_args.args[0]+ assert issued == AccountChangeEmailOldEmailToken(+ account_id="account-1",+ email="[email protected]",+ old_email="[email protected]",+ code="123456",+ )+ dependencies["notifications"].send_code.assert_called_once_with(+ email="[email protected]",+ code="123456",+ language="en-US",+ phase=AccountChangeEmailPhase.OLD_EMAIL,+ )+ dependencies["send_limits"].record.assert_called_once_with("[email protected]")+++def test_send_new_email_code_requires_account_bound_old_verified_token() -> None:+ service, dependencies = _service()+ dependencies["tokens"].get.return_value = AccountChangeEmailOldEmailVerifiedToken(+ account_id="account-1",+ email="[email protected]",+ old_email="[email protected]",+ code="old-code",+ )++ service.send_code(+ _context(),+ requested_email="[email protected]",+ language="zh-Hans",+ phase="new_email",+ predecessor_token="old-verified-token",+ ip_address="127.0.0.1",+ )++ issued = dependencies["tokens"].issue.call_args.args[0]+ assert issued == AccountChangeEmailNewEmailToken(+ account_id="account-1",+ email="[email protected]",+ old_email="[email protected]",+ code="123456",+ )+++def test_send_new_email_code_rejects_unverified_predecessor() -> None:+ service, dependencies = _service()+ dependencies["tokens"].get.return_value = AccountChangeEmailOldEmailToken(+ account_id="account-1",+ email="[email protected]",+ old_email="[email protected]",+ code="old-code",+ )++ with pytest.raises(InvalidChangeEmailTokenError):+ service.send_code(+ _context(),+ requested_email="[email protected]",+ language="en-US",+ phase="new_email",+ predecessor_token="unverified-token",+ ip_address="127.0.0.1",+ )++ dependencies["tokens"].issue.assert_not_called()+++ ("pending", "verified_type"),+ [+ (+ AccountChangeEmailOldEmailToken(+ account_id="account-1",+ email="[email protected]",+ old_email="[email protected]",+ code="123456",+ ),+ AccountChangeEmailOldEmailVerifiedToken,+ ),+ (+ AccountChangeEmailNewEmailToken(+ account_id="account-1",+ email="[email protected]",+ old_email="[email protected]",+ code="123456",+ ),+ AccountChangeEmailNewEmailVerifiedToken,+ ),+ ],+)+def test_verify_code_promotes_only_pending_account_bound_token(+ pending: AccountChangeEmailOldEmailToken | AccountChangeEmailNewEmailToken,+ verified_type: type[AccountChangeEmailOldEmailVerifiedToken] | type[AccountChangeEmailNewEmailVerifiedToken],+) -> None:+ service, dependencies = _service()+ dependencies["tokens"].get.return_value = pending+ dependencies["tokens"].issue.return_value = "verified-token"++ result = service.verify_code(+ _context(),+ email=pending.email.upper(),+ code="123456",+ token="pending-token",+ )++ assert result.email == pending.email+ assert result.token == "verified-token"+ assert isinstance(dependencies["tokens"].issue.call_args.args[0], verified_type)+ dependencies["tokens"].revoke.assert_called_once_with("pending-token")+ dependencies["security"].reset_verification_failures.assert_called_once_with(pending.email)+++def test_verify_code_records_invalid_code_without_promoting_token() -> None:+ service, dependencies = _service()+ dependencies["tokens"].get.return_value = AccountChangeEmailNewEmailToken(+ account_id="account-1",+ email="[email protected]",+ old_email="[email protected]",+ code="123456",+ )++ with pytest.raises(InvalidChangeEmailCodeError):+ service.verify_code(+ _context(),+ email="[email protected]",+ code="wrong",+ token="pending-token",+ )++ dependencies["security"].record_verification_failure.assert_called_once_with("[email protected]")+ dependencies["tokens"].revoke.assert_not_called()+++def test_reset_updates_account_and_unbinds_integrations_before_external_notifications() -> None:+ service, dependencies = _service()+ dependencies["tokens"].get.return_value = AccountChangeEmailNewEmailVerifiedToken(+ account_id="account-1",+ email="[email protected]",+ old_email="[email protected]",+ code="123456",+ )+ dependencies["accounts"].reset_email.return_value = AccountEmailResetResult(+ status=AccountEmailResetStatus.UPDATED,+ account=_account(email="[email protected]"),+ )++ result = service.reset(_context(), new_email="[email protected]", token="verified-token")++ assert result.email == "[email protected]"+ dependencies["accounts"].reset_email.assert_called_once_with(+ "account-1",+ expected_old_email="[email protected]",+ new_email="[email protected]",+ )+ dependencies["tokens"].revoke.assert_called_once_with("verified-token")+ dependencies["notifications"].send_completed.assert_called_once_with(+ email="[email protected]",+ language="en-US",+ )+++def test_email_availability_preserves_suspended_domain_policy() -> None:+ service, dependencies = _service()+ dependencies["email_policy"].is_frozen.return_value = "email_domain_suspended"++ with pytest.raises(AccountEmailDomainSuspendedError):+ service.ensure_available("[email protected]")++ dependencies["email_policy"].is_frozen.assert_called_once_with("[email protected]")+ dependencies["accounts"].email_exists.assert_not_called()+++def test_reset_rejects_existing_email_without_burning_verified_token() -> None:+ service, dependencies = _service()+ dependencies["tokens"].get.return_value = AccountChangeEmailNewEmailVerifiedToken(+ account_id="account-1",+ email="[email protected]",+ old_email="[email protected]",+ code="123456",+ )+ dependencies["accounts"].reset_email.return_value = AccountEmailResetResult(+ status=AccountEmailResetStatus.EMAIL_IN_USE+ )++ with pytest.raises(AccountEmailAlreadyInUseError):+ service.reset(_context(), new_email="[email protected]", token="verified-token")++ dependencies["tokens"].revoke.assert_not_called()+++def test_reset_rejects_token_when_account_email_changed_since_verification() -> None:+ service, dependencies = _service()+ dependencies["accounts"].reset_email.return_value = AccountEmailResetResult(+ status=AccountEmailResetStatus.EMAIL_CHANGED+ )+ dependencies["tokens"].get.return_value = AccountChangeEmailNewEmailVerifiedToken(+ account_id="account-1",+ email="[email protected]",+ old_email="[email protected]",+ code="123456",+ )++ with pytest.raises(AccountNotFoundError):+ service.reset(_context(), new_email="[email protected]", token="verified-token")++ dependencies["tokens"].revoke.assert_not_called()diff --git a/api/tests/unit_tests/services/test_account_deletion_adapters.py b/api/tests/unit_tests/services/test_account_deletion_adapters.pyindex 6ced40b1dd2..880b5e8a094 100644--- a/api/tests/unit_tests/services/test_account_deletion_adapters.py+++ b/api/tests/unit_tests/services/test_account_deletion_adapters.py@@ -35,9 +35,8 @@ def test_verification_gateway_creates_six_digit_account_bound_challenge() -> Nonassert challenge.token == "token"assert challenge.code == "123456"- token_account = generate_token.call_args.kwargs["account"]- assert token_account.id == "account-1"- assert token_account.email == "[email protected]"+ assert generate_token.call_args.kwargs["account_id"] == "account-1"+ assert generate_token.call_args.kwargs["email"] == "[email protected]"assert generate_token.call_args.kwargs["additional_data"] == {"code": "123456"}