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 email registration application service (#41108)
Byron.wang9e07c2dac6fb
diff --git a/api/.importlinter b/api/.importlinterindex f3609e5826a..7cf69c0c515 100644--- a/api/.importlinter+++ b/api/.importlinter@@ -207,6 +207,7 @@ source_modules =services.account_avatar_serviceservices.account_change_email_portsservices.account_change_email_service+ services.account_email_registration_serviceservices.account_deletion_serviceservices.account_deletion_feedback_serviceservices.account_education_servicediff --git a/api/controllers/console/auth/email_register.py b/api/controllers/console/auth/email_register.pyindex e81acbed99d..e0bfddccfa0 100644--- a/api/controllers/console/auth/email_register.py+++ b/api/controllers/console/auth/email_register.py@@ -2,8 +2,6 @@ from flask import requestfrom flask_restx import Resourcefrom pydantic import BaseModel, Field, field_validator-from configs import dify_config-from constants.languages import get_valid_language, languagesfrom controllers.common.fields import SimpleResultDataResponse, VerificationTokenResponsefrom controllers.common.schema import register_response_schema_models, register_schema_modelsfrom controllers.console import console_ns@@ -11,31 +9,35 @@ from controllers.console.auth.error import (EmailAlreadyInUseError,EmailCodeError,EmailRegisterLimitError,+ EmailRegisterRateLimitExceededError,InvalidEmailError,InvalidTokenError,NormalizedEmailAlreadyInUseError,PasswordMismatchError,)-from enums import DeploymentEdition-from extensions.ext_database import db+from controllers.console.flask_admission import console_email_registration_admission+from controllers.console.wraps import model_validate+from extensions.ext_application_services import application_servicesfrom fields.base import ResponseModel-from libs.helper import EmailStr, extract_remote_ip+from libs.helper import EmailStr, dump_response, extract_remote_ipfrom libs.helper import timezone as validate_timezone_stringfrom libs.password import valid_password-from models import Account-from services.account_service import AccountService-from services.billing_service import BillingService-from services.errors.account import (+from services.account_errors import (+ AccountEmailAlreadyInUseError,+ AccountEmailDomainSuspendedError,+ AccountEmailFrozenError,AccountNormalizedEmailAlreadyInUseError,- AccountRegisterError,- SeatsLimitExceededError,-)-from services.errors.account import (- EmailDomainSuspendedError as EmailDomainSuspendedRegistrationError,+ EmailRegistrationPasswordMismatchError,+ EmailRegistrationSeatsLimitError,+ EmailRegistrationSendIPLimitedError,+ EmailRegistrationSendRateLimitError,+ EmailRegistrationVerificationLimitError,+ InvalidEmailRegistrationAddressError,+ InvalidEmailRegistrationCodeError,+ InvalidEmailRegistrationTokenError,)from ..error import AccountInFreezeError, EmailDomainSuspendedError, EmailSendIpLimitError, SeatsLimitExceeded-from ..wraps import email_password_login_enabled, email_register_enabled, model_validate, setup_requiredclass EmailRegisterSendPayload(BaseModel):@@ -91,146 +93,91 @@ register_response_schema_models(@console_ns.route("/email-register/send-email")class EmailRegisterSendEmailApi(Resource):- @setup_required- @email_password_login_enabled- @email_register_enabled@console_ns.expect(console_ns.models[EmailRegisterSendPayload.__name__])@console_ns.response(200, "Success", console_ns.models[SimpleResultDataResponse.__name__])+ @console_email_registration_admission@model_validate(EmailRegisterSendPayload)- def post(self, req_data: EmailRegisterSendPayload):- normalized_email = req_data.email.lower()-- ip_address = extract_remote_ip(request)- if AccountService.is_email_send_ip_limit(ip_address):- raise EmailSendIpLimitError()- language = "en-US"- if req_data.language is not None and req_data.language in languages:- language = req_data.language-- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:- freeze_type = BillingService.get_email_freeze_type(normalized_email)- if freeze_type:- if freeze_type == "email_domain_suspended":- raise EmailDomainSuspendedError()- raise AccountInFreezeError()-- account = AccountService.get_account_by_email_with_case_fallback(req_data.email, session=db.session())- token = AccountService.send_email_register_email(email=normalized_email, account=account, language=language)- return {"result": "success", "data": token}+ def post(self, args: EmailRegisterSendPayload):+ try:+ token = application_services().accounts.email_registration.send_code(+ remote_ip=extract_remote_ip(request),+ requested_email=args.email,+ requested_language=args.language,+ )+ except EmailRegistrationSendIPLimitedError:+ raise EmailSendIpLimitError() from None+ except EmailRegistrationSendRateLimitError as error:+ raise EmailRegisterRateLimitExceededError(error.retry_after_minutes) from None+ except AccountEmailDomainSuspendedError:+ raise EmailDomainSuspendedError() from None+ except AccountEmailFrozenError:+ raise AccountInFreezeError() from None+ return dump_response(SimpleResultDataResponse, {"result": "success", "data": token})@console_ns.route("/email-register/validity")class EmailRegisterCheckApi(Resource):- @setup_required- @email_password_login_enabled- @email_register_enabled@console_ns.expect(console_ns.models[EmailRegisterValidityPayload.__name__])@console_ns.response(200, "Success", console_ns.models[VerificationTokenResponse.__name__])+ @console_email_registration_admission@model_validate(EmailRegisterValidityPayload)- def post(self, req_data: EmailRegisterValidityPayload):-- user_email = req_data.email.lower()-- is_email_register_error_rate_limit = AccountService.is_email_register_error_rate_limit(user_email)- if is_email_register_error_rate_limit:- raise EmailRegisterLimitError()-- token_data = AccountService.get_email_register_data(req_data.token)- if token_data is None:- raise InvalidTokenError()-- token_email = token_data.get("email")- normalized_token_email = token_email.lower() if isinstance(token_email, str) else token_email-- if user_email != normalized_token_email:- raise InvalidEmailError()-- if req_data.code != token_data.get("code"):- AccountService.add_email_register_error_rate_limit(user_email)- raise EmailCodeError()-- # Verified, revoke the first token- AccountService.revoke_email_register_token(req_data.token)-- # Refresh token data by generating a new token- _, new_token = AccountService.generate_email_register_token(- user_email, code=req_data.code, additional_data={"phase": "register"}+ def post(self, args: EmailRegisterValidityPayload):+ try:+ verification = application_services().accounts.email_registration.verify_code(+ email=args.email,+ code=args.code,+ token=args.token,+ )+ except EmailRegistrationVerificationLimitError:+ raise EmailRegisterLimitError() from None+ except InvalidEmailRegistrationTokenError:+ raise InvalidTokenError() from None+ except InvalidEmailRegistrationAddressError:+ raise InvalidEmailError() from None+ except InvalidEmailRegistrationCodeError:+ raise EmailCodeError() from None+ return dump_response(+ VerificationTokenResponse,+ {+ "is_valid": True,+ "email": verification.email,+ "token": verification.token,+ },)- AccountService.reset_email_register_error_rate_limit(user_email)- return {"is_valid": True, "email": normalized_token_email, "token": new_token}-@console_ns.route("/email-register")class EmailRegisterResetApi(Resource):- @setup_required- @email_password_login_enabled- @email_register_enabled@console_ns.expect(console_ns.models[EmailRegisterResetPayload.__name__])@console_ns.response(200, "Success", console_ns.models[EmailRegisterResetResponse.__name__])+ @console_email_registration_admission@model_validate(EmailRegisterResetPayload)- def post(self, req_data: EmailRegisterResetPayload):-- # Validate passwords match- if req_data.new_password != req_data.password_confirm:- raise PasswordMismatchError()-- # Validate token and get register data- register_data = AccountService.get_email_register_data(req_data.token)- if not register_data:- raise InvalidTokenError()- # Must use token in reset phase- if register_data.get("phase", "") != "register":- raise InvalidTokenError()-- # Revoke token to prevent reuse- AccountService.revoke_email_register_token(req_data.token)-- email = register_data.get("email", "")- normalized_email = email.lower()-- account = AccountService.get_account_by_email_with_case_fallback(email, session=db.session())-- if account:- raise EmailAlreadyInUseError()-- ip_address = extract_remote_ip(request)- account = self._create_new_account(- email=normalized_email,- password=req_data.password_confirm,- timezone=req_data.timezone,- language=req_data.language,- ip_address=ip_address,- )- token_pair = AccountService.login(account=account, session=db.session(), ip_address=ip_address)- AccountService.reset_login_error_rate_limit(normalized_email)-- return {"result": "success", "data": token_pair.model_dump()}-- def _create_new_account(- self,- email: str,- password: str,- timezone: str | None = None,- language: str | None = None,- ip_address: str | None = None,- ) -> Account:+ def post(self, args: EmailRegisterResetPayload):try:- return AccountService.create_account_and_tenant(- email=email,- name=email,- password=password,- interface_language=get_valid_language(language),- timezone=timezone,- ip_address=ip_address,- check_normalized_email=True,- session=db.session(),+ token_pair = application_services().accounts.email_registration.register(+ remote_ip=extract_remote_ip(request),+ token=args.token,+ new_password=args.new_password,+ password_confirm=args.password_confirm,+ language=args.language,+ timezone=args.timezone,)- except SeatsLimitExceededError:- raise SeatsLimitExceeded()- except EmailDomainSuspendedRegistrationError as exc:- raise EmailDomainSuspendedError() from exc- except AccountNormalizedEmailAlreadyInUseError as exc:- raise NormalizedEmailAlreadyInUseError() from exc- except AccountRegisterError as exc:- raise AccountInFreezeError() from exc+ except EmailRegistrationPasswordMismatchError:+ raise PasswordMismatchError() from None+ except InvalidEmailRegistrationTokenError:+ raise InvalidTokenError() from None+ except AccountNormalizedEmailAlreadyInUseError:+ raise NormalizedEmailAlreadyInUseError() from None+ except AccountEmailAlreadyInUseError:+ raise EmailAlreadyInUseError() from None+ except EmailRegistrationSeatsLimitError:+ raise SeatsLimitExceeded() from None+ except AccountEmailDomainSuspendedError:+ raise EmailDomainSuspendedError() from None+ except AccountEmailFrozenError:+ raise AccountInFreezeError() from None++ return dump_response(+ EmailRegisterResetResponse,+ {"result": "success", "data": token_pair},+ )diff --git a/api/controllers/console/flask_admission.py b/api/controllers/console/flask_admission.pyindex 5eafc9c4741..eb300128aed 100644--- a/api/controllers/console/flask_admission.py+++ b/api/controllers/console/flask_admission.py@@ -22,6 +22,22 @@ from libs.login import current_account_with_tenant, login_requiredfrom machinery.context import RequestContextfrom machinery.errors import AdmissionConfigurationErrorfrom models.account import TenantAccountRole+from services.feature_service import FeatureService+++def console_email_registration_admission[T, **P, R](+ view: Callable[Concatenate[T, P], R],+) -> Callable[Concatenate[T, P], R | Response]:+ """Apply the complete admission policy for anonymous email registration."""++ @wraps(view)+ def check_registration_features(self: T, /, *args: P.args, **kwargs: P.kwargs) -> R:+ features = FeatureService.get_system_features()+ if not features.enable_email_password_login or not features.is_allow_register:+ abort(403)+ return view(self, *args, **kwargs)++ return setup_required(check_registration_features)def console_account_admission[T, **P, R](diff --git a/api/controllers/console/wraps.py b/api/controllers/console/wraps.pyindex 7850f4d206a..da1d5584af6 100644--- a/api/controllers/console/wraps.py+++ b/api/controllers/console/wraps.py@@ -352,19 +352,6 @@ def email_password_login_enabled[**P, R](view: Callable[P, R]) -> Callable[P, R]return decorated-def email_register_enabled[**P, R](view: Callable[P, R]) -> Callable[P, R]:- @wraps(view)- def decorated(*args: P.args, **kwargs: P.kwargs):- features = FeatureService.get_system_features()- if features.is_allow_register:- return view(*args, **kwargs)-- # otherwise, return 403- abort(403)-- return decorated--def enable_change_email[**P, R](view: Callable[P, R]) -> Callable[P, R]:@wraps(view)def decorated(*args: P.args, **kwargs: P.kwargs):@@ -652,6 +639,23 @@ def with_current_user_id[T, **P, R](return decorated+def validate_request[M: BaseModel](model: type[M]) -> M:+ """Parse and validate the current request without exposing submitted values."""++ if request.method == "GET":+ raw = request.args.to_dict(flat=True)+ elif request.method == "DELETE":+ raw = request.args.to_dict(flat=True) or (request.get_json(silent=True) or {})+ else:+ raw = request.get_json(silent=True) or {}++ try:+ return model.model_validate(raw)+ except ValidationError as exc:+ errors = exc.errors(include_url=False, include_input=False, include_context=False)+ raise UnprocessableEntity(json.dumps(errors)) from None++def model_validate[T, M: BaseModel, **P, R](model: type[M],) -> Callable[@@ -671,19 +675,7 @@ def model_validate[T, M: BaseModel, **P, R]() -> Callable[Concatenate[T, P], R]:@wraps(view)def wrapper(self: T, *args: P.args, **kwargs: P.kwargs) -> R:- if request.method == "GET":- raw = request.args.to_dict(flat=True)- elif request.method == "DELETE":- raw = request.args.to_dict(flat=True) or (request.get_json(silent=True) or {})- else:- raw = request.get_json(silent=True) or {}-- try:- validated = model.model_validate(raw)- except ValidationError as exc:- raise UnprocessableEntity(exc.json())-- return view(self, validated, *args, **kwargs)+ return view(self, validate_request(model), *args, **kwargs)return wrapperdiff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.pyindex e29b92c8617..7a482248cce 100644--- a/api/extensions/ext_application_services.py+++ b/api/extensions/ext_application_services.py@@ -70,6 +70,16 @@ from services.account_deletion_adapters import (from services.account_deletion_feedback_service import AccountDeletionFeedbackServicefrom services.account_deletion_service import AccountDeletionServicefrom services.account_education_service import AccountEducationService+from services.account_email_registration_adapters import (+ AccountServiceRegistrationGateway,+ BillingAccountRegistrationPolicyGateway,+ CeleryEmailRegistrationNotificationGateway,+ RateLimiterEmailRegistrationSendLimiter,+ RedisEmailRegistrationSecurityGateway,+ SecureEmailRegistrationCodeGenerator,+ TokenManagerEmailRegistrationTokenGateway,+)+from services.account_email_registration_service import AccountEmailRegistrationServicefrom services.account_initialization_service import AccountInitializationServicefrom services.account_integration_service import AccountIntegrationServicefrom services.account_password_hasher import LegacyAccountPasswordHasher@@ -150,6 +160,7 @@ def _is_user_allowed_to_access_webapp(user_id: str, app_id: str) -> bool:class AccountServices:avatar: AccountAvatarServicechange_email: AccountChangeEmailService+ email_registration: AccountEmailRegistrationServicedeletion: AccountDeletionServicedeletion_feedback: AccountDeletionFeedbackServiceeducation: AccountEducationService@@ -278,6 +289,29 @@ def build_application_services(billing_enabled=deployment_edition == DeploymentEdition.CLOUD,),),+ email_registration=AccountEmailRegistrationService(+ accounts=accounts,+ tokens=TokenManagerEmailRegistrationTokenGateway(),+ codes=SecureEmailRegistrationCodeGenerator(),+ notifications=CeleryEmailRegistrationNotificationGateway(),+ send_limits=RateLimiterEmailRegistrationSendLimiter(+ rate_limiter=RateLimiter(+ prefix="email_register_rate_limit",+ max_attempts=1,+ time_window=60,+ redis_client=redis,+ )+ ),+ security=RedisEmailRegistrationSecurityGateway(+ redis=redis,+ verification_failure_limit=5,+ verification_lockout_duration=dify_config.EMAIL_REGISTER_LOCKOUT_DURATION,+ ),+ account_policy=BillingAccountRegistrationPolicyGateway(+ enabled=deployment_edition == DeploymentEdition.CLOUD,+ ),+ registration=AccountServiceRegistrationGateway(session_factory=database_client),+ ),deletion=AccountDeletionService(accounts=accounts,memberships=workspace_query_repository,diff --git a/api/repositories/account_repository.py b/api/repositories/account_repository.pyindex 1e7fb55e0d3..54568c7321c 100644--- a/api/repositories/account_repository.py+++ b/api/repositories/account_repository.py@@ -31,6 +31,14 @@ class SQLAlchemyAccountRepository(AccountRepository):account = session.get(Account, account_id)return self._to_snapshot(account) if account is not None else None+ @override+ def find_by_email(self, email: str) -> AccountSnapshot | None:+ with self._session_factory() as session:+ account = session.scalar(select(Account).where(Account.email == email).limit(1))+ if account is None and email != email.lower():+ account = session.scalar(select(Account).where(Account.email == email.lower()).limit(1))+ return self._to_snapshot(account) if account is not None else None+@overridedef get_credentials(self, account_id: str) -> AccountCredentials | None:with self._session_factory() as session:diff --git a/api/services/account_email_registration_adapters.py b/api/services/account_email_registration_adapters.pynew file mode 100644index 00000000000..5bd25b33b6e--- /dev/null+++ b/api/services/account_email_registration_adapters.py@@ -0,0 +1,230 @@+"""Infrastructure adapters for account email registration."""++import logging+import secrets+from typing import override++from redis import RedisError+from sqlalchemy.orm import Session, sessionmaker++from extensions.ext_redis import RedisClientWrapper+from libs.helper import RateLimiter, TokenManager+from models.account import Account+from services.account_email_registration_service import (+ AccountRegistrationGateway,+ AccountRegistrationPolicyGateway,+ EmailRegistrationCodeGenerator,+ EmailRegistrationNotificationGateway,+ EmailRegistrationSecurityGateway,+ EmailRegistrationSendLimiter,+ EmailRegistrationTokenGateway,+)+from services.account_errors import (+ AccountEmailDomainSuspendedError,+ AccountEmailFrozenError,+ AccountNormalizedEmailAlreadyInUseError,+ EmailRegistrationSeatsLimitError,+)+from services.account_service import AccountService+from services.billing_service import BillingService+from services.entities.account_entities import (+ AccountEmailRegistrationPhase,+ AccountEmailRegistrationToken,+ AccountSessionTokens,+)+from services.errors.account import (+ AccountNormalizedEmailAlreadyInUseError as AccountNormalizedEmailAlreadyInUseServiceError,+)+from services.errors.account import AccountRegisterError, EmailDomainSuspendedError, SeatsLimitExceededError+from tasks.mail_register_task import send_email_register_mail_task, send_email_register_mail_task_when_account_exist++logger = logging.getLogger(__name__)+++class TokenManagerEmailRegistrationTokenGateway(EmailRegistrationTokenGateway):+ @override+ def get(self, token: str) -> AccountEmailRegistrationToken | None:+ payload = TokenManager.get_token_data(token, "email_register")+ if payload is None:+ return None+ email = payload.get("email")+ code = payload.get("code")+ phase_value = payload.get("phase")+ if not isinstance(email, str) or not isinstance(code, str):+ return None+ if phase_value is None:+ phase = None+ else:+ try:+ phase = AccountEmailRegistrationPhase(phase_value)+ except (TypeError, ValueError):+ return None+ return AccountEmailRegistrationToken(email=email, code=code, phase=phase)++ @override+ def issue(self, token_data: AccountEmailRegistrationToken) -> str:+ additional_data = {"code": token_data.code}+ if token_data.phase is not None:+ additional_data["phase"] = token_data.phase.value+ return TokenManager.generate_token(+ email=token_data.email,+ token_type="email_register",+ additional_data=additional_data,+ )++ @override+ def revoke(self, token: str) -> None:+ TokenManager.revoke_token(token, "email_register")+++class SecureEmailRegistrationCodeGenerator(EmailRegistrationCodeGenerator):+ @override+ def generate(self) -> str:+ return "".join(str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6))+++class CeleryEmailRegistrationNotificationGateway(EmailRegistrationNotificationGateway):+ @override+ def send_code(self, *, email: str, code: str, language: str) -> None:+ send_email_register_mail_task.delay(language=language, to=email, code=code)++ @override+ def send_account_exists(self, *, email: str, account_name: str, language: str) -> None:+ send_email_register_mail_task_when_account_exist.delay(+ language=language,+ to=email,+ account_name=account_name,+ )+++class RateLimiterEmailRegistrationSendLimiter(EmailRegistrationSendLimiter):+ 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 RedisEmailRegistrationSecurityGateway(EmailRegistrationSecurityGateway):+ def __init__(+ self,+ *,+ redis: RedisClientWrapper,+ verification_failure_limit: int,+ verification_lockout_duration: int,+ ) -> None:+ self._redis = redis+ self._verification_failure_limit = verification_failure_limit+ self._verification_lockout_duration = verification_lockout_duration++ @override+ def is_ip_limited(self, ip_address: str) -> bool:+ return AccountService.is_email_send_ip_limit(ip_address) is True++ @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:+ logger.warning("Failed to read email-registration verification limit", exc_info=True)+ 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:+ logger.warning("Failed to record email-registration verification failure", exc_info=True)+ return None++ @override+ def reset_verification_failures(self, email: str) -> None:+ try:+ self._redis.delete(self._verification_key(email))+ except RedisError:+ logger.warning("Failed to reset email-registration verification failures", exc_info=True)+ return None++ @override+ def reset_login_failures(self, email: str) -> None:+ AccountService.reset_login_error_rate_limit(email)++ @staticmethod+ def _verification_key(email: str) -> str:+ return f"email_register_error_rate_limit:{email}"+++class BillingAccountRegistrationPolicyGateway(AccountRegistrationPolicyGateway):+ def __init__(self, *, enabled: bool) -> None:+ self._enabled = enabled++ @override+ def get_freeze_type(self, email: str) -> str | None:+ if not self._enabled:+ return None+ return BillingService.get_email_freeze_type(email)+++class AccountServiceRegistrationGateway(AccountRegistrationGateway):+ """Compatibility adapter around account provisioning and login internals."""++ def __init__(self, *, session_factory: sessionmaker[Session]) -> None:+ self._session_factory = session_factory++ @override+ def create(+ self,+ *,+ email: str,+ password: str,+ interface_language: str,+ timezone: str | None,+ ip_address: str,+ ) -> str:+ with self._session_factory() as session:+ try:+ account = AccountService.create_account_and_tenant(+ email=email,+ name=email,+ password=password,+ interface_language=interface_language,+ timezone=timezone,+ ip_address=ip_address,+ check_normalized_email=True,+ session=session,+ )+ except SeatsLimitExceededError as exc:+ raise EmailRegistrationSeatsLimitError from exc+ except EmailDomainSuspendedError as exc:+ raise AccountEmailDomainSuspendedError from exc+ except AccountNormalizedEmailAlreadyInUseServiceError as exc:+ raise AccountNormalizedEmailAlreadyInUseError from exc+ except AccountRegisterError as exc:+ raise AccountEmailFrozenError from exc+ return account.id++ @override+ def login(self, account_id: str, *, ip_address: str) -> AccountSessionTokens:+ with self._session_factory() as session:+ account = session.get(Account, account_id)+ if account is None:+ raise RuntimeError("newly registered account no longer exists")+ token_pair = AccountService.login(account=account, session=session, ip_address=ip_address)+ return AccountSessionTokens(+ access_token=token_pair.access_token,+ refresh_token=token_pair.refresh_token,+ csrf_token=token_pair.csrf_token,+ )diff --git a/api/services/account_email_registration_service.py b/api/services/account_email_registration_service.pynew file mode 100644index 00000000000..2379f220254--- /dev/null+++ b/api/services/account_email_registration_service.py@@ -0,0 +1,207 @@+"""Application service for the account email-registration use case."""++from typing import Protocol++from constants.languages import get_valid_language, languages+from services.account_errors import (+ AccountEmailAlreadyInUseError,+ AccountEmailDomainSuspendedError,+ AccountEmailFrozenError,+ EmailRegistrationPasswordMismatchError,+ EmailRegistrationSendIPLimitedError,+ EmailRegistrationSendRateLimitError,+ EmailRegistrationVerificationLimitError,+ InvalidEmailRegistrationAddressError,+ InvalidEmailRegistrationCodeError,+ InvalidEmailRegistrationTokenError,+)+from services.account_ports import AccountRepository+from services.entities.account_entities import (+ AccountEmailRegistrationPhase,+ AccountEmailRegistrationToken,+ AccountEmailRegistrationVerification,+ AccountSessionTokens,+)+++class EmailRegistrationTokenGateway(Protocol):+ def get(self, token: str) -> AccountEmailRegistrationToken | None: ...++ def issue(self, token_data: AccountEmailRegistrationToken) -> str: ...++ def revoke(self, token: str) -> None: ...+++class EmailRegistrationCodeGenerator(Protocol):+ def generate(self) -> str: ...+++class EmailRegistrationNotificationGateway(Protocol):+ def send_code(self, *, email: str, code: str, language: str) -> None: ...++ def send_account_exists(self, *, email: str, account_name: str, language: str) -> None: ...+++class EmailRegistrationSendLimiter(Protocol):+ def is_limited(self, email: str) -> bool: ...++ def record(self, email: str) -> None: ...++ @property+ def retry_after_minutes(self) -> int: ...+++class EmailRegistrationSecurityGateway(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: ...++ def reset_login_failures(self, email: str) -> None: ...+++class AccountRegistrationPolicyGateway(Protocol):+ def get_freeze_type(self, email: str) -> str | None: ...+++class AccountRegistrationGateway(Protocol):+ def create(+ self,+ *,+ email: str,+ password: str,+ interface_language: str,+ timezone: str | None,+ ip_address: str,+ ) -> str: ...++ def login(self, account_id: str, *, ip_address: str) -> AccountSessionTokens: ...+++class AccountEmailRegistrationService:+ def __init__(+ self,+ *,+ accounts: AccountRepository,+ tokens: EmailRegistrationTokenGateway,+ codes: EmailRegistrationCodeGenerator,+ notifications: EmailRegistrationNotificationGateway,+ send_limits: EmailRegistrationSendLimiter,+ security: EmailRegistrationSecurityGateway,+ account_policy: AccountRegistrationPolicyGateway,+ registration: AccountRegistrationGateway,+ ) -> None:+ self._accounts = accounts+ self._tokens = tokens+ self._codes = codes+ self._notifications = notifications+ self._send_limits = send_limits+ self._security = security+ self._account_policy = account_policy+ self._registration = registration++ def send_code(+ self,+ *,+ remote_ip: str,+ requested_email: str,+ requested_language: str | None,+ ) -> str:+ if self._security.is_ip_limited(remote_ip):+ raise EmailRegistrationSendIPLimitedError++ normalized_email = requested_email.lower()+ self._ensure_email_allowed(normalized_email)+ account = self._accounts.find_by_email(requested_email)+ delivery_email = account.email if account is not None else normalized_email+ if self._send_limits.is_limited(delivery_email):+ raise EmailRegistrationSendRateLimitError(self._send_limits.retry_after_minutes)++ language = requested_language if requested_language is not None and requested_language in languages else "en-US"+ code = self._codes.generate()+ token = self._tokens.issue(AccountEmailRegistrationToken(email=delivery_email, code=code))+ if account is None:+ self._notifications.send_code(email=delivery_email, code=code, language=language)+ else:+ self._notifications.send_account_exists(+ email=delivery_email,+ account_name=account.name,+ language=language,+ )+ self._send_limits.record(delivery_email)+ return token++ def verify_code(+ self,+ *,+ email: str,+ code: str,+ token: str,+ ) -> AccountEmailRegistrationVerification:+ normalized_email = email.lower()+ if self._security.is_verification_limited(normalized_email):+ raise EmailRegistrationVerificationLimitError++ token_data = self._tokens.get(token)+ if token_data is None:+ raise InvalidEmailRegistrationTokenError+ normalized_token_email = token_data.email.lower()+ if normalized_email != normalized_token_email:+ raise InvalidEmailRegistrationAddressError+ if code != token_data.code:+ self._security.record_verification_failure(normalized_email)+ raise InvalidEmailRegistrationCodeError++ self._tokens.revoke(token)+ verified_token = self._tokens.issue(+ AccountEmailRegistrationToken(+ email=normalized_email,+ code=code,+ phase=AccountEmailRegistrationPhase.REGISTER,+ )+ )+ self._security.reset_verification_failures(normalized_email)+ return AccountEmailRegistrationVerification(email=normalized_token_email, token=verified_token)++ def register(+ self,+ *,+ remote_ip: str,+ token: str,+ new_password: str,+ password_confirm: str,+ language: str | None,+ timezone: str | None,+ ) -> AccountSessionTokens:+ if new_password != password_confirm:+ raise EmailRegistrationPasswordMismatchError++ token_data = self._tokens.get(token)+ if token_data is None or token_data.phase != AccountEmailRegistrationPhase.REGISTER:+ raise InvalidEmailRegistrationTokenError+ self._tokens.revoke(token)++ normalized_email = token_data.email.lower()+ if self._accounts.find_by_email(token_data.email) is not None:+ raise AccountEmailAlreadyInUseError++ account_id = self._registration.create(+ email=normalized_email,+ password=password_confirm,+ interface_language=get_valid_language(language),+ timezone=timezone,+ ip_address=remote_ip,+ )+ tokens = self._registration.login(account_id, ip_address=remote_ip)+ self._security.reset_login_failures(normalized_email)+ return tokens++ def _ensure_email_allowed(self, email: str) -> None:+ freeze_type = self._account_policy.get_freeze_type(email)+ if freeze_type == "email_domain_suspended":+ raise AccountEmailDomainSuspendedError+ if freeze_type:+ raise AccountEmailFrozenErrordiff --git a/api/services/account_errors.py b/api/services/account_errors.pyindex c902c7d331b..115e0e6f511 100644--- a/api/services/account_errors.py+++ b/api/services/account_errors.py@@ -85,6 +85,46 @@ class AccountEmailAlreadyInUseError(AccountApplicationError):"""The target email already belongs to an account."""+class AccountNormalizedEmailAlreadyInUseError(AccountEmailAlreadyInUseError):+ """A normalized equivalent of the target email already belongs to an account."""+++class EmailRegistrationSendIPLimitedError(AccountApplicationError):+ """The caller IP exceeded the registration-email send policy."""+++class EmailRegistrationSendRateLimitError(AccountApplicationError):+ """Too many registration 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 EmailRegistrationVerificationLimitError(AccountApplicationError):+ """Too many invalid registration-code attempts were made."""+++class InvalidEmailRegistrationTokenError(AccountApplicationError):+ """The registration token is absent, malformed, or in the wrong phase."""+++class InvalidEmailRegistrationAddressError(AccountApplicationError):+ """The request address does not match the registration token."""+++class InvalidEmailRegistrationCodeError(AccountApplicationError):+ """The verification code does not match the registration token."""+++class EmailRegistrationPasswordMismatchError(AccountApplicationError):+ """The registration password confirmation does not match."""+++class EmailRegistrationSeatsLimitError(AccountApplicationError):+ """The deployment has no licensed seat available for another account."""++class EducationDiscountPausedError(AccountApplicationError):"""Education discount activation is temporarily paused."""diff --git a/api/services/account_ports.py b/api/services/account_ports.pyindex 39afd92bd1f..78792664127 100644--- a/api/services/account_ports.py+++ b/api/services/account_ports.py@@ -19,6 +19,8 @@ from services.entities.account_entities import (class AccountRepository(Protocol):def get(self, account_id: str) -> AccountSnapshot | None: ...+ def find_by_email(self, email: str) -> AccountSnapshot | None: ...+def get_credentials(self, account_id: str) -> AccountCredentials | None: ...def update_profile(self, account_id: str, changes: AccountProfileChanges) -> AccountSnapshot | None: ...diff --git a/api/services/account_service.py b/api/services/account_service.pyindex 586619abe1d..b022187e14d 100644--- a/api/services/account_service.py+++ b/api/services/account_service.py@@ -93,7 +93,6 @@ from tasks.mail_owner_transfer_task import (send_old_owner_transfer_notify_email_task,send_owner_transfer_confirm_task,)-from tasks.mail_register_task import send_email_register_mail_task, send_email_register_mail_task_when_account_existfrom tasks.mail_reset_password_task import (send_reset_password_mail_task,send_reset_password_mail_task_when_account_not_exist,@@ -157,7 +156,6 @@ class AccountService:CHANGE_EMAIL_PHASE_NEW = ChangeEmailPhase.NEW_EMAILreset_password_rate_limiter = RateLimiter(prefix="reset_password_rate_limit", max_attempts=1, time_window=60 * 1)- email_register_rate_limiter = RateLimiter(prefix="email_register_rate_limit", max_attempts=1, time_window=60 * 1)email_code_login_rate_limiter = RateLimiter(prefix="email_code_login_rate_limit", max_attempts=3, time_window=300 * 1)@@ -168,7 +166,6 @@ class AccountService:FORGOT_PASSWORD_MAX_ERROR_LIMITS = 5CHANGE_EMAIL_MAX_ERROR_LIMITS = 5OWNER_TRANSFER_MAX_ERROR_LIMITS = 5- EMAIL_REGISTER_MAX_ERROR_LIMITS = 5@staticmethoddef _resolve_role_id_by_tag(tenant_id: str, account_id: str, tag: str) -> str:@@ -679,40 +676,6 @@ class AccountService:cls.reset_password_rate_limiter.increment_rate_limit(account_email)return token- @classmethod- def send_email_register_email(- cls,- account: Account | None = None,- email: str | None = None,- language: str = "en-US",- ):- account_email = account.email if account else email- if account_email is None:- raise ValueError("Email must be provided.")-- if cls.email_register_rate_limiter.is_rate_limited(account_email):- from controllers.console.auth.error import EmailRegisterRateLimitExceededError-- raise EmailRegisterRateLimitExceededError(int(cls.email_register_rate_limiter.time_window / 60))-- code, token = cls.generate_email_register_token(account_email)-- if account:- send_email_register_mail_task_when_account_exist.delay(- language=language,- to=account_email,- account_name=account.name,- )-- else:- send_email_register_mail_task.delay(- language=language,- to=account_email,- code=code,- )- cls.email_register_rate_limiter.increment_rate_limit(account_email)- return token-@classmethoddef send_change_email_email(cls,@@ -866,19 +829,6 @@ class AccountService:)return code, token- @classmethod- def generate_email_register_token(- cls,- email: str,- code: str | None = None,- additional_data: dict[str, Any] = {},- ):- if not code:- code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])- additional_data["code"] = code- token = TokenManager.generate_token(email=email, token_type="email_register", additional_data=additional_data)- return code, token-@classmethoddef generate_change_email_token(cls,@@ -916,10 +866,6 @@ class AccountService:def revoke_reset_password_token(cls, token: str):TokenManager.revoke_token(token, "reset_password")- @classmethod- def revoke_email_register_token(cls, token: str):- TokenManager.revoke_token(token, "email_register")-@classmethoddef revoke_change_email_token(cls, token: str):TokenManager.revoke_token(token, "change_email")@@ -932,10 +878,6 @@ class AccountService:def get_reset_password_data(cls, token: str) -> dict[str, Any] | None:return TokenManager.get_token_data(token, "reset_password")- @classmethod- def get_email_register_data(cls, token: str) -> dict[str, Any] | None:- return TokenManager.get_token_data(token, "email_register")-@classmethoddef get_change_email_data(cls, token: str) -> ChangeEmailTokenData | None:token_data = TokenManager.get_token_data(token, "change_email")@@ -1066,16 +1008,6 @@ class AccountService:count = int(count) + 1redis_client.setex(key, dify_config.FORGOT_PASSWORD_LOCKOUT_DURATION, count)- @staticmethod- @redis_fallback(default_return=None)- def add_email_register_error_rate_limit(email: str) -> None:- key = f"email_register_error_rate_limit:{email}"- count = redis_client.get(key)- if count is None:- count = 0- count = int(count) + 1- redis_client.setex(key, dify_config.EMAIL_REGISTER_LOCKOUT_DURATION, count)-@staticmethod@redis_fallback(default_return=False)def is_forgot_password_error_rate_limit(email: str) -> bool:@@ -1095,24 +1027,6 @@ class AccountService:key = f"forgot_password_error_rate_limit:{email}"redis_client.delete(key)- @staticmethod- @redis_fallback(default_return=False)- def is_email_register_error_rate_limit(email: str) -> bool:- key = f"email_register_error_rate_limit:{email}"- count = redis_client.get(key)- if count is None:- return False- count = int(count)- if count > AccountService.EMAIL_REGISTER_MAX_ERROR_LIMITS:- return True- return False-- @staticmethod- @redis_fallback(default_return=None)- def reset_email_register_error_rate_limit(email: str):- key = f"email_register_error_rate_limit:{email}"- redis_client.delete(key)-@staticmethod@redis_fallback(default_return=None)def add_change_email_error_rate_limit(email: str):diff --git a/api/services/entities/account_entities.py b/api/services/entities/account_entities.pyindex 21cfc2df00d..b53a739eba2 100644--- a/api/services/entities/account_entities.py+++ b/api/services/entities/account_entities.py@@ -116,6 +116,30 @@ class AccountEmailResetResult:account: AccountSnapshot | None = None+class AccountEmailRegistrationPhase(StrEnum):+ REGISTER = "register"+++@dataclass(frozen=True, slots=True)+class AccountEmailRegistrationToken:+ email: str+ code: str+ phase: AccountEmailRegistrationPhase | None = None+++@dataclass(frozen=True, slots=True)+class AccountEmailRegistrationVerification:+ email: str+ token: str+++@dataclass(frozen=True, slots=True)+class AccountSessionTokens:+ access_token: str+ refresh_token: str+ csrf_token: str++class AccountChangeEmailPhase(StrEnum):OLD_EMAIL = "old_email"OLD_EMAIL_VERIFIED = "old_email_verified"diff --git a/api/tests/unit_tests/controllers/console/auth/test_email_register.py b/api/tests/unit_tests/controllers/console/auth/test_email_register.pyindex 7eee2e68102..7b5f859877b 100644--- a/api/tests/unit_tests/controllers/console/auth/test_email_register.py+++ b/api/tests/unit_tests/controllers/console/auth/test_email_register.py@@ -1,30 +1,57 @@-"""Unit tests for email register controller endpoints."""+"""Unit tests for the email-registration Flask adapter."""from __future__ import annotations-from collections.abc import Callable-from unittest.mock import MagicMock, patch+from collections.abc import Callable, Generator+from contextlib import contextmanager+from types import SimpleNamespace+from unittest.mock import Mock, patchimport pytestfrom flask import Flask+from pydantic import ValidationError+from controllers.console import bp as console_bpfrom controllers.console.auth.email_register import (EmailRegisterCheckApi,EmailRegisterResetApi,+ EmailRegisterResetPayload,EmailRegisterSendEmailApi,)-from controllers.console.auth.error import NormalizedEmailAlreadyInUseError-from controllers.console.error import AccountInFreezeError, EmailDomainSuspendedError+from controllers.console.auth.error import (+ EmailAlreadyInUseError,+ EmailCodeError,+ EmailRegisterLimitError,+ EmailRegisterRateLimitExceededError,+ InvalidEmailError,+ InvalidTokenError,+ NormalizedEmailAlreadyInUseError,+ PasswordMismatchError,+)+from controllers.console.error import (+ AccountInFreezeError,+ EmailDomainSuspendedError,+ EmailSendIpLimitError,+ SeatsLimitExceeded,+)from enums import DeploymentEdition-from models.account import Account-from services.entities.feature_entities import SystemFeatureModel-from services.errors.account import (+from services.account_email_registration_service import AccountEmailRegistrationService+from services.account_errors import (+ AccountEmailAlreadyInUseError,+ AccountEmailDomainSuspendedError,+ AccountEmailFrozenError,AccountNormalizedEmailAlreadyInUseError,- AccountRegisterError,-)-from services.errors.account import (- EmailDomainSuspendedError as EmailDomainSuspendedRegistrationError,+ EmailRegistrationPasswordMismatchError,+ EmailRegistrationSeatsLimitError,+ EmailRegistrationSendIPLimitedError,+ EmailRegistrationSendRateLimitError,+ EmailRegistrationVerificationLimitError,+ InvalidEmailRegistrationAddressError,+ InvalidEmailRegistrationCodeError,+ InvalidEmailRegistrationTokenError,)+from services.entities.account_entities import AccountEmailRegistrationVerification, AccountSessionTokens+from services.entities.feature_entities import SystemFeatureModel@pytest.fixture(autouse=True)@@ -32,6 +59,33 @@ def _cloud_edition(config_overrides: Callable[..., None]) -> None:config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)+@contextmanager+def _request(+ app: Flask,+ service: Mock,+ *,+ path: str,+ payload: dict[str, str],+) -> Generator[None, None, None]:+ services = SimpleNamespace(accounts=SimpleNamespace(email_registration=service))+ features = SystemFeatureModel(+ deployment_edition=DeploymentEdition.CLOUD,+ enable_email_password_login=True,+ is_allow_register=True,+ )+ with (+ patch("controllers.console.auth.email_register.application_services", return_value=services),+ patch("controllers.console.flask_admission.FeatureService.get_system_features", return_value=features),+ patch("controllers.console.auth.email_register.extract_remote_ip", return_value="127.0.0.1"),+ app.test_request_context(path, method="POST", json=payload),+ ):+ yield+++def _service() -> Mock:+ return Mock(spec=AccountEmailRegistrationService)++def test_normalized_email_conflict_exposes_a_distinct_error_code() -> None:error = NormalizedEmailAlreadyInUseError()@@ -40,321 +94,210 @@ def test_normalized_email_conflict_exposes_a_distinct_error_code() -> None:assert error.data["code"] == "normalized_email_already_in_use"-class TestEmailRegisterSendEmailApi:- @patch("controllers.console.auth.email_register.AccountService.get_account_by_email_with_case_fallback")- @patch("controllers.console.auth.email_register.AccountService.send_email_register_email")- @patch("controllers.console.auth.email_register.BillingService.get_email_freeze_type")- @patch("controllers.console.auth.email_register.AccountService.is_email_send_ip_limit", return_value=False)- @patch("controllers.console.auth.email_register.extract_remote_ip", return_value="127.0.0.1")- def test_send_email_normalizes_and_falls_back(- self,- mock_extract_ip,- mock_is_email_send_ip_limit,- mock_is_freeze,- mock_send_mail,- mock_get_account,- app: Flask,+def test_send_email_delegates_with_remote_ip(app: Flask) -> None:+ service = _service()+ service.send_code.return_value = "token-123"++ with _request(+ app,+ service,+ path="/email-register/send-email",+ payload={"email": "[email protected]", "language": "zh-Hans"},):- mock_send_mail.return_value = "token-123"- mock_is_freeze.return_value = False- account = Account(name="Invitee", email="[email protected]")- mock_get_account.return_value = account-- feature_flags = SystemFeatureModel(- deployment_edition=DeploymentEdition.COMMUNITY,- enable_email_password_login=True,- is_allow_register=True,- )- with (- patch("controllers.console.wraps.FeatureService.get_system_features", return_value=feature_flags),- ):- with app.test_request_context(- "/email-register/send-email",- method="POST",- json={"email": "[email protected]", "language": "en-US"},- ):- response = EmailRegisterSendEmailApi().post()-- assert response == {"result": "success", "data": "token-123"}- mock_is_freeze.assert_called_once_with("[email protected]")- mock_send_mail.assert_called_once_with(email="[email protected]", account=account, language="en-US")- mock_extract_ip.assert_called_once()- mock_is_email_send_ip_limit.assert_called_once_with("127.0.0.1")-- @pytest.mark.parametrize(- ("freeze_type", "expected_error"),- [- ("freeze", AccountInFreezeError),- ("email_domain_suspended", EmailDomainSuspendedError),- ],- )- @patch("controllers.console.auth.email_register.BillingService.get_email_freeze_type")- @patch("controllers.console.auth.email_register.AccountService.is_email_send_ip_limit", return_value=False)- @patch("controllers.console.auth.email_register.extract_remote_ip", return_value="127.0.0.1")- def test_send_email_rejects_frozen_email(- self,- mock_extract_ip,- mock_is_email_send_ip_limit,- mock_get_freeze_type,- app: Flask,- freeze_type,- expected_error,+ response = EmailRegisterSendEmailApi().post()++ assert response == {"result": "success", "data": "token-123"}+ assert service.send_code.call_args.kwargs == {+ "remote_ip": "127.0.0.1",+ "requested_email": "[email protected]",+ "requested_language": "zh-Hans",+ }+++ ("service_error", "http_error"),+ [+ pytest.param(EmailRegistrationSendIPLimitedError(), EmailSendIpLimitError, id="ip-limit"),+ pytest.param(EmailRegistrationSendRateLimitError(1), EmailRegisterRateLimitExceededError, id="send-limit"),+ pytest.param(AccountEmailFrozenError(), AccountInFreezeError, id="frozen"),+ pytest.param(AccountEmailDomainSuspendedError(), EmailDomainSuspendedError, id="suspended-domain"),+ ],+)+def test_send_email_translates_application_errors(+ app: Flask,+ service_error: Exception,+ http_error: type[Exception],+) -> None:+ service = _service()+ service.send_code.side_effect = service_error++ with _request(+ app,+ service,+ path="/email-register/send-email",+ payload={"email": "[email protected]"},):- mock_get_freeze_type.return_value = freeze_type- feature_flags = SystemFeatureModel(- deployment_edition=DeploymentEdition.COMMUNITY,- enable_email_password_login=True,- is_allow_register=True,- )+ with pytest.raises(http_error):+ EmailRegisterSendEmailApi().post()- with (- patch("controllers.console.wraps.FeatureService.get_system_features", return_value=feature_flags),- ):- with app.test_request_context(- "/email-register/send-email",- method="POST",- json={"email": "[email protected]"},- ):- with pytest.raises(expected_error):- EmailRegisterSendEmailApi().post()-- mock_get_freeze_type.assert_called_once_with("[email protected]")- mock_is_email_send_ip_limit.assert_called_once_with("127.0.0.1")- mock_extract_ip.assert_called_once()---class TestEmailRegisterCheckApi:- @patch("controllers.console.auth.email_register.AccountService.reset_email_register_error_rate_limit")- @patch("controllers.console.auth.email_register.AccountService.generate_email_register_token")- @patch("controllers.console.auth.email_register.AccountService.revoke_email_register_token")- @patch("controllers.console.auth.email_register.AccountService.add_email_register_error_rate_limit")- @patch("controllers.console.auth.email_register.AccountService.get_email_register_data")- @patch("controllers.console.auth.email_register.AccountService.is_email_register_error_rate_limit")- def test_validity_normalizes_email_before_checks(- self,- mock_rate_limit_check,- mock_get_data,- mock_add_rate,- mock_revoke,- mock_generate_token,- mock_reset_rate,- app: Flask,- ):- mock_rate_limit_check.return_value = False- mock_get_data.return_value = {"email": "[email protected]", "code": "4321"}- mock_generate_token.return_value = (None, "new-token")-- feature_flags = SystemFeatureModel(- deployment_edition=DeploymentEdition.COMMUNITY,- enable_email_password_login=True,- is_allow_register=True,- )- with (- patch("controllers.console.wraps.FeatureService.get_system_features", return_value=feature_flags),- ):- with app.test_request_context(- "/email-register/validity",- method="POST",- json={"email": "[email protected]", "code": "4321", "token": "token-123"},- ):- response = EmailRegisterCheckApi().post()-- assert response == {"is_valid": True, "email": "[email protected]", "token": "new-token"}- mock_rate_limit_check.assert_called_once_with("[email protected]")- mock_generate_token.assert_called_once_with(- "[email protected]", code="4321", additional_data={"phase": "register"}- )- mock_reset_rate.assert_called_once_with("[email protected]")- mock_add_rate.assert_not_called()- mock_revoke.assert_called_once_with("token-123")---class TestEmailRegisterResetApi:- @pytest.mark.parametrize(- ("service_error", "expected_error"),- [- (EmailDomainSuspendedRegistrationError(), EmailDomainSuspendedError),- (AccountNormalizedEmailAlreadyInUseError(), NormalizedEmailAlreadyInUseError),- (AccountRegisterError("frozen"), AccountInFreezeError),- ],++def test_verify_email_code_serializes_application_result(app: Flask) -> None:+ service = _service()+ service.verify_code.return_value = AccountEmailRegistrationVerification(+ email="[email protected]",+ token="verified-token",)- @patch("controllers.console.auth.email_register.AccountService.create_account_and_tenant")- def test_create_new_account_translates_freeze_errors(- self,- mock_create_account,- service_error,- expected_error,++ with _request(+ app,+ service,+ path="/email-register/validity",+ payload={"email": "[email protected]", "code": "123456", "token": "pending-token"},):- mock_create_account.side_effect = service_error-- with pytest.raises(expected_error):- EmailRegisterResetApi()._create_new_account(- email="[email protected]",- password="ValidPass123!",- )-- @patch("controllers.console.auth.email_register.AccountService.reset_login_error_rate_limit")- @patch("controllers.console.auth.email_register.AccountService.login")- @patch("controllers.console.auth.email_register.EmailRegisterResetApi._create_new_account")- @patch("controllers.console.auth.email_register.AccountService.get_account_by_email_with_case_fallback")- @patch("controllers.console.auth.email_register.AccountService.revoke_email_register_token")- @patch("controllers.console.auth.email_register.AccountService.get_email_register_data")- @patch("controllers.console.auth.email_register.extract_remote_ip", return_value="127.0.0.1")- def test_reset_creates_account_with_normalized_email(- self,- mock_extract_ip,- mock_get_data,- mock_revoke_token,- mock_get_account,- mock_create_account,- mock_login,- mock_reset_login_rate,- app: Flask,+ response = EmailRegisterCheckApi().post()++ assert response == {"is_valid": True, "email": "[email protected]", "token": "verified-token"}+ service.verify_code.assert_called_once_with(+ email="[email protected]",+ code="123456",+ token="pending-token",+ )+++ ("service_error", "http_error"),+ [+ pytest.param(EmailRegistrationVerificationLimitError(), EmailRegisterLimitError, id="attempt-limit"),+ pytest.param(InvalidEmailRegistrationTokenError(), InvalidTokenError, id="token"),+ pytest.param(InvalidEmailRegistrationAddressError(), InvalidEmailError, id="email"),+ pytest.param(InvalidEmailRegistrationCodeError(), EmailCodeError, id="code"),+ ],+)+def test_verify_email_code_translates_application_errors(+ app: Flask,+ service_error: Exception,+ http_error: type[Exception],+) -> None:+ service = _service()+ service.verify_code.side_effect = service_error++ with _request(+ app,+ service,+ path="/email-register/validity",+ payload={"email": "[email protected]", "code": "wrong", "token": "pending-token"},):- mock_get_data.return_value = {"phase": "register", "email": "[email protected]"}- mock_create_account.return_value = Account(name="Invitee", email="[email protected]")- token_pair = MagicMock()- token_pair.model_dump.return_value = {"access_token": "a", "refresh_token": "r"}- mock_login.return_value = token_pair- mock_get_account.return_value = None-- feature_flags = SystemFeatureModel(- deployment_edition=DeploymentEdition.COMMUNITY,- enable_email_password_login=True,- is_allow_register=True,- )- with (- patch("controllers.console.wraps.FeatureService.get_system_features", return_value=feature_flags),- ):- with app.test_request_context(- "/email-register",- method="POST",- json={"token": "token-123", "new_password": "ValidPass123!", "password_confirm": "ValidPass123!"},- ):- response = EmailRegisterResetApi().post()-- assert response == {"result": "success", "data": {"access_token": "a", "refresh_token": "r"}}- mock_create_account.assert_called_once_with(- email="[email protected]",- password="ValidPass123!",- timezone=None,- language=None,- ip_address="127.0.0.1",- )- mock_reset_login_rate.assert_called_once_with("[email protected]")- mock_revoke_token.assert_called_once_with("token-123")- mock_extract_ip.assert_called_once()-- @patch("controllers.console.auth.email_register.AccountService.reset_login_error_rate_limit")- @patch("controllers.console.auth.email_register.AccountService.login")- @patch("controllers.console.auth.email_register.EmailRegisterResetApi._create_new_account")- @patch("controllers.console.auth.email_register.AccountService.get_account_by_email_with_case_fallback")- @patch("controllers.console.auth.email_register.AccountService.revoke_email_register_token")- @patch("controllers.console.auth.email_register.AccountService.get_email_register_data")- @patch("controllers.console.auth.email_register.extract_remote_ip", return_value="127.0.0.1")- def test_reset_passes_timezone_to_new_account(- self,- mock_extract_ip,- mock_get_data,- mock_revoke_token,- mock_get_account,- mock_create_account,- mock_login,- mock_reset_login_rate,- app: Flask,+ with pytest.raises(http_error):+ EmailRegisterCheckApi().post()+++def test_register_delegates_and_serializes_tokens(app: Flask) -> None:+ service = _service()+ service.register.return_value = AccountSessionTokens(+ access_token="access",+ refresh_token="refresh",+ csrf_token="csrf",+ )++ with _request(+ app,+ service,+ path="/email-register",+ payload={+ "token": "verified-token",+ "new_password": "ValidPass123!",+ "password_confirm": "ValidPass123!",+ "language": "zh-Hans",+ "timezone": "Asia/Shanghai",+ },):- mock_get_data.return_value = {"phase": "register", "email": "[email protected]"}- mock_create_account.return_value = Account(name="Invitee", email="[email protected]")- token_pair = MagicMock()- token_pair.model_dump.return_value = {"access_token": "a", "refresh_token": "r"}- mock_login.return_value = token_pair- mock_get_account.return_value = None-- feature_flags = SystemFeatureModel(- deployment_edition=DeploymentEdition.COMMUNITY,- enable_email_password_login=True,- is_allow_register=True,- )- with (- patch("controllers.console.wraps.FeatureService.get_system_features", return_value=feature_flags),- ):- with app.test_request_context(- "/email-register",- method="POST",- json={- "token": "token-123",- "new_password": "ValidPass123!",- "password_confirm": "ValidPass123!",- "timezone": "Asia/Shanghai",- },- ):- response = EmailRegisterResetApi().post()-- assert response == {"result": "success", "data": {"access_token": "a", "refresh_token": "r"}}- mock_create_account.assert_called_once_with(- email="[email protected]",- password="ValidPass123!",- timezone="Asia/Shanghai",- language=None,- ip_address="127.0.0.1",- )- mock_reset_login_rate.assert_called_once_with("[email protected]")- mock_revoke_token.assert_called_once_with("token-123")- mock_extract_ip.assert_called_once()-- @patch("controllers.console.auth.email_register.AccountService.reset_login_error_rate_limit")- @patch("controllers.console.auth.email_register.AccountService.login")- @patch("controllers.console.auth.email_register.EmailRegisterResetApi._create_new_account")- @patch("controllers.console.auth.email_register.AccountService.get_account_by_email_with_case_fallback")- @patch("controllers.console.auth.email_register.AccountService.revoke_email_register_token")- @patch("controllers.console.auth.email_register.AccountService.get_email_register_data")- @patch("controllers.console.auth.email_register.extract_remote_ip", return_value="127.0.0.1")- def test_reset_passes_language_to_new_account(- self,- mock_extract_ip,- mock_get_data,- mock_revoke_token,- mock_get_account,- mock_create_account,- mock_login,- mock_reset_login_rate,- app: Flask,+ response = EmailRegisterResetApi().post()++ assert response == {+ "result": "success",+ "data": {"access_token": "access", "refresh_token": "refresh", "csrf_token": "csrf"},+ }+ assert service.register.call_args.kwargs == {+ "remote_ip": "127.0.0.1",+ "token": "verified-token",+ "new_password": "ValidPass123!",+ "password_confirm": "ValidPass123!",+ "language": "zh-Hans",+ "timezone": "Asia/Shanghai",+ }+++ ("service_error", "http_error"),+ [+ pytest.param(EmailRegistrationPasswordMismatchError(), PasswordMismatchError, id="password"),+ pytest.param(InvalidEmailRegistrationTokenError(), InvalidTokenError, id="token"),+ pytest.param(+ AccountNormalizedEmailAlreadyInUseError(),+ NormalizedEmailAlreadyInUseError,+ id="normalized-email-in-use",+ ),+ pytest.param(AccountEmailAlreadyInUseError(), EmailAlreadyInUseError, id="email-in-use"),+ pytest.param(EmailRegistrationSeatsLimitError(), SeatsLimitExceeded, id="seat-limit"),+ pytest.param(AccountEmailFrozenError(), AccountInFreezeError, id="frozen"),+ pytest.param(AccountEmailDomainSuspendedError(), EmailDomainSuspendedError, id="suspended-domain"),+ ],+)+def test_register_translates_application_errors(+ app: Flask,+ service_error: Exception,+ http_error: type[Exception],+) -> None:+ service = _service()+ service.register.side_effect = service_error++ with _request(+ app,+ service,+ path="/email-register",+ payload={+ "token": "verified-token",+ "new_password": "ValidPass123!",+ "password_confirm": "ValidPass123!",+ },):- mock_get_data.return_value = {"phase": "register", "email": "[email protected]"}- mock_create_account.return_value = Account(name="Invitee", email="[email protected]")- token_pair = MagicMock()- token_pair.model_dump.return_value = {"access_token": "a", "refresh_token": "r"}- mock_login.return_value = token_pair- mock_get_account.return_value = None-- feature_flags = SystemFeatureModel(- deployment_edition=DeploymentEdition.COMMUNITY,- enable_email_password_login=True,- is_allow_register=True,+ with pytest.raises(http_error):+ EmailRegisterResetApi().post()+++def test_reset_payload_rejects_invalid_timezone() -> None:+ with pytest.raises(ValidationError):+ EmailRegisterResetPayload.model_validate(+ {+ "token": "token-123",+ "new_password": "ValidPass123!",+ "password_confirm": "ValidPass123!",+ "timezone": "",+ })- with (- patch("controllers.console.wraps.FeatureService.get_system_features", return_value=feature_flags),- ):- with app.test_request_context(- "/email-register",- method="POST",- json={- "token": "token-123",- "new_password": "ValidPass123!",- "password_confirm": "ValidPass123!",- "language": "zh-Hans",- },- ):- response = EmailRegisterResetApi().post()-- assert response == {"result": "success", "data": {"access_token": "a", "refresh_token": "r"}}- mock_create_account.assert_called_once_with(- email="[email protected]",- password="ValidPass123!",- timezone=None,- language="zh-Hans",- ip_address="127.0.0.1",+++def test_invalid_password_is_sanitized_by_real_error_handler(caplog: pytest.LogCaptureFixture) -> None:+ app = Flask(__name__)+ app.config["TESTING"] = True+ app.register_blueprint(console_bp)+ features = SystemFeatureModel(+ deployment_edition=DeploymentEdition.CLOUD,+ enable_email_password_login=True,+ is_allow_register=True,+ )+ password_marker = "SecretMarker"++ with patch("controllers.console.flask_admission.FeatureService.get_system_features", return_value=features):+ response = app.test_client().post(+ "/console/api/email-register",+ json={+ "token": "verified-token",+ "new_password": password_marker,+ "password_confirm": password_marker,+ },)- mock_reset_login_rate.assert_called_once_with("[email protected]")- mock_revoke_token.assert_called_once_with("token-123")- mock_extract_ip.assert_called_once()++ assert response.status_code == 422+ assert password_marker not in response.get_data(as_text=True)+ assert password_marker not in caplog.textdiff --git a/api/tests/unit_tests/controllers/console/auth/test_email_register_language.py b/api/tests/unit_tests/controllers/console/auth/test_email_register_language.pydeleted file mode 100644index e8331bda8cc..00000000000--- a/api/tests/unit_tests/controllers/console/auth/test_email_register_language.py+++ /dev/null@@ -1,44 +0,0 @@-from unittest.mock import ANY, patch--import pytest-from pydantic import ValidationError--from controllers.console.auth.email_register import EmailRegisterResetApi, EmailRegisterResetPayload-from models.account import Account---@patch("controllers.console.auth.email_register.AccountService.create_account_and_tenant")-def test_create_new_account_uses_requested_language(mock_create_account):- account = Account(name="Invitee", email="[email protected]")- mock_create_account.return_value = account-- result = EmailRegisterResetApi()._create_new_account(- "[email protected]",- "ValidPass123!",- timezone="Asia/Shanghai",- language="zh-Hans",- )-- assert result is account- mock_create_account.assert_called_once_with(- email="[email protected]",- name="[email protected]",- password="ValidPass123!",- interface_language="zh-Hans",- timezone="Asia/Shanghai",- ip_address=None,- check_normalized_email=True,- session=ANY,- )---def test_reset_payload_rejects_invalid_timezone():- with pytest.raises(ValidationError):- EmailRegisterResetPayload.model_validate(- {- "token": "token-123",- "new_password": "ValidPass123!",- "password_confirm": "ValidPass123!",- "timezone": "",- }- )diff --git a/api/tests/unit_tests/controllers/console/test_wraps.py b/api/tests/unit_tests/controllers/console/test_wraps.pyindex be562c20133..20a7291ec66 100644--- a/api/tests/unit_tests/controllers/console/test_wraps.py+++ b/api/tests/unit_tests/controllers/console/test_wraps.py@@ -196,6 +196,64 @@ class TestCurrentContextInjection:login_required.assert_called_once()account_initialization_required.assert_called_once()+ def test_console_email_registration_admission_checks_features_once(self):+ features = SimpleNamespace(enable_email_password_login=True, is_allow_register=True)+ with (+ patch(+ "controllers.console.flask_admission.setup_required", side_effect=lambda view: view+ ) as setup_required,+ patch(+ "controllers.console.flask_admission.FeatureService.get_system_features",+ return_value=features,+ ) as get_system_features,+ ):++ class Handler:+ @flask_admission.console_email_registration_admission+ def post(self):+ return "ok"++ with Flask(__name__).test_request_context():+ result = Handler().post()++ assert result == "ok"+ setup_required.assert_called_once()+ get_system_features.assert_called_once_with()++ @pytest.mark.parametrize(+ ("enable_email_password_login", "is_allow_register"),+ [+ pytest.param(False, True, id="password-login-disabled"),+ pytest.param(True, False, id="registration-disabled"),+ ],+ )+ def test_console_email_registration_admission_rejects_disabled_features(+ self,+ enable_email_password_login: bool,+ is_allow_register: bool,+ ) -> None:+ features = SimpleNamespace(+ enable_email_password_login=enable_email_password_login,+ is_allow_register=is_allow_register,+ )+ with (+ patch("controllers.console.flask_admission.setup_required", side_effect=lambda view: view),+ patch(+ "controllers.console.flask_admission.FeatureService.get_system_features",+ return_value=features,+ ),+ ):++ class Handler:+ @flask_admission.console_email_registration_admission+ def post(self):+ return "ok"++ with Flask(__name__).test_request_context(), pytest.raises(HTTPException) as exc_info:+ Handler().post()++ assert exc_info.value.code == 403+def test_console_account_admission_preserves_route_kwarg_named_request_context(self):current_user = make_account()diff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.pyindex 1cf77a1f27b..ee3d2125204 100644--- a/api/tests/unit_tests/extensions/test_ext_application_services.py+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py@@ -32,6 +32,12 @@ from services.account_activation_adapters import (RegisterServiceInvitationTokenStore,)from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGateway+from services.account_email_registration_adapters import (+ AccountServiceRegistrationGateway,+ BillingAccountRegistrationPolicyGateway,+ RedisEmailRegistrationSecurityGateway,+ TokenManagerEmailRegistrationTokenGateway,+)from services.app_site_service import AppSiteServicefrom services.auth.data_source_api_key_auth_service import DataSourceApiKeyAuthServicefrom services.billing_portal_service import BillingPortalService@@ -367,6 +373,13 @@ def test_build_application_services_wires_account_profile_repository(assert services.accounts.initialization._accounts is accountsassert not services.accounts.initialization._invitation_requiredassert services.accounts.change_email._accounts is accounts+ email_registration = services.accounts.email_registration+ assert email_registration._accounts is accounts+ assert isinstance(email_registration._tokens, TokenManagerEmailRegistrationTokenGateway)+ assert isinstance(email_registration._security, RedisEmailRegistrationSecurityGateway)+ assert isinstance(email_registration._account_policy, BillingAccountRegistrationPolicyGateway)+ assert isinstance(email_registration._registration, AccountServiceRegistrationGateway)+ assert email_registration._registration._session_factory is sqlite_session_factoryassert services.accounts.education._accounts is accountsassert services.accounts.deletion._accounts is accountsassert services.accounts.deletion._memberships is services.workspace_queries._workspacesdiff --git a/api/tests/unit_tests/repositories/test_account_repository.py b/api/tests/unit_tests/repositories/test_account_repository.pyindex daab5e6e7c3..945d2c7ddd6 100644--- a/api/tests/unit_tests/repositories/test_account_repository.py+++ b/api/tests/unit_tests/repositories/test_account_repository.py@@ -97,6 +97,20 @@ def test_account_repository_updates_password(assert persisted.password_salt == "new-salt"+def test_account_repository_finds_email_with_lowercase_fallback(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _persist_account(sqlite_session)+ repository = SQLAlchemyAccountRepository(sqlite_session_factory)++ account = repository.find_by_email("[email protected]")++ assert account is not None+ assert account.id == "account-1"+ assert account.email == "[email protected]"++def test_account_integration_repository_lists_integrations(sqlite_session: Session,sqlite_session_factory: sessionmaker[Session],diff --git a/api/tests/unit_tests/services/test_account_email_registration_adapters.py b/api/tests/unit_tests/services/test_account_email_registration_adapters.pynew file mode 100644index 00000000000..14d2fd725f2--- /dev/null+++ b/api/tests/unit_tests/services/test_account_email_registration_adapters.py@@ -0,0 +1,176 @@+from unittest.mock import Mock, patch++import pytest+from sqlalchemy.orm import Session, sessionmaker++from extensions.ext_redis import RedisClientWrapper+from models.account import Account+from services.account_email_registration_adapters import (+ AccountServiceRegistrationGateway,+ BillingAccountRegistrationPolicyGateway,+ RedisEmailRegistrationSecurityGateway,+ TokenManagerEmailRegistrationTokenGateway,+)+from services.account_errors import (+ AccountEmailDomainSuspendedError,+ AccountNormalizedEmailAlreadyInUseError,+ EmailRegistrationSeatsLimitError,+)+from services.account_service import TokenPair+from services.entities.account_entities import AccountEmailRegistrationPhase, AccountEmailRegistrationToken+from services.errors.account import (+ AccountNormalizedEmailAlreadyInUseError as AccountNormalizedEmailAlreadyInUseServiceError,+)+from services.errors.account import EmailDomainSuspendedError, SeatsLimitExceededError+++def test_token_gateway_rejects_malformed_payload() -> None:+ gateway = TokenManagerEmailRegistrationTokenGateway()++ with patch(+ "services.account_email_registration_adapters.TokenManager.get_token_data",+ return_value={"email": "[email protected]", "phase": "unknown"},+ ):+ assert gateway.get("token") is None+++def test_token_gateway_issues_verified_registration_state() -> None:+ gateway = TokenManagerEmailRegistrationTokenGateway()+ token_data = AccountEmailRegistrationToken(+ email="[email protected]",+ code="123456",+ phase=AccountEmailRegistrationPhase.REGISTER,+ )++ with patch(+ "services.account_email_registration_adapters.TokenManager.generate_token",+ return_value="token",+ ) as generate_token:+ assert gateway.issue(token_data) == "token"++ generate_token.assert_called_once_with(+ email="[email protected]",+ token_type="email_register",+ additional_data={"code": "123456", "phase": "register"},+ )+++def test_security_gateway_delegates_ip_limit_to_existing_policy_owner() -> None:+ redis = Mock(spec=RedisClientWrapper)+ gateway = RedisEmailRegistrationSecurityGateway(+ redis=redis,+ verification_failure_limit=5,+ verification_lockout_duration=600,+ )++ with patch(+ "services.account_email_registration_adapters.AccountService.is_email_send_ip_limit",+ return_value=False,+ ) as is_email_send_ip_limit:+ assert gateway.is_ip_limited("127.0.0.1") is False++ is_email_send_ip_limit.assert_called_once_with("127.0.0.1")+ redis.get.assert_not_called()+++def test_security_gateway_uses_registration_and_login_keys() -> None:+ redis = Mock(spec=RedisClientWrapper)+ redis.get.return_value = 1+ gateway = RedisEmailRegistrationSecurityGateway(+ redis=redis,+ verification_failure_limit=5,+ verification_lockout_duration=600,+ )++ with patch(+ "services.account_email_registration_adapters.AccountService.reset_login_error_rate_limit"+ ) as reset_login_error_rate_limit:+ gateway.record_verification_failure("[email protected]")+ gateway.reset_verification_failures("[email protected]")+ gateway.reset_login_failures("[email protected]")++ redis.setex.assert_called_once_with("email_register_error_rate_limit:[email protected]", 600, 2)+ redis.delete.assert_called_once_with("email_register_error_rate_limit:[email protected]")+ reset_login_error_rate_limit.assert_called_once_with("[email protected]")+++def test_billing_policy_is_disabled_outside_cloud() -> None:+ gateway = BillingAccountRegistrationPolicyGateway(enabled=False)++ with patch("services.account_email_registration_adapters.BillingService.get_email_freeze_type") as freeze_type:+ assert gateway.get_freeze_type("[email protected]") is None++ freeze_type.assert_not_called()+++ ("service_error", "application_error"),+ [+ pytest.param(SeatsLimitExceededError(), EmailRegistrationSeatsLimitError, id="seat-limit"),+ pytest.param(EmailDomainSuspendedError(), AccountEmailDomainSuspendedError, id="suspended-domain"),+ pytest.param(+ AccountNormalizedEmailAlreadyInUseServiceError(),+ AccountNormalizedEmailAlreadyInUseError,+ id="normalized-email-in-use",+ ),+ ],+)+def test_registration_gateway_translates_account_provisioning_errors(+ sqlite_session_factory: sessionmaker[Session],+ service_error: Exception,+ application_error: type[Exception],+) -> None:+ gateway = AccountServiceRegistrationGateway(session_factory=sqlite_session_factory)++ with patch(+ "services.account_email_registration_adapters.AccountService.create_account_and_tenant",+ side_effect=service_error,+ ):+ with pytest.raises(application_error):+ gateway.create(+ email="[email protected]",+ password="ValidPass123!",+ interface_language="en-US",+ timezone=None,+ ip_address="127.0.0.1",+ )+++def test_registration_gateway_owns_short_lived_sessions(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ gateway = AccountServiceRegistrationGateway(session_factory=sqlite_session_factory)++ def create_account(*, session: Session, **_: object) -> Account:+ account = Account(name="[email protected]", email="[email protected]")+ account.id = "account-1"+ session.add(account)+ session.commit()+ return account++ with patch(+ "services.account_email_registration_adapters.AccountService.create_account_and_tenant",+ side_effect=create_account,+ ) as create_account_and_tenant:+ account_id = gateway.create(+ email="[email protected]",+ password="ValidPass123!",+ interface_language="en-US",+ timezone=None,+ ip_address="127.0.0.1",+ )++ assert create_account_and_tenant.call_args.kwargs["check_normalized_email"] is True+ sqlite_session.expire_all()+ assert sqlite_session.get(Account, account_id) is not None++ with patch(+ "services.account_email_registration_adapters.AccountService.login",+ return_value=TokenPair(access_token="access", refresh_token="refresh", csrf_token="csrf"),+ ) as login:+ tokens = gateway.login(account_id, ip_address="127.0.0.1")++ assert tokens.access_token == "access"+ assert login.call_args.kwargs["account"].id == account_id+ assert isinstance(login.call_args.kwargs["session"], Session)diff --git a/api/tests/unit_tests/services/test_account_email_registration_service.py b/api/tests/unit_tests/services/test_account_email_registration_service.pynew file mode 100644index 00000000000..b3091f51438--- /dev/null+++ b/api/tests/unit_tests/services/test_account_email_registration_service.py@@ -0,0 +1,267 @@+from __future__ import annotations++from datetime import datetime+from unittest.mock import Mock++import pytest++from services.account_email_registration_service import (+ AccountEmailRegistrationService,+ AccountRegistrationGateway,+ AccountRegistrationPolicyGateway,+ EmailRegistrationCodeGenerator,+ EmailRegistrationNotificationGateway,+ EmailRegistrationSecurityGateway,+ EmailRegistrationSendLimiter,+ EmailRegistrationTokenGateway,+)+from services.account_errors import (+ AccountEmailAlreadyInUseError,+ AccountEmailDomainSuspendedError,+ EmailRegistrationPasswordMismatchError,+ InvalidEmailRegistrationCodeError,+ InvalidEmailRegistrationTokenError,+)+from services.account_ports import AccountRepository+from services.entities.account_entities import (+ AccountEmailRegistrationPhase,+ AccountEmailRegistrationToken,+ AccountSessionTokens,+ AccountSnapshot,+)+++def _account(*, email: str = "[email protected]") -> AccountSnapshot:+ return AccountSnapshot(+ id="account-1",+ name="Stored 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[AccountEmailRegistrationService, dict[str, Mock]]:+ dependencies = {+ "accounts": Mock(spec=AccountRepository),+ "tokens": Mock(spec=EmailRegistrationTokenGateway),+ "codes": Mock(spec=EmailRegistrationCodeGenerator),+ "notifications": Mock(spec=EmailRegistrationNotificationGateway),+ "send_limits": Mock(spec=EmailRegistrationSendLimiter),+ "security": Mock(spec=EmailRegistrationSecurityGateway),+ "account_policy": Mock(spec=AccountRegistrationPolicyGateway),+ "registration": Mock(spec=AccountRegistrationGateway),+ }+ service = AccountEmailRegistrationService(+ accounts=dependencies["accounts"],+ tokens=dependencies["tokens"],+ codes=dependencies["codes"],+ notifications=dependencies["notifications"],+ send_limits=dependencies["send_limits"],+ security=dependencies["security"],+ account_policy=dependencies["account_policy"],+ registration=dependencies["registration"],+ )+ dependencies["accounts"].find_by_email.return_value = None+ dependencies["codes"].generate.return_value = "123456"+ dependencies["tokens"].issue.return_value = "token-1"+ 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["account_policy"].get_freeze_type.return_value = None+ return service, dependencies+++def test_send_code_uses_case_fallback_account_and_existing_account_notification() -> None:+ service, dependencies = _service()+ dependencies["accounts"].find_by_email.return_value = _account(email="[email protected]")++ token = service.send_code(+ remote_ip="127.0.0.1",+ requested_email="[email protected]",+ requested_language="zh-Hans",+ )++ assert token == "token-1"+ dependencies["accounts"].find_by_email.assert_called_once_with("[email protected]")+ dependencies["tokens"].issue.assert_called_once_with(+ AccountEmailRegistrationToken(email="[email protected]", code="123456")+ )+ dependencies["notifications"].send_account_exists.assert_called_once_with(+ email="[email protected]",+ account_name="Stored Account",+ language="zh-Hans",+ )+ dependencies["send_limits"].record.assert_called_once_with("[email protected]")+++def test_send_code_normalizes_new_account_email_and_language() -> None:+ service, dependencies = _service()++ service.send_code(+ remote_ip="127.0.0.1",+ requested_email="[email protected]",+ requested_language="unsupported",+ )++ dependencies["notifications"].send_code.assert_called_once_with(+ email="[email protected]",+ code="123456",+ language="en-US",+ )+++def test_send_code_rejects_suspended_domain_before_account_lookup() -> None:+ service, dependencies = _service()+ dependencies["account_policy"].get_freeze_type.return_value = "email_domain_suspended"++ with pytest.raises(AccountEmailDomainSuspendedError):+ service.send_code(+ remote_ip="127.0.0.1",+ requested_email="[email protected]",+ requested_language=None,+ )++ dependencies["accounts"].find_by_email.assert_not_called()+++def test_verify_code_rotates_token_into_register_phase() -> None:+ service, dependencies = _service()+ dependencies["tokens"].get.return_value = AccountEmailRegistrationToken(+ email="[email protected]",+ code="123456",+ )+ dependencies["tokens"].issue.return_value = "verified-token"++ verification = service.verify_code(+ email="[email protected]",+ code="123456",+ token="pending-token",+ )++ assert verification.email == "[email protected]"+ assert verification.token == "verified-token"+ dependencies["tokens"].revoke.assert_called_once_with("pending-token")+ dependencies["tokens"].issue.assert_called_once_with(+ AccountEmailRegistrationToken(+ email="[email protected]",+ code="123456",+ phase=AccountEmailRegistrationPhase.REGISTER,+ )+ )+ dependencies["security"].reset_verification_failures.assert_called_once_with("[email protected]")+++def test_verify_code_records_failure_without_consuming_token() -> None:+ service, dependencies = _service()+ dependencies["tokens"].get.return_value = AccountEmailRegistrationToken(+ email="[email protected]",+ code="123456",+ )++ with pytest.raises(InvalidEmailRegistrationCodeError):+ service.verify_code(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_register_creates_account_and_logs_it_in() -> None:+ service, dependencies = _service()+ dependencies["tokens"].get.return_value = AccountEmailRegistrationToken(+ email="[email protected]",+ code="123456",+ phase=AccountEmailRegistrationPhase.REGISTER,+ )+ dependencies["registration"].create.return_value = "account-1"+ expected_tokens = AccountSessionTokens(access_token="access", refresh_token="refresh", csrf_token="csrf")+ dependencies["registration"].login.return_value = expected_tokens++ tokens = service.register(+ remote_ip="127.0.0.1",+ token="verified-token",+ new_password="ValidPass123!",+ password_confirm="ValidPass123!",+ language="zh-Hans",+ timezone="Asia/Shanghai",+ )++ assert tokens == expected_tokens+ dependencies["tokens"].revoke.assert_called_once_with("verified-token")+ dependencies["accounts"].find_by_email.assert_called_once_with("[email protected]")+ dependencies["registration"].create.assert_called_once_with(+ email="[email protected]",+ password="ValidPass123!",+ interface_language="zh-Hans",+ timezone="Asia/Shanghai",+ ip_address="127.0.0.1",+ )+ dependencies["registration"].login.assert_called_once_with("account-1", ip_address="127.0.0.1")+ dependencies["security"].reset_login_failures.assert_called_once_with("[email protected]")+++def test_register_rejects_password_mismatch_before_reading_token() -> None:+ service, dependencies = _service()++ with pytest.raises(EmailRegistrationPasswordMismatchError):+ service.register(+ remote_ip="127.0.0.1",+ token="verified-token",+ new_password="ValidPass123!",+ password_confirm="DifferentPass123!",+ language=None,+ timezone=None,+ )++ dependencies["tokens"].get.assert_not_called()+++def test_register_requires_verified_registration_phase() -> None:+ service, dependencies = _service()+ dependencies["tokens"].get.return_value = AccountEmailRegistrationToken(+ email="[email protected]",+ code="123456",+ )++ with pytest.raises(InvalidEmailRegistrationTokenError):+ service.register(+ remote_ip="127.0.0.1",+ token="pending-token",+ new_password="ValidPass123!",+ password_confirm="ValidPass123!",+ language=None,+ timezone=None,+ )++ dependencies["tokens"].revoke.assert_not_called()+++def test_register_consumes_token_before_rejecting_existing_account() -> None:+ service, dependencies = _service()+ dependencies["tokens"].get.return_value = AccountEmailRegistrationToken(+ email="[email protected]",+ code="123456",+ phase=AccountEmailRegistrationPhase.REGISTER,+ )+ dependencies["accounts"].find_by_email.return_value = _account(email="[email protected]")++ with pytest.raises(AccountEmailAlreadyInUseError):+ service.register(+ remote_ip="127.0.0.1",+ token="verified-token",+ new_password="ValidPass123!",+ password_confirm="ValidPass123!",+ language=None,+ timezone=None,+ )++ dependencies["tokens"].revoke.assert_called_once_with("verified-token")+ dependencies["registration"].create.assert_not_called()