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 account login service and consolidate adapters (#41184)
Byron.wangb015aa416fd9
diff --git a/api/.importlinter b/api/.importlinterindex 54067b553da..53da8e4c6c5 100644--- a/api/.importlinter+++ b/api/.importlinter@@ -214,10 +214,13 @@ source_modules =services.account_forgot_password_serviceservices.account_initialization_serviceservices.account_integration_service+ services.account_login_serviceservices.account_password_serviceservices.account_portsservices.account_profile_serviceservices.entities.account_entities+ services.entities.account_login_entities+ services.entities.auth_audit_entitiesforbidden_modules =configscontrollersdiff --git a/api/controllers/console/auth/login.py b/api/controllers/console/auth/login.pyindex 4a06243877c..e17325cc269 100644--- a/api/controllers/console/auth/login.py+++ b/api/controllers/console/auth/login.py@@ -1,16 +1,12 @@-import logging+from http import HTTPStatus+from typing import Neverfrom uuid import UUIDimport flask_loginfrom flask import make_response, requestfrom flask_restx import Resourcefrom pydantic import BaseModel, Field, field_validator-from sqlalchemy.orm import Session-from werkzeug.exceptions import Unauthorized-import services-from configs import dify_config-from constants.languages import get_valid_languagefrom controllers.common.fields import (SimpleResultDataResponse,SimpleResultMessageResponse,@@ -18,16 +14,17 @@ from controllers.common.fields import (SimpleResultResponse,)from controllers.common.schema import register_response_schema_models, register_schema_models-from controllers.common.session import with_sessionfrom controllers.console import console_nsfrom controllers.console.auth.error import (AuthenticationFailedError,EmailCodeError,+ EmailCodeLoginRateLimitExceededError,EmailCodeLoginServiceUnavailableError,EmailPasswordLoginLimitError,InvalidEmailError,InvalidTokenError,NormalizedEmailAlreadyInUseError,+ PasswordResetRateLimitExceededError,TurnstileServiceUnavailableError,TurnstileVerificationFailedError,)@@ -37,6 +34,7 @@ from controllers.console.error import (AccountNotFound,EmailDomainSuspendedError,EmailSendIpLimitError,+ InvalidAccountPasswordRequestError,NotAllowedCreateWorkspace,SeatsLimitExceeded,WorkspacesLimitExceeded,@@ -47,12 +45,11 @@ from controllers.console.wraps import (email_password_login_enabled,model_validate,setup_required,- with_current_user,)-from enums import DeploymentEdition-from extensions.ext_database import db-from libs.helper import EmailStr, extract_remote_ip+from extensions.ext_application_services import application_services+from libs.helper import EmailStr, dump_response, extract_remote_ipfrom libs.helper import timezone as validate_timezone_string+from libs.login import current_account_with_tenant_optionalfrom libs.token import (clear_access_token_from_cookie,clear_csrf_token_from_cookie,@@ -62,34 +59,14 @@ from libs.token import (set_csrf_token_to_cookie,set_refresh_token_to_cookie,)-from models.account import Account-from services.account_service import AccountService, InvitationDetailDict, RegisterService, TenantService-from services.billing_service import BillingService-from services.email_code_login_challenge import (- EmailCodeLoginChallengeStatus,- EmailCodeLoginChallengeUnavailableError,-)-from services.entities.auth_entities import LoginFailureReason, LoginPayloadBase-from services.errors.account import (- AccountNormalizedEmailAlreadyInUseError,- AccountRegisterError,- RefreshTokenAccountNotFoundError,- RefreshTokenNotFoundError,- SeatsLimitExceededError,-)-from services.errors.account import (- EmailDomainSuspendedError as EmailDomainSuspendedRegistrationError,-)-from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkspacesLimitExceededError-from services.system_feature_service import SystemFeatureService-from services.turnstile_service import (- EMAIL_CODE_VERIFY_ACTION,- TurnstileChallengeRejectedError,- TurnstileService,- TurnstileUpstreamError,+from services import account_errors+from services.entities.account_login_entities import (+ AuthTokenPair,+ EmailCodeLoginCommand,+ EmailCodeSendCommand,+ PasswordLoginCommand,)--logger = logging.getLogger(__name__)+from services.entities.auth_entities import LoginPayloadBaseclass LoginPayload(LoginPayloadBase):@@ -152,98 +129,43 @@ class LoginApi(Resource):@model_validate(LoginPayload)def post(self, req_data: LoginPayload):"""Authenticate user and login."""- request_email = req_data.email- normalized_email = request_email.lower()-- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:- freeze_type = BillingService.get_email_freeze_type(normalized_email)- if freeze_type:- _log_console_login_failure(email=normalized_email, reason=LoginFailureReason.ACCOUNT_IN_FREEZE)- if freeze_type == "email_domain_suspended":- raise EmailDomainSuspendedError()- raise AccountInFreezeError()-- is_login_error_rate_limit = AccountService.is_login_error_rate_limit(normalized_email)- if is_login_error_rate_limit:- _log_console_login_failure(email=normalized_email, reason=LoginFailureReason.LOGIN_RATE_LIMITED)- raise EmailPasswordLoginLimitError()-- invite_token = req_data.invite_token- invitation_data: InvitationDetailDict | None = None- if invite_token:- invitation_data = RegisterService.get_invitation_with_case_fallback(- None, request_email, invite_token, session=db.session()- )- if invitation_data is None:- invite_token = None-try:- if invitation_data:- data = invitation_data.get("data", {})- invitee_email = data.get("email") if data else None- invitee_email_normalized = invitee_email.lower() if isinstance(invitee_email, str) else invitee_email- if invitee_email_normalized != normalized_email:- _log_console_login_failure(- email=normalized_email,- reason=LoginFailureReason.INVALID_INVITATION_EMAIL,- )- raise InvalidEmailError()- account = _authenticate_account_with_case_fallback(- request_email, normalized_email, req_data.password, invite_token+ result = application_services().accounts.authentication.login_with_password(+ PasswordLoginCommand(+ email=req_data.email,+ password=req_data.password,+ invite_token=req_data.invite_token,+ ip_address=extract_remote_ip(request),+ ))- except services.errors.account.AccountLoginError:- _log_console_login_failure(email=normalized_email, reason=LoginFailureReason.ACCOUNT_BANNED)- raise AccountBannedError()- except services.errors.account.AccountPasswordError as exc:- AccountService.add_login_error_rate_limit(normalized_email)- _log_console_login_failure(email=normalized_email, reason=LoginFailureReason.INVALID_CREDENTIALS)- raise AuthenticationFailedError() from exc- tenants = TenantService.get_join_tenants(account, session=db.session())- if len(tenants) == 0:- if (- SystemFeatureService.is_workspace_creation_allowed()- and not SystemFeatureService.get_license().workspaces.is_available()- ):- raise WorkspacesLimitExceeded()- else:- return SimpleResultOptionalDataResponse(- result="fail",- data="workspace not found, please contact system admin to invite you to join in a workspace",- ).model_dump(mode="json")-- token_pair = AccountService.login(account=account, session=db.session(), ip_address=extract_remote_ip(request))- AccountService.reset_login_error_rate_limit(normalized_email)-- # Create response with cookies instead of returning tokens in body- # response-contract:ignore cookie-bearing Flask response- response = make_response(- SimpleResultOptionalDataResponse(result="success").model_dump(mode="json", exclude_none=True)- )-- set_access_token_to_cookie(request, response, token_pair.access_token)- set_refresh_token_to_cookie(request, response, token_pair.refresh_token)- set_csrf_token_to_cookie(request, response, token_pair.csrf_token)-- return response+ except account_errors.AccountApplicationError as error:+ _raise_request_error(error)++ if not result.workspace_found or result.token_pair is None:+ return dump_response(+ SimpleResultOptionalDataResponse,+ {+ "result": "fail",+ "data": "workspace not found, please contact system admin to invite you to join in a workspace",+ },+ )+ return _token_response(result.token_pair, SimpleResultOptionalDataResponse, {"result": "success"})@console_ns.route("/logout")class LogoutApi(Resource):@setup_required@console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__])- @with_current_user- def post(self, account: Account):- # response-contract:ignore cookie-bearing Flask response- response = make_response(SimpleResultResponse(result="success").model_dump(mode="json"))- if not isinstance(account, flask_login.AnonymousUserMixin):- AccountService.logout(account=account)+ def post(self):+ account, _ = current_account_with_tenant_optional()+ if account is not None:+ application_services().accounts.authentication.logout(account.id)flask_login.logout_user()- # Clear cookies on logout+ response = make_response(dump_response(SimpleResultResponse, {"result": "success"}))clear_access_token_from_cookie(response)clear_refresh_token_from_cookie(response)clear_csrf_token_from_cookie(response)-return response@@ -255,27 +177,15 @@ class ResetPasswordSendEmailApi(Resource):@console_ns.response(200, "Success", console_ns.models[SimpleResultDataResponse.__name__])@model_validate(EmailPayload)def post(self, req_data: EmailPayload):- normalized_email = req_data.email.lower()-- if req_data.language is not None and req_data.language == "zh-Hans":- language = "zh-Hans"- else:- language = "en-US"try:- account = _get_account_with_case_fallback(req_data.email)- except EmailDomainSuspendedRegistrationError as exc:- raise EmailDomainSuspendedError() from exc- except AccountRegisterError as exc:- raise AccountInFreezeError() from exc-- token = AccountService.send_reset_password_email(- email=normalized_email,- account=account,- language=language,- is_allow_register=SystemFeatureService.is_registration_allowed(),- )-- return SimpleResultDataResponse(result="success", data=token).model_dump(mode="json")+ token = application_services().accounts.authentication.send_reset_password_email(+ email=req_data.email,+ language=req_data.language,+ ip_address=extract_remote_ip(request),+ )+ except account_errors.AccountApplicationError as error:+ _raise_request_error(error)+ return dump_response(SimpleResultDataResponse, {"result": "success", "data": token})@console_ns.route("/email-code-login")@@ -285,42 +195,18 @@ class EmailCodeLoginSendEmailApi(Resource):@console_ns.response(200, "Success", console_ns.models[SimpleResultDataResponse.__name__])@model_validate(EmailCodeSendPayload)def post(self, req_data: EmailCodeSendPayload):- normalized_email = req_data.email.lower()-- ip_address = extract_remote_ip(request)- if AccountService.is_email_send_ip_limit(ip_address):- raise EmailSendIpLimitError()-- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:- try:- TurnstileService.verify(token=req_data.turnstile_token, remote_ip=ip_address)- except TurnstileChallengeRejectedError as exc:- logger.info("Turnstile rejected an email-code login challenge")- raise TurnstileVerificationFailedError() from exc- except TurnstileUpstreamError as exc:- logger.warning("Turnstile verification is unavailable", exc_info=True)- raise TurnstileServiceUnavailableError() from exc-- if req_data.language is not None and req_data.language == "zh-Hans":- language = "zh-Hans"- else:- language = "en-US"try:- account = _get_account_with_case_fallback(req_data.email)- except EmailDomainSuspendedRegistrationError as exc:- raise EmailDomainSuspendedError() from exc- except AccountRegisterError as exc:- raise AccountInFreezeError() from exc-- if account is None:- if SystemFeatureService.is_registration_allowed():- token = AccountService.send_email_code_login_email(email=normalized_email, language=language)- else:- raise AccountNotFound()- else:- token = AccountService.send_email_code_login_email(account=account, language=language)-- return SimpleResultDataResponse(result="success", data=token).model_dump(mode="json")+ token = application_services().accounts.authentication.send_email_code(+ EmailCodeSendCommand(+ email=req_data.email,+ language=req_data.language,+ turnstile_token=req_data.turnstile_token,+ ip_address=extract_remote_ip(request),+ )+ )+ except account_errors.AccountApplicationError as error:+ _raise_request_error(error)+ return dump_response(SimpleResultDataResponse, {"result": "success", "data": token})@console_ns.route("/email-code-login/validity")@@ -331,177 +217,95 @@ class EmailCodeLoginApi(Resource):@decrypt_code_field@model_validate(EmailCodeLoginPayload)def post(self, req_data: EmailCodeLoginPayload):-- original_email = req_data.email- user_email = original_email.lower()- language = req_data.language- ip_address = extract_remote_ip(request)-- # ``code`` is Base64 on the wire and is decoded by- # ``decrypt_code_field`` before model validation reaches this handler.- if len(req_data.code) != 6 or not req_data.code.isascii() or not req_data.code.isdigit():- _log_console_login_failure(email=user_email, reason=LoginFailureReason.INVALID_EMAIL_CODE)- raise EmailCodeError()-- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD and (- dify_config.TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED or req_data.turnstile_token- ):- try:- TurnstileService.verify(- token=req_data.turnstile_token,- remote_ip=ip_address,- expected_action=EMAIL_CODE_VERIFY_ACTION,- )- except TurnstileChallengeRejectedError as exc:- logger.info("Turnstile rejected an email-code verification challenge")- raise TurnstileVerificationFailedError() from exc- except TurnstileUpstreamError as exc:- logger.warning("Turnstile verification is unavailable", exc_info=True)- raise TurnstileServiceUnavailableError() from exc-- try:- verification = AccountService.verify_email_code_login_challenge(- email=user_email,- code=req_data.code,- token=str(req_data.token),- )- except EmailCodeLoginChallengeUnavailableError as exc:- logger.warning("Email-code challenge verification is unavailable", exc_info=True)- raise EmailCodeLoginServiceUnavailableError() from exc-- if verification.status == EmailCodeLoginChallengeStatus.INVALID_TOKEN:- _log_console_login_failure(email=user_email, reason=LoginFailureReason.INVALID_EMAIL_CODE_TOKEN)- raise InvalidTokenError()-- if verification.status == EmailCodeLoginChallengeStatus.EMAIL_MISMATCH:- _log_console_login_failure(email=user_email, reason=LoginFailureReason.EMAIL_CODE_EMAIL_MISMATCH)- raise InvalidEmailError()-- if verification.status in {- EmailCodeLoginChallengeStatus.INVALID_CODE,- EmailCodeLoginChallengeStatus.EXHAUSTED,- }:- _log_console_login_failure(email=user_email, reason=LoginFailureReason.INVALID_EMAIL_CODE)- raise EmailCodeError()-try:- account = _get_account_with_case_fallback(original_email)- except Unauthorized as exc:- _log_console_login_failure(email=user_email, reason=LoginFailureReason.ACCOUNT_BANNED)- raise AccountBannedError() from exc- except EmailDomainSuspendedRegistrationError as exc:- _log_console_login_failure(email=user_email, reason=LoginFailureReason.ACCOUNT_IN_FREEZE)- raise EmailDomainSuspendedError() from exc- except AccountRegisterError as exc:- _log_console_login_failure(email=user_email, reason=LoginFailureReason.ACCOUNT_IN_FREEZE)- raise AccountInFreezeError() from exc- if account:- tenants = TenantService.get_join_tenants(account, session=db.session())- if not tenants:- workspaces = SystemFeatureService.get_license().workspaces- if not workspaces.is_available():- raise WorkspacesLimitExceeded()- if not SystemFeatureService.is_workspace_creation_allowed():- raise NotAllowedCreateWorkspace()- else:- TenantService.create_owner_tenant(account, session=db.session())-- if account is None:- try:- account = AccountService.create_account_and_tenant(- email=user_email,- name=user_email,- interface_language=get_valid_language(language),+ token_pair = application_services().accounts.authentication.login_with_email_code(+ EmailCodeLoginCommand(+ email=req_data.email,+ code=req_data.code,+ token=str(req_data.token),+ turnstile_token=req_data.turnstile_token,+ language=req_data.language,timezone=req_data.timezone,- ip_address=ip_address,- check_normalized_email=True,- session=db.session(),+ ip_address=extract_remote_ip(request),)- except WorkSpaceNotAllowedCreateError:- raise NotAllowedCreateWorkspace()- except SeatsLimitExceededError:- raise SeatsLimitExceeded()- except EmailDomainSuspendedRegistrationError as exc:- _log_console_login_failure(email=user_email, reason=LoginFailureReason.ACCOUNT_IN_FREEZE)- raise EmailDomainSuspendedError() from exc- except AccountNormalizedEmailAlreadyInUseError as exc:- raise NormalizedEmailAlreadyInUseError() from exc- except AccountRegisterError as exc:- _log_console_login_failure(email=user_email, reason=LoginFailureReason.ACCOUNT_IN_FREEZE)- raise AccountInFreezeError() from exc- except WorkspacesLimitExceededError:- raise WorkspacesLimitExceeded()- token_pair = AccountService.login(account, session=db.session(), ip_address=ip_address)- AccountService.reset_login_error_rate_limit(user_email)-- # Create response with cookies instead of returning tokens in body- # response-contract:ignore cookie-bearing Flask response- response = make_response(SimpleResultResponse(result="success").model_dump(mode="json"))-- set_csrf_token_to_cookie(request, response, token_pair.csrf_token)- # Set HTTP-only secure cookies for tokens- set_access_token_to_cookie(request, response, token_pair.access_token)- set_refresh_token_to_cookie(request, response, token_pair.refresh_token)- return response+ )+ except account_errors.AccountApplicationError as error:+ _raise_request_error(error)+ return _token_response(token_pair, SimpleResultResponse, {"result": "success"})@console_ns.route("/refresh-token")class RefreshTokenApi(Resource):@console_ns.response(200, "Success", console_ns.models[SimpleResultResponse.__name__])@console_ns.response(401, "Unauthorized", console_ns.models[SimpleResultMessageResponse.__name__])- @with_session(write=False)- def post(self, session: Session):- # Get refresh token from cookie instead of request body+ def post(self):refresh_token = extract_refresh_token(request)-if not refresh_token:- return SimpleResultMessageResponse(result="fail", message="No refresh token provided").model_dump(- mode="json"- ), 401+ return dump_response(+ SimpleResultMessageResponse,+ {"result": "fail", "message": "No refresh token provided"},+ ), HTTPStatus.UNAUTHORIZEDtry:- new_token_pair = AccountService.refresh_token(refresh_token, session=session)- except Unauthorized as exc:- return SimpleResultMessageResponse(result="fail", message=exc.description or "Unauthorized.").model_dump(- mode="json"- ), 401- except (RefreshTokenNotFoundError, RefreshTokenAccountNotFoundError) as exc:- return SimpleResultMessageResponse(result="fail", message=str(exc)).model_dump(mode="json"), 401-- # Create response with new cookies- # response-contract:ignore cookie-bearing Flask response- response = make_response(SimpleResultResponse(result="success").model_dump(mode="json"))-- # Update cookies with new tokens- set_csrf_token_to_cookie(request, response, new_token_pair.csrf_token)- set_access_token_to_cookie(request, response, new_token_pair.access_token)- set_refresh_token_to_cookie(request, response, new_token_pair.refresh_token)- return response---def _get_account_with_case_fallback(email: str):- account = AccountService.get_user_through_email(email, session=db.session())- if account or email == email.lower():- return account-- return AccountService.get_user_through_email(email.lower(), session=db.session())---def _authenticate_account_with_case_fallback(- original_email: str, normalized_email: str, password: str, invite_token: str | None-):- try:- return AccountService.authenticate(original_email, password, invite_token, session=db.session())- except services.errors.account.AccountPasswordError:- if original_email == normalized_email:- raise- return AccountService.authenticate(normalized_email, password, invite_token, session=db.session())---def _log_console_login_failure(*, email: str, reason: LoginFailureReason) -> None:- logger.warning(- "Console login failed: email=%s reason=%s ip_address=%s",- email,- reason,- extract_remote_ip(request),- )+ token_pair = application_services().accounts.authentication.refresh(refresh_token)+ except account_errors.InvalidRefreshTokenError as error:+ return dump_response(+ SimpleResultMessageResponse,+ {"result": "fail", "message": str(error)},+ ), HTTPStatus.UNAUTHORIZED+ return _token_response(token_pair, SimpleResultResponse, {"result": "success"})+++def _token_response(token_pair: AuthTokenPair, response_model: type[BaseModel], data: object):+ # response-contract:ignore cookie-bearing Flask response+ response = make_response(dump_response(response_model, data))+ set_csrf_token_to_cookie(request, response, token_pair.csrf_token)+ set_access_token_to_cookie(request, response, token_pair.access_token)+ set_refresh_token_to_cookie(request, response, token_pair.refresh_token)+ return response+++def _raise_request_error(error: account_errors.AccountApplicationError) -> Never:+ if isinstance(error, account_errors.AccountEmailDomainSuspendedError):+ raise EmailDomainSuspendedError() from error+ if isinstance(error, account_errors.AccountEmailFrozenError):+ raise AccountInFreezeError() from error+ if isinstance(error, account_errors.LoginRateLimitError):+ raise EmailPasswordLoginLimitError() from error+ if isinstance(error, account_errors.InvalidLoginCredentialsError):+ raise AuthenticationFailedError() from error+ if isinstance(error, account_errors.InvalidAccountPasswordError):+ raise InvalidAccountPasswordRequestError(description=str(error)) from error+ if isinstance(error, account_errors.LoginAccountBannedError):+ raise AccountBannedError() from error+ if isinstance(error, account_errors.InvalidLoginInvitationEmailError):+ raise InvalidEmailError() from error+ if isinstance(error, account_errors.LoginWorkspaceLimitError):+ raise WorkspacesLimitExceeded() from error+ if isinstance(error, account_errors.LoginWorkspaceCreationNotAllowedError):+ raise NotAllowedCreateWorkspace() from error+ if isinstance(error, account_errors.LoginSeatLimitError):+ raise SeatsLimitExceeded() from error+ if isinstance(error, account_errors.AccountNormalizedEmailAlreadyInUseError):+ raise NormalizedEmailAlreadyInUseError() from error+ if isinstance(error, account_errors.EmailCodeSendIPLimitedError):+ raise EmailSendIpLimitError() from error+ if isinstance(error, account_errors.EmailCodeSendRateLimitError):+ raise EmailCodeLoginRateLimitExceededError(error.retry_after_minutes) from error+ if isinstance(error, account_errors.HumanVerificationRejectedError):+ raise TurnstileVerificationFailedError() from error+ if isinstance(error, account_errors.HumanVerificationUnavailableError):+ raise TurnstileServiceUnavailableError() from error+ if isinstance(error, account_errors.EmailCodeLoginUnavailableError):+ raise EmailCodeLoginServiceUnavailableError() from error+ if isinstance(error, account_errors.InvalidEmailCodeTokenError):+ raise InvalidTokenError() from error+ if isinstance(error, account_errors.EmailCodeEmailMismatchError):+ raise InvalidEmailError() from error+ if isinstance(error, account_errors.InvalidEmailCodeError):+ raise EmailCodeError() from error+ if isinstance(error, account_errors.AccountNotFoundError):+ raise AccountNotFound() from error+ if isinstance(error, account_errors.ResetPasswordEmailRateLimitError):+ raise PasswordResetRateLimitExceededError(error.retry_after_minutes) from error+ raise errordiff --git a/api/controllers/console/error.py b/api/controllers/console/error.pyindex 0de7c2df2f5..cc78268fe26 100644--- a/api/controllers/console/error.py+++ b/api/controllers/console/error.py@@ -76,6 +76,12 @@ class AccountNotFound(BaseHTTPException):code = 400+class InvalidAccountPasswordRequestError(BaseHTTPException):+ error_code = "invalid_account_password"+ description = "The password does not satisfy the account password policy."+ code = 400++class EmailSendIpLimitError(BaseHTTPException):error_code = "email_send_ip_limit"description = "Too many emails have been sent from this IP address recently. Please try again later."diff --git a/api/controllers/console/workspace/account.py b/api/controllers/console/workspace/account.pyindex ce3383ff13c..d2993fc209c 100644--- a/api/controllers/console/workspace/account.py+++ b/api/controllers/console/workspace/account.py@@ -35,13 +35,13 @@ from controllers.console.error import (EducationVerifyLimitError,EmailDomainSuspendedError,EmailSendIpLimitError,+ InvalidAccountPasswordRequestError,)from controllers.console.flask_admission import console_account_admissionfrom controllers.console.workspace.error import (AccountAlreadyInitedError,CurrentPasswordIncorrectError,InvalidAccountDeletionCodeError,- InvalidAccountPasswordRequestError,InvalidInvitationCodeError,MissingInvitationCodeRequestError,RepeatPasswordNotMatchError,diff --git a/api/controllers/console/workspace/error.py b/api/controllers/console/workspace/error.pyindex 09125486711..6f66c162fe3 100644--- a/api/controllers/console/workspace/error.py+++ b/api/controllers/console/workspace/error.py@@ -19,12 +19,6 @@ class CurrentPasswordIncorrectError(BaseHTTPException):code = 400-class InvalidAccountPasswordRequestError(BaseHTTPException):- error_code = "invalid_account_password"- description = "The password does not satisfy the account password policy."- code = 400--class InvalidInvitationCodeError(BaseHTTPException):error_code = "invalid_invitation_code"description = "Invalid invitation code."diff --git a/api/controllers/web/login.py b/api/controllers/web/login.pyindex 6d99d290b0b..b95178327de 100644--- a/api/controllers/web/login.py+++ b/api/controllers/web/login.py@@ -42,7 +42,8 @@ from libs.token import ()from services.account_service import AccountServicefrom services.app_service import AppService-from services.entities.auth_entities import LoginFailureReason, LoginPayloadBase+from services.entities.auth_audit_entities import LoginFailureReason+from services.entities.auth_entities import LoginPayloadBasefrom services.webapp_auth_service import WebAppAuthServicelogger = logging.getLogger(__name__)diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.pyindex 986fc5a79c4..65b948ccb9f 100644--- a/api/extensions/ext_application_services.py+++ b/api/extensions/ext_application_services.py@@ -43,35 +43,29 @@ from repositories.webapp_access_query_repository import WebAppAccessQueryRepositfrom repositories.workflow_run_archive_repository import WorkflowRunArchiveBundleQueryRepositoryfrom repositories.workspace_member_query_repository import WorkspaceMemberQueryRepositoryfrom repositories.workspace_query_repository import WorkspaceQueryRepository-from services.account_activation_adapters import (- BillingAccountActivationEligibility,- BillingWorkspaceMembershipCache,- DeploymentWorkspaceInvitePolicy,- RBACWorkspaceMemberAccessSync,- RegisterServiceInvitationTokenStore,-)from services.account_activation_service import AccountActivationService-from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGateway-from services.account_avatar_service import AccountAvatarService-from services.account_billing_adapters import (+from services.account_adapters import (+ BillingAccountActivationEligibility,BillingAccountDeletionFeedbackGateway,BillingAccountEducationGateway,-)-from services.account_change_email_adapters import (BillingAccountEmailPolicyGateway,+ BillingWorkspaceMembershipCache,+ CeleryAccountDeletionScheduler,+ CeleryAccountDeletionVerificationNotifier,CeleryChangeEmailNotificationGateway,+ DeploymentWorkspaceInvitePolicy,+ EnterpriseAccountDeletionSyncGateway,RateLimiterChangeEmailSendLimiter,+ RBACWorkspaceMemberAccessSync,RedisChangeEmailSecurityGateway,+ RedisInvitationTokenStore,SecureChangeEmailCodeGenerator,+ TokenManagerAccountDeletionVerificationGateway,TokenManagerChangeEmailTokenGateway,)+from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGateway+from services.account_avatar_service import AccountAvatarServicefrom services.account_change_email_service import AccountChangeEmailService-from services.account_deletion_adapters import (- CeleryAccountDeletionScheduler,- CeleryAccountDeletionVerificationNotifier,- EnterpriseAccountDeletionSyncGateway,- TokenManagerAccountDeletionVerificationGateway,-)from services.account_deletion_feedback_service import AccountDeletionFeedbackServicefrom services.account_deletion_service import AccountDeletionServicefrom services.account_education_service import AccountEducationService@@ -96,6 +90,19 @@ from services.account_forgot_password_adapters import (from services.account_forgot_password_service import AccountForgotPasswordServicefrom services.account_initialization_service import AccountInitializationServicefrom services.account_integration_service import AccountIntegrationService+from services.account_login_adapters import (+ AccountActivationConsoleAuthInvitationGateway,+ DeploymentConsoleAuthPolicyGateway,+ LoggingConsoleAuthAuditGateway,+ RedisAccountSessionGateway,+ RedisConsoleAuthSecurityGateway,+ RedisEmailCodeGateway,+ RedisResetPasswordEmailGateway,+ SQLAlchemyAccountRefreshPreparationGateway,+ SQLAlchemyConsoleAuthProvisioningGateway,+ TurnstileHumanVerificationGateway,+)+from services.account_login_service import ConsoleAuthenticationServicefrom services.account_password_hasher import DefaultAccountPasswordHasherfrom services.account_password_service import AccountPasswordServicefrom services.account_profile_service import AccountProfileService@@ -183,6 +190,7 @@ def _is_user_allowed_to_access_webapp(user_id: str, app_id: str) -> bool:@dataclass(frozen=True, slots=True)class AccountServices:+ authentication: ConsoleAuthenticationServiceavatar: AccountAvatarServicechange_email: AccountChangeEmailServiceemail_registration: AccountEmailRegistrationService@@ -295,8 +303,37 @@ def build_application_services(workspace_query_repository = WorkspaceQueryRepository(session_factory=database_client)file_service = FileService(session_factory=database_client)passwords = DefaultAccountPasswordHasher()+ invitation_tokens = RedisInvitationTokenStore(redis=redis)+ activation_accounts = SQLAlchemyAccountActivationRepository(session_factory=database_client)+ account_provisioning = SQLAlchemyConsoleAuthProvisioningGateway(session_factory=database_client)return ApplicationServices(accounts=AccountServices(+ authentication=ConsoleAuthenticationService(+ accounts=accounts,+ workspaces=workspace_query_repository,+ invitations=AccountActivationConsoleAuthInvitationGateway(+ tokens=invitation_tokens,+ accounts=activation_accounts,+ ),+ policies=DeploymentConsoleAuthPolicyGateway(+ billing_enabled=deployment_edition == DeploymentEdition.CLOUD,+ ),+ security=RedisConsoleAuthSecurityGateway(redis=redis),+ passwords=passwords,+ human_verification=TurnstileHumanVerificationGateway(),+ sessions=RedisAccountSessionGateway(redis=redis),+ refresh_preparation=SQLAlchemyAccountRefreshPreparationGateway(session_factory=database_client),+ account_provisioning=account_provisioning,+ workspace_provisioning=account_provisioning,+ email_codes=RedisEmailCodeGateway(redis=redis),+ reset_password_emails=RedisResetPasswordEmailGateway(redis=redis),+ audit=LoggingConsoleAuthAuditGateway(),+ now=naive_utc_now,+ turnstile_enabled=deployment_edition == DeploymentEdition.CLOUD,+ turnstile_verify_required=(+ deployment_edition == DeploymentEdition.CLOUD and dify_config.TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED+ ),+ ),avatar=AccountAvatarService(files=SQLAlchemyAccountAvatarFileGateway(session_factory=database_client),),@@ -305,14 +342,7 @@ def build_application_services(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,- )- ),+ send_limits=RateLimiterChangeEmailSendLimiter(redis=redis),security=RedisChangeEmailSecurityGateway(redis=redis,email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,@@ -350,14 +380,7 @@ def build_application_services(accounts=accounts,memberships=workspace_query_repository,verification=TokenManagerAccountDeletionVerificationGateway(),- notifications=CeleryAccountDeletionVerificationNotifier(- rate_limiter=RateLimiter(- prefix="email_code_account_deletion_rate_limit",- max_attempts=1,- time_window=60,- redis_client=redis,- )- ),+ notifications=CeleryAccountDeletionVerificationNotifier(redis=redis),synchronization=EnterpriseAccountDeletionSyncGateway(),scheduler=CeleryAccountDeletionScheduler(),),@@ -410,8 +433,8 @@ def build_application_services(profile=AccountProfileService(accounts=accounts),),account_activation=AccountActivationService(- tokens=RegisterServiceInvitationTokenStore(),- accounts=SQLAlchemyAccountActivationRepository(session_factory=database_client),+ tokens=invitation_tokens,+ accounts=activation_accounts,workspace_policy=DeploymentWorkspaceInvitePolicy(),eligibility=BillingAccountActivationEligibility(enabled=deployment_edition == DeploymentEdition.CLOUD,diff --git a/api/repositories/account_repository.py b/api/repositories/account_repository.pyindex b75a0eaefae..1f1c988fb83 100644--- a/api/repositories/account_repository.py+++ b/api/repositories/account_repository.py@@ -2,11 +2,12 @@from typing import override-from sqlalchemy import delete, select+from sqlalchemy import case, delete, selectfrom sqlalchemy.orm import Session, sessionmakerfrom models.account import Account, AccountIntegrate, AccountStatus, InvitationCode, InvitationCodeStatusfrom services.account_email import normalize_email+from services.account_login_service import ConsoleAuthAccountRepositoryfrom services.account_ports import AccountRepositoryfrom services.entities.account_entities import (AccountCredentials,@@ -19,9 +20,14 @@ from services.entities.account_entities import (AccountProfileChanges,AccountSnapshot,)+from services.entities.account_login_entities import (+ AccountSessionPreparation,+ LoginAccountSnapshot,+ PasswordLoginCompletion,+)-class SQLAlchemyAccountRepository(AccountRepository):+class SQLAlchemyAccountRepository(AccountRepository, ConsoleAuthAccountRepository):def __init__(self, session_factory: sessionmaker[Session]) -> None:self._session_factory = session_factory@@ -47,6 +53,47 @@ class SQLAlchemyAccountRepository(AccountRepository):return Nonereturn AccountCredentials(password_hash=account.password, password_salt=account.password_salt)+ @override+ def list_for_login(self, email: str) -> tuple[LoginAccountSnapshot, ...]:+ normalized_email = email.lower()+ candidate_emails = (email,) if email == normalized_email else (email, normalized_email)+ email_priority = case((Account.email == email, 0), else_=1)+ with self._session_factory() as session:+ accounts = session.scalars(+ select(Account)+ .where(Account.email.in_(candidate_emails))+ .order_by(email_priority.asc(), Account.id.asc())+ ).all()+ return tuple(self._to_login_snapshot(account) for account in accounts)++ @override+ def complete_password_login(self, completion: PasswordLoginCompletion) -> bool:+ with self._session_factory.begin() as session:+ account = session.get(Account, completion.account_id)+ if account is None:+ return False+ if completion.password is not None:+ account.password = completion.password.password_hash+ account.password_salt = completion.password.password_salt+ if completion.activate_pending_account and account.status == AccountStatus.PENDING:+ account.status = AccountStatus.ACTIVE+ account.initialized_at = completion.initialized_at+ session.flush()+ return True++ @override+ def prepare_session(self, account_id: str, preparation: AccountSessionPreparation) -> bool:+ with self._session_factory.begin() as session:+ account = session.get(Account, account_id)+ if account is None:+ return False+ account.last_login_at = preparation.logged_in_at+ account.last_login_ip = preparation.ip_address+ if preparation.activate_pending_account and account.status == AccountStatus.PENDING:+ account.status = AccountStatus.ACTIVE+ session.flush()+ return True+@overridedef update_profile(self, account_id: str, changes: AccountProfileChanges) -> AccountSnapshot | None:with self._session_factory.begin() as session:@@ -171,3 +218,13 @@ class SQLAlchemyAccountRepository(AccountRepository):initialized_at=account.initialized_at,created_at=account.created_at,)++ @staticmethod+ def _to_login_snapshot(account: Account) -> LoginAccountSnapshot:+ return LoginAccountSnapshot(+ id=account.id,+ email=account.email,+ status=account.status.value,+ password_hash=account.password,+ password_salt=account.password_salt,+ )diff --git a/api/repositories/workspace_query_repository.py b/api/repositories/workspace_query_repository.pyindex ed4b41293e5..9af32673fa5 100644--- a/api/repositories/workspace_query_repository.py+++ b/api/repositories/workspace_query_repository.py@@ -6,11 +6,12 @@ from sqlalchemy import selectfrom sqlalchemy.orm import Session, sessionmakerfrom models.account import Tenant, TenantAccountJoin, TenantStatus+from services.account_login_service import ConsoleAuthWorkspaceQueryfrom services.account_ports import AccountWorkspaceMembershipQueryfrom services.workspace_query_service import WorkspaceQuery, WorkspaceRecord-class WorkspaceQueryRepository(WorkspaceQuery, AccountWorkspaceMembershipQuery):+class WorkspaceQueryRepository(WorkspaceQuery, AccountWorkspaceMembershipQuery, ConsoleAuthWorkspaceQuery):def __init__(self, session_factory: sessionmaker[Session]) -> None:self._session_factory = session_factory@@ -50,3 +51,17 @@ class WorkspaceQueryRepository(WorkspaceQuery, AccountWorkspaceMembershipQuery):stmt = select(TenantAccountJoin.tenant_id).where(TenantAccountJoin.account_id == account_id)with self._session_factory() as session:return tuple(session.scalars(stmt).all())++ @override+ def has_active_for_account(self, account_id: str) -> bool:+ stmt = (+ select(Tenant.id)+ .join(TenantAccountJoin, TenantAccountJoin.tenant_id == Tenant.id)+ .where(+ TenantAccountJoin.account_id == account_id,+ Tenant.status == TenantStatus.NORMAL,+ )+ .limit(1)+ )+ with self._session_factory() as session:+ return session.scalar(stmt) is not Nonediff --git a/api/services/account_activation_adapters.py b/api/services/account_activation_adapters.pydeleted file mode 100644index 708ff620966..00000000000--- a/api/services/account_activation_adapters.py+++ /dev/null@@ -1,89 +0,0 @@-"""Infrastructure gateways for account invitation activation."""--from typing import override--from libs.workspace_permission import check_workspace_member_invite_permission-from services.account_activation_service import (- AccountActivationEligibility,- InvitationTokenStore,- WorkspaceInvitePolicy,- WorkspaceMemberAccessSync,- WorkspaceMembershipCache,-)-from services.account_service import RegisterService-from services.billing_service import BillingService-from services.entities.account_activation_entities import InvitationLookup, InvitationToken---class RegisterServiceInvitationTokenStore(InvitationTokenStore):- """Compatibility adapter around the existing Redis invitation token owner."""-- @override- def find(self, invitation: InvitationLookup) -> InvitationToken | None:- data = RegisterService.get_invitation_by_token(- invitation.token,- invitation.workspace_id,- invitation.email,- )- if data is None:- return None- return InvitationToken(- account_id=data["account_id"],- email=data["email"],- workspace_id=data["workspace_id"],- role=data.get("role"),- requires_setup=data.get("requires_setup"),- )-- @override- def revoke(self, invitation: InvitationLookup) -> None:- RegisterService.revoke_token(- invitation.workspace_id,- invitation.email,- invitation.token,- )---class DeploymentWorkspaceInvitePolicy(WorkspaceInvitePolicy):- @override- def ensure_allowed(self, workspace_id: str) -> None:- check_workspace_member_invite_permission(workspace_id)---class BillingAccountActivationEligibility(AccountActivationEligibility):- 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 BillingWorkspaceMembershipCache(WorkspaceMembershipCache):- def __init__(self, *, enabled: bool) -> None:- self._enabled = enabled-- @override- def invalidate(self, workspace_id: str) -> None:- if self._enabled:- BillingService.clean_billing_info_cache(workspace_id)---class RBACWorkspaceMemberAccessSync(WorkspaceMemberAccessSync):- def __init__(self, *, enabled: bool) -> None:- self._enabled = enabled-- @override- def sync(self, workspace_id: str, account_id: str) -> None:- if not self._enabled:- return-- from tasks.initialize_created_app_rbac_access_task import sync_joined_workspace_member_rbac_access_task-- sync_joined_workspace_member_rbac_access_task.delay(- str(workspace_id),- str(account_id),- operator_account_id=None,- )diff --git a/api/services/account_adapters.py b/api/services/account_adapters.pynew file mode 100644index 00000000000..36bbff56052--- /dev/null+++ b/api/services/account_adapters.py@@ -0,0 +1,393 @@+"""Infrastructure adapters shared by account application services."""++import secrets+from collections.abc import Sequence+from datetime import UTC, datetime+from hashlib import sha256+from typing import override++from pydantic import TypeAdapter, ValidationError++from extensions.ext_redis import RedisClientWrapper+from libs.helper import RateLimiter, TokenManager+from libs.workspace_permission import check_workspace_member_invite_permission+from services.account_activation_service import (+ AccountActivationEligibility,+ InvitationTokenStore,+ WorkspaceInvitePolicy,+ WorkspaceMemberAccessSync,+ WorkspaceMembershipCache,+)+from services.account_change_email_ports import (+ AccountEmailPolicyGateway,+ ChangeEmailCodeGenerator,+ ChangeEmailNotificationGateway,+ ChangeEmailSecurityGateway,+ ChangeEmailSendLimiter,+ ChangeEmailTokenGateway,+)+from services.account_deletion_feedback_service import AccountDeletionFeedbackGateway+from services.account_education_service import AccountEducationGateway+from services.account_errors import AccountDeletionRateLimitError+from services.account_ports import (+ AccountDeletionScheduler,+ AccountDeletionSyncGateway,+ AccountDeletionVerificationGateway,+ AccountDeletionVerificationNotifier,+)+from services.account_security_gateway import RedisAccountEmailSecurityGateway+from services.billing_service import BillingService+from services.enterprise.account_deletion_sync import sync_account_deletion_memberships+from services.entities.account_activation_entities import InvitationLookup, InvitationToken+from services.entities.account_entities import (+ AccountChangeEmailNewEmailToken,+ AccountChangeEmailNewEmailVerifiedToken,+ AccountChangeEmailOldEmailToken,+ AccountChangeEmailOldEmailVerifiedToken,+ AccountChangeEmailPhase,+ AccountChangeEmailTokenData,+ AccountDeletionChallenge,+ AccountEducationActivation,+ AccountEducationAutocomplete,+ AccountEducationStatus,+ AccountEducationVerification,+)+from services.entities.auth_entities import (+ ChangeEmailNewEmailToken,+ ChangeEmailNewEmailVerifiedToken,+ ChangeEmailOldEmailToken,+ ChangeEmailOldEmailVerifiedToken,+ ChangeEmailTokenData,+)+from tasks.delete_account_task import delete_account_task+from tasks.mail_account_deletion_task import send_account_deletion_verification_code+from tasks.mail_change_mail_task import send_change_mail_completed_notification_task, send_change_mail_task++_invitation_token_adapter = TypeAdapter(InvitationToken)+_change_email_token_adapter: TypeAdapter[ChangeEmailTokenData] = TypeAdapter(ChangeEmailTokenData)++_CHANGE_EMAIL_RATE_LIMIT_ATTEMPTS = 1+_CHANGE_EMAIL_RATE_LIMIT_SECONDS = 60+_ACCOUNT_DELETION_RATE_LIMIT_ATTEMPTS = 1+_ACCOUNT_DELETION_RATE_LIMIT_SECONDS = 60+++class RedisInvitationTokenStore(InvitationTokenStore):+ def __init__(self, *, redis: RedisClientWrapper) -> None:+ self._redis = redis++ @override+ def find(self, invitation: InvitationLookup) -> InvitationToken | None:+ if invitation.workspace_id is not None and invitation.email is not None:+ account_id = self._redis.get(self._workspace_invitation_key(invitation))+ if account_id is None:+ return None+ return InvitationToken(+ account_id=account_id.decode("utf-8"),+ email=invitation.email,+ workspace_id=invitation.workspace_id,+ )++ data = self._redis.get(self._invitation_token_key(invitation.token))+ if data is None:+ return None+ return _invitation_token_adapter.validate_json(data)++ @override+ def revoke(self, invitation: InvitationLookup) -> None:+ if invitation.workspace_id is not None and invitation.email is not None:+ self._redis.delete(self._workspace_invitation_key(invitation))+ else:+ self._redis.delete(self._invitation_token_key(invitation.token))++ @staticmethod+ def _invitation_token_key(token: str) -> str:+ return f"member_invite:token:{token}"++ @staticmethod+ def _workspace_invitation_key(invitation: InvitationLookup) -> str:+ assert invitation.workspace_id is not None+ assert invitation.email is not None+ email_hash = sha256(invitation.email.encode()).hexdigest()+ return f"member_invite_token:{invitation.workspace_id}, {email_hash}:{invitation.token}"+++class DeploymentWorkspaceInvitePolicy(WorkspaceInvitePolicy):+ @override+ def ensure_allowed(self, workspace_id: str) -> None:+ check_workspace_member_invite_permission(workspace_id)+++class BillingAccountActivationEligibility(AccountActivationEligibility):+ 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 BillingWorkspaceMembershipCache(WorkspaceMembershipCache):+ def __init__(self, *, enabled: bool) -> None:+ self._enabled = enabled++ @override+ def invalidate(self, workspace_id: str) -> None:+ if self._enabled:+ BillingService.clean_billing_info_cache(workspace_id)+++class RBACWorkspaceMemberAccessSync(WorkspaceMemberAccessSync):+ def __init__(self, *, enabled: bool) -> None:+ self._enabled = enabled++ @override+ def sync(self, workspace_id: str, account_id: str) -> None:+ if not self._enabled:+ return++ from tasks.initialize_created_app_rbac_access_task import sync_joined_workspace_member_rbac_access_task++ sync_joined_workspace_member_rbac_access_task.delay(+ str(workspace_id),+ str(account_id),+ operator_account_id=None,+ )+++class BillingAccountEducationGateway(AccountEducationGateway):+ @override+ def verify(self, *, account_id: str) -> AccountEducationVerification:+ result = BillingService.EducationIdentity.verify(account_id=account_id) or {}+ return AccountEducationVerification(token=result.get("token"))++ @override+ def activate(+ self,+ *,+ account_id: str,+ tenant_id: str,+ token: str,+ institution: str,+ role: str,+ ) -> AccountEducationActivation:+ result = BillingService.EducationIdentity.activate(+ account_id=account_id,+ tenant_id=tenant_id,+ token=token,+ institution=institution,+ role=role,+ )+ return AccountEducationActivation(message=result["message"])++ @override+ def status(self, account_id: str) -> AccountEducationStatus:+ result = BillingService.EducationIdentity.status(account_id) or {}+ expire_at = result.get("expire_at")+ return AccountEducationStatus(+ result=result.get("result"),+ is_student=result.get("is_student"),+ expire_at=datetime.fromisoformat(expire_at).astimezone(UTC) if isinstance(expire_at, str) else expire_at,+ allow_refresh=result.get("allow_refresh"),+ )++ @override+ def autocomplete(self, *, keywords: str, page: int, limit: int) -> AccountEducationAutocomplete:+ result = BillingService.EducationIdentity.autocomplete(keywords, page, limit) or {}+ return AccountEducationAutocomplete(+ data=tuple(result.get("data") or ()),+ curr_page=result.get("curr_page"),+ has_next=result.get("has_next"),+ )+++class BillingAccountDeletionFeedbackGateway(AccountDeletionFeedbackGateway):+ @override+ def submit(self, *, email: str, feedback: str) -> None:+ BillingService.update_account_deletion_feedback(email, feedback)+++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 = _change_email_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,+ *,+ redis: RedisClientWrapper | None = None,+ rate_limiter: RateLimiter | None = None,+ ) -> None:+ if rate_limiter is None:+ if redis is None:+ raise ValueError("redis is required when rate_limiter is not provided")+ rate_limiter = RateLimiter(+ prefix="change_email_rate_limit",+ max_attempts=_CHANGE_EMAIL_RATE_LIMIT_ATTEMPTS,+ time_window=_CHANGE_EMAIL_RATE_LIMIT_SECONDS,+ redis_client=redis,+ )+ 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(RedisAccountEmailSecurityGateway, ChangeEmailSecurityGateway):+ def __init__(+ self,+ *,+ redis: RedisClientWrapper,+ email_send_ip_limit_per_minute: int,+ verification_failure_limit: int,+ verification_lockout_duration: int,+ ) -> None:+ super().__init__(+ redis=redis,+ email_send_ip_limit_per_minute=email_send_ip_limit_per_minute,+ verification_failure_limit=verification_failure_limit,+ verification_lockout_duration=verification_lockout_duration,+ verification_key_prefix="change_email_error_rate_limit",+ )+++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"+++class TokenManagerAccountDeletionVerificationGateway(AccountDeletionVerificationGateway):+ @override+ def 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_id=account_id,+ email=email,+ token_type="account_deletion",+ additional_data={"code": code},+ )+ return AccountDeletionChallenge(token=token, code=code)++ @override+ def verify(self, *, account_id: str, token: str, code: str) -> bool:+ token_data = TokenManager.get_token_data(token, "account_deletion")+ if token_data is None:+ return False+ return token_data.get("account_id") == account_id and token_data.get("code") == code+++class CeleryAccountDeletionVerificationNotifier(AccountDeletionVerificationNotifier):+ def __init__(+ self,+ *,+ redis: RedisClientWrapper | None = None,+ rate_limiter: RateLimiter | None = None,+ ) -> None:+ if rate_limiter is None:+ if redis is None:+ raise ValueError("redis is required when rate_limiter is not provided")+ rate_limiter = RateLimiter(+ prefix="email_code_account_deletion_rate_limit",+ max_attempts=_ACCOUNT_DELETION_RATE_LIMIT_ATTEMPTS,+ time_window=_ACCOUNT_DELETION_RATE_LIMIT_SECONDS,+ redis_client=redis,+ )+ self._rate_limiter = rate_limiter++ @override+ def send(self, *, email: str, code: str) -> None:+ if self._rate_limiter.is_rate_limited(email):+ raise AccountDeletionRateLimitError(int(self._rate_limiter.time_window / 60))++ send_account_deletion_verification_code.delay(to=email, code=code)+ self._rate_limiter.increment_rate_limit(email)+++class EnterpriseAccountDeletionSyncGateway(AccountDeletionSyncGateway):+ @override+ def sync(self, *, account_id: str, workspace_ids: Sequence[str]) -> bool:+ return sync_account_deletion_memberships(+ account_id=account_id,+ workspace_ids=workspace_ids,+ source="account_deleted",+ )+++class CeleryAccountDeletionScheduler(AccountDeletionScheduler):+ @override+ def schedule(self, account_id: str) -> None:+ delete_account_task.delay(account_id)diff --git a/api/services/account_billing_adapters.py b/api/services/account_billing_adapters.pydeleted file mode 100644index c8f22b09be6..00000000000--- a/api/services/account_billing_adapters.py+++ /dev/null@@ -1,66 +0,0 @@-"""Billing adapters for account education and deletion-feedback use cases."""--from datetime import UTC, datetime-from typing import override--from services.account_deletion_feedback_service import AccountDeletionFeedbackGateway-from services.account_education_service import AccountEducationGateway-from services.billing_service import BillingService-from services.entities.account_entities import (- AccountEducationActivation,- AccountEducationAutocomplete,- AccountEducationStatus,- AccountEducationVerification,-)---class BillingAccountEducationGateway(AccountEducationGateway):- @override- def verify(self, *, account_id: str) -> AccountEducationVerification:- result = BillingService.EducationIdentity.verify(account_id=account_id) or {}- return AccountEducationVerification(token=result.get("token"))-- @override- def activate(- self,- *,- account_id: str,- tenant_id: str,- token: str,- institution: str,- role: str,- ) -> AccountEducationActivation:- result = BillingService.EducationIdentity.activate(- account_id=account_id,- tenant_id=tenant_id,- token=token,- institution=institution,- role=role,- )- return AccountEducationActivation(message=result["message"])-- @override- def status(self, account_id: str) -> AccountEducationStatus:- result = BillingService.EducationIdentity.status(account_id) or {}- expire_at = result.get("expire_at")- return AccountEducationStatus(- result=result.get("result"),- is_student=result.get("is_student"),- expire_at=datetime.fromisoformat(expire_at).astimezone(UTC) if isinstance(expire_at, str) else expire_at,- allow_refresh=result.get("allow_refresh"),- )-- @override- def autocomplete(self, *, keywords: str, page: int, limit: int) -> AccountEducationAutocomplete:- result = BillingService.EducationIdentity.autocomplete(keywords, page, limit) or {}- return AccountEducationAutocomplete(- data=tuple(result.get("data") or ()),- curr_page=result.get("curr_page"),- has_next=result.get("has_next"),- )---class BillingAccountDeletionFeedbackGateway(AccountDeletionFeedbackGateway):- @override- def submit(self, *, email: str, feedback: str) -> None:- BillingService.update_account_deletion_feedback(email, feedback)diff --git a/api/services/account_change_email_adapters.py b/api/services/account_change_email_adapters.pydeleted file mode 100644index dacdbf757b0..00000000000--- a/api/services/account_change_email_adapters.py+++ /dev/null@@ -1,144 +0,0 @@-"""Infrastructure adapters for the account change-email application service."""--import secrets-from typing import override--from pydantic import TypeAdapter, ValidationError--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.account_security_gateway import RedisAccountEmailSecurityGateway-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(RedisAccountEmailSecurityGateway, ChangeEmailSecurityGateway):- def __init__(- self,- *,- redis: RedisClientWrapper,- email_send_ip_limit_per_minute: int,- verification_failure_limit: int,- verification_lockout_duration: int,- ) -> None:- super().__init__(- redis=redis,- email_send_ip_limit_per_minute=email_send_ip_limit_per_minute,- verification_failure_limit=verification_failure_limit,- verification_lockout_duration=verification_lockout_duration,- verification_key_prefix="change_email_error_rate_limit",- )---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_deletion_adapters.py b/api/services/account_deletion_adapters.pydeleted file mode 100644index bcf705c5924..00000000000--- a/api/services/account_deletion_adapters.py+++ /dev/null@@ -1,67 +0,0 @@-"""Infrastructure adapters for the account deletion application service."""--import secrets-from collections.abc import Sequence-from typing import override--from libs.helper import RateLimiter, TokenManager-from services.account_errors import AccountDeletionRateLimitError-from services.account_ports import (- AccountDeletionScheduler,- AccountDeletionSyncGateway,- AccountDeletionVerificationGateway,- AccountDeletionVerificationNotifier,-)-from services.enterprise.account_deletion_sync import sync_account_deletion_memberships-from services.entities.account_entities import AccountDeletionChallenge-from tasks.delete_account_task import delete_account_task-from tasks.mail_account_deletion_task import send_account_deletion_verification_code---class TokenManagerAccountDeletionVerificationGateway(AccountDeletionVerificationGateway):- @override- def 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_id=account_id,- email=email,- token_type="account_deletion",- additional_data={"code": code},- )- return AccountDeletionChallenge(token=token, code=code)-- @override- def verify(self, *, account_id: str, token: str, code: str) -> bool:- token_data = TokenManager.get_token_data(token, "account_deletion")- if token_data is None:- return False- return token_data.get("account_id") == account_id and token_data.get("code") == code---class CeleryAccountDeletionVerificationNotifier(AccountDeletionVerificationNotifier):- def __init__(self, *, rate_limiter: RateLimiter) -> None:- self._rate_limiter = rate_limiter-- @override- def send(self, *, email: str, code: str) -> None:- if self._rate_limiter.is_rate_limited(email):- raise AccountDeletionRateLimitError(int(self._rate_limiter.time_window / 60))-- send_account_deletion_verification_code.delay(to=email, code=code)- self._rate_limiter.increment_rate_limit(email)---class EnterpriseAccountDeletionSyncGateway(AccountDeletionSyncGateway):- @override- def sync(self, *, account_id: str, workspace_ids: Sequence[str]) -> bool:- return sync_account_deletion_memberships(- account_id=account_id,- workspace_ids=workspace_ids,- source="account_deleted",- )---class CeleryAccountDeletionScheduler(AccountDeletionScheduler):- @override- def schedule(self, account_id: str) -> None:- delete_account_task.delay(account_id)diff --git a/api/services/account_errors.py b/api/services/account_errors.pyindex e0db485c9a4..b64b245ddac 100644--- a/api/services/account_errors.py+++ b/api/services/account_errors.py@@ -163,3 +163,79 @@ class EducationDiscountPausedError(AccountApplicationError):class EducationRateLimitExceededError(AccountApplicationError):"""Too many education verification or activation requests were made."""+++class LoginRateLimitError(AccountApplicationError):+ """Too many failed password-login attempts were made for the address."""+++class InvalidLoginCredentialsError(AccountApplicationError):+ """The supplied login credentials are invalid."""+++class LoginAccountBannedError(AccountApplicationError):+ """The account is banned from signing in."""+++class InvalidLoginInvitationEmailError(AccountApplicationError):+ """The invitation belongs to a different email address."""+++class LoginWorkspaceLimitError(AccountApplicationError):+ """A required workspace cannot be created because the limit was reached."""+++class LoginWorkspaceCreationNotAllowedError(AccountApplicationError):+ """Workspace creation is disabled for this deployment."""+++class LoginSeatLimitError(AccountApplicationError):+ """A new account cannot be created because the seat limit was reached."""+++class EmailCodeSendIPLimitedError(AccountApplicationError):+ """The caller IP exceeded the email-code send policy."""+++class EmailCodeSendRateLimitError(AccountApplicationError):+ """Too many email-code 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 HumanVerificationRejectedError(AccountApplicationError):+ """The anti-bot challenge was rejected."""+++class HumanVerificationUnavailableError(AccountApplicationError):+ """The anti-bot verification provider is unavailable."""+++class EmailCodeLoginUnavailableError(AccountApplicationError):+ """The email-code challenge store is unavailable."""+++class InvalidEmailCodeTokenError(AccountApplicationError):+ """The email-code token is invalid or no longer usable."""+++class EmailCodeEmailMismatchError(AccountApplicationError):+ """The email-code token belongs to a different address."""+++class InvalidEmailCodeError(AccountApplicationError):+ """The supplied email verification code is invalid."""+++class InvalidRefreshTokenError(AccountApplicationError):+ """The refresh token cannot be exchanged for a new session."""+++class ResetPasswordEmailRateLimitError(AccountApplicationError):+ """Too many reset-password 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_minutesdiff --git a/api/services/account_login_adapters.py b/api/services/account_login_adapters.pynew file mode 100644index 00000000000..65c8fac4513--- /dev/null+++ b/api/services/account_login_adapters.py@@ -0,0 +1,569 @@+"""Infrastructure adapters for the Console authentication application service."""++import logging+import secrets+from datetime import UTC, datetime, timedelta+from typing import override++from redis import RedisError+from sqlalchemy import select, update+from sqlalchemy.orm import Session, sessionmaker++from configs import dify_config+from enums import DeploymentEdition+from events.tenant_event import tenant_was_created+from extensions.ext_redis import RedisClientWrapper+from libs.datetime_utils import naive_utc_now+from libs.helper import RateLimiter, TokenManager+from libs.key_providers import generate_key_pair+from libs.passport import PassportService+from libs.token import generate_csrf_token+from models import TenantCreditPool+from models.account import (+ Account,+ AccountStatus,+ Tenant,+ TenantAccountJoin,+ TenantAccountRole,+ TenantPluginAutoUpgradeCategory,+ TenantPluginAutoUpgradeMode,+ TenantPluginAutoUpgradeStrategy,+ TenantStatus,+)+from models.enums import ProviderQuotaType+from services import account_errors+from services.account_activation_service import AccountActivationRepository, InvitationTokenStore+from services.account_email import normalize_email+from services.account_login_service import (+ AccountProvisioningGateway,+ AccountRefreshPreparationGateway,+ AccountSessionGateway,+ ConsoleAuthAuditGateway,+ ConsoleAuthInvitationGateway,+ ConsoleAuthPolicyGateway,+ ConsoleAuthSecurityGateway,+ EmailCodeGateway,+ HumanVerificationGateway,+ ResetPasswordEmailGateway,+ WorkspaceProvisioningGateway,+)+from services.billing_service import BillingService+from services.email_code_login_challenge import EmailCodeLoginChallengeStore, EmailCodeLoginChallengeUnavailableError+from services.enterprise.rbac_service import ListOption, RBACService+from services.entities.account_activation_entities import InvitationLookup+from services.entities.account_login_entities import (+ AuthTokenPair,+ EmailCodeChallengeStatus,+ LoginInvitation,+ RefreshAccountStatus,+)+from services.entities.auth_audit_entities import LoginFailureReason+from services.plugin.plugin_auto_upgrade_service import PluginAutoUpgradeService+from services.system_feature_service import SystemFeatureService+from services.turnstile_service import (+ EMAIL_CODE_SEND_ACTION,+ EMAIL_CODE_VERIFY_ACTION,+ TurnstileChallengeRejectedError,+ TurnstileService,+ TurnstileUpstreamError,+)+from tasks.mail_email_code_login import send_email_code_login_mail_task+from tasks.mail_reset_password_task import (+ send_reset_password_mail_task,+ send_reset_password_mail_task_when_account_not_exist,+)++logger = logging.getLogger(__name__)++_ACCOUNT_LAST_ACTIVE_REFRESH_INTERVAL = timedelta(minutes=10)+_ACCOUNT_REFRESH_TOKEN_PREFIX = "account_refresh_token:"+_EMAIL_CODE_LOGIN_RATE_LIMIT_ATTEMPTS = 3+_EMAIL_CODE_LOGIN_RATE_LIMIT_SECONDS = 5 * 60+_LOGIN_FAILURE_LIMIT = 5+_LOGIN_FAILURE_PREFIX = "login_error_rate_limit:"+_REFRESH_TOKEN_PREFIX = "refresh_token:"+_RESET_PASSWORD_RATE_LIMIT_ATTEMPTS = 1+_RESET_PASSWORD_RATE_LIMIT_SECONDS = 60+++class AccountActivationConsoleAuthInvitationGateway(ConsoleAuthInvitationGateway):+ """Resolve login invitations through the shared activation contracts."""++ def __init__(self, *, tokens: InvitationTokenStore, accounts: AccountActivationRepository) -> None:+ self._tokens = tokens+ self._accounts = accounts++ @override+ def resolve(self, *, email: str, token: str) -> LoginInvitation | None:+ candidate_emails = (email,) if email == email.lower() else (email, email.lower())+ for candidate_email in candidate_emails:+ invitation_token = self._tokens.find(+ InvitationLookup(workspace_id=None, email=candidate_email, token=token)+ )+ if invitation_token is None:+ continue+ invitation = self._accounts.resolve(invitation_token)+ if invitation is not None:+ return LoginInvitation(email=invitation.account_email)+ return None+++class DeploymentConsoleAuthPolicyGateway(ConsoleAuthPolicyGateway):+ def __init__(self, *, billing_enabled: bool) -> None:+ self._billing_enabled = billing_enabled++ @override+ def get_email_freeze_type(self, email: str) -> str | None:+ if not self._billing_enabled:+ return None+ return BillingService.get_email_freeze_type(email)++ @override+ def is_registration_allowed(self) -> bool:+ return SystemFeatureService.is_registration_allowed()++ @override+ def is_workspace_creation_allowed(self) -> bool:+ return SystemFeatureService.is_workspace_creation_allowed()++ @override+ def has_workspace_capacity(self) -> bool:+ return SystemFeatureService.get_license().workspaces.is_available()++ @override+ def has_account_capacity(self) -> bool:+ return SystemFeatureService.get_license().seats.is_available()+++class RedisConsoleAuthSecurityGateway(ConsoleAuthSecurityGateway):+ def __init__(self, *, redis: RedisClientWrapper) -> None:+ self._redis = redis++ @override+ def is_login_limited(self, email: str) -> bool:+ try:+ count = self._redis.get(f"{_LOGIN_FAILURE_PREFIX}{email}")+ return count is not None and int(count) > _LOGIN_FAILURE_LIMIT+ except RedisError:+ return False++ @override+ def record_login_failure(self, email: str) -> None:+ try:+ key = f"{_LOGIN_FAILURE_PREFIX}{email}"+ count = int(self._redis.get(key) or 0) + 1+ self._redis.setex(key, dify_config.LOGIN_LOCKOUT_DURATION, count)+ except RedisError:+ return None++ @override+ def reset_login_failures(self, email: str) -> None:+ try:+ self._redis.delete(f"{_LOGIN_FAILURE_PREFIX}{email}")+ except RedisError:+ return None++ @override+ def is_email_send_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 > dify_config.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+++class TurnstileHumanVerificationGateway(HumanVerificationGateway):+ @override+ def verify(self, *, token: str | None, remote_ip: str, action: str) -> None:+ is_email_code_verification = action == "signin_code_verify"+ expected_action = EMAIL_CODE_VERIFY_ACTION if is_email_code_verification else EMAIL_CODE_SEND_ACTION+ try:+ TurnstileService.verify(token=token, remote_ip=remote_ip, expected_action=expected_action)+ except TurnstileChallengeRejectedError as error:+ if is_email_code_verification:+ logger.info("Turnstile rejected an email-code verification challenge")+ else:+ logger.info("Turnstile rejected an email-code login challenge")+ raise account_errors.HumanVerificationRejectedError from error+ except TurnstileUpstreamError as error:+ logger.warning("Turnstile verification is unavailable", exc_info=True)+ raise account_errors.HumanVerificationUnavailableError from error+++class RedisAccountSessionGateway(AccountSessionGateway):+ def __init__(self, *, redis: RedisClientWrapper) -> None:+ self._redis = redis++ @override+ def issue(self, account_id: str) -> AuthTokenPair:+ return self._issue(account_id)++ @override+ def revoke(self, account_id: str) -> None:+ refresh_token = self._redis.get(self._account_refresh_token_key(account_id))+ if refresh_token:+ self._delete_refresh_token(refresh_token.decode("utf-8"), account_id)++ @override+ def resolve_refresh_token(self, refresh_token: str) -> str | None:+ account_id = self._redis.get(self._refresh_token_key(refresh_token))+ return account_id.decode("utf-8") if account_id else None++ @override+ def rotate(self, *, refresh_token: str, account_id: str) -> AuthTokenPair:+ self._delete_refresh_token(refresh_token, account_id)+ return self._issue(account_id)++ def _issue(self, account_id: str) -> AuthTokenPair:+ expires_at = datetime.now(UTC) + timedelta(minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES)+ access_token = PassportService().issue(+ {+ "user_id": account_id,+ "exp": int(expires_at.timestamp()),+ "iss": dify_config.DEPLOYMENT_EDITION.value,+ "sub": "Console API Passport",+ }+ )+ refresh_token = secrets.token_hex(64)+ self._store_refresh_token(refresh_token, account_id)+ return AuthTokenPair(+ access_token=access_token,+ refresh_token=refresh_token,+ csrf_token=generate_csrf_token(account_id),+ )++ def _store_refresh_token(self, refresh_token: str, account_id: str) -> None:+ expires_in = timedelta(days=dify_config.REFRESH_TOKEN_EXPIRE_DAYS)+ self._redis.setex(self._refresh_token_key(refresh_token), expires_in, account_id)+ self._redis.setex(self._account_refresh_token_key(account_id), expires_in, refresh_token)++ def _delete_refresh_token(self, refresh_token: str, account_id: str) -> None:+ self._redis.delete(self._refresh_token_key(refresh_token))+ self._redis.delete(self._account_refresh_token_key(account_id))++ @staticmethod+ def _refresh_token_key(refresh_token: str) -> str:+ return f"{_REFRESH_TOKEN_PREFIX}{refresh_token}"++ @staticmethod+ def _account_refresh_token_key(account_id: str) -> str:+ return f"{_ACCOUNT_REFRESH_TOKEN_PREFIX}{account_id}"+++class SQLAlchemyAccountRefreshPreparationGateway(AccountRefreshPreparationGateway):+ def __init__(self, *, session_factory: sessionmaker[Session]) -> None:+ self._session_factory = session_factory++ @override+ def prepare(self, account_id: str) -> RefreshAccountStatus:+ now = naive_utc_now()+ with self._session_factory.begin() as session:+ account = session.get(Account, account_id)+ if account is None:+ return RefreshAccountStatus.NOT_FOUND+ if account.status == AccountStatus.BANNED:+ return RefreshAccountStatus.BANNED++ current_membership = session.scalar(+ select(TenantAccountJoin)+ .join(Tenant, Tenant.id == TenantAccountJoin.tenant_id)+ .where(+ TenantAccountJoin.account_id == account_id,+ TenantAccountJoin.current.is_(True),+ Tenant.status == TenantStatus.NORMAL,+ )+ .limit(1)+ )+ if current_membership is None:+ session.execute(+ update(TenantAccountJoin)+ .where(TenantAccountJoin.account_id == account_id, TenantAccountJoin.current.is_(True))+ .values(current=False)+ )+ current_membership = session.scalar(+ select(TenantAccountJoin)+ .join(Tenant, Tenant.id == TenantAccountJoin.tenant_id)+ .where(+ TenantAccountJoin.account_id == account_id,+ Tenant.status == TenantStatus.NORMAL,+ )+ .order_by(TenantAccountJoin.id.asc())+ .limit(1)+ )+ if current_membership is None:+ return RefreshAccountStatus.NOT_FOUND+ current_membership.current = True+ current_membership.last_opened_at = now++ session.execute(+ update(Account)+ .where(+ Account.id == account_id,+ Account.last_active_at < now - _ACCOUNT_LAST_ACTIVE_REFRESH_INTERVAL,+ )+ .values(last_active_at=now)+ )+ return RefreshAccountStatus.READY+++class SQLAlchemyConsoleAuthProvisioningGateway(AccountProvisioningGateway, WorkspaceProvisioningGateway):+ """Persist the account/workspace aggregate and own its transaction boundary."""++ def __init__(self, *, session_factory: sessionmaker[Session]) -> None:+ self._session_factory = session_factory++ @override+ def create_with_owner_workspace(+ self,+ *,+ email: str,+ name: str,+ interface_language: str,+ timezone: str,+ ip_address: str,+ ) -> str:+ normalized_email = normalize_email(email)+ account = Account(+ name=name,+ email=email,+ normalized_email=normalized_email,+ interface_language=interface_language,+ interface_theme="light",+ timezone=timezone,+ last_login_ip=ip_address,+ )+ with self._session_factory.begin() as session:+ normalized_email_in_use = session.scalar(+ select(Account.id).where(Account.normalized_email == normalized_email).limit(1)+ )+ if normalized_email_in_use is not None:+ raise account_errors.AccountNormalizedEmailAlreadyInUseError+ session.add(account)+ tenant = self._add_owner_workspace(session, account)+ self._bind_owner_rbac_role(tenant, account.id, session)++ self._after_workspace_created(tenant, account.id)+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE:+ from services.enterprise.enterprise_service import try_join_default_workspace++ try_join_default_workspace(account.id)+ return account.id++ @override+ def create_owner_workspace(self, account_id: str) -> None:+ with self._session_factory.begin() as session:+ account = session.scalar(select(Account).where(Account.id == account_id).with_for_update())+ if account is None:+ raise account_errors.AccountNotFoundError+ existing_workspace_id = session.scalar(+ select(Tenant.id)+ .join(TenantAccountJoin, TenantAccountJoin.tenant_id == Tenant.id)+ .where(+ TenantAccountJoin.account_id == account_id,+ Tenant.status == TenantStatus.NORMAL,+ )+ .limit(1)+ )+ if existing_workspace_id is not None:+ return+ tenant = self._add_owner_workspace(session, account)+ self._bind_owner_rbac_role(tenant, account.id, session)++ self._after_workspace_created(tenant, account.id)++ @staticmethod+ def _add_owner_workspace(session: Session, account: Account) -> Tenant:+ tenant = Tenant(name=f"{account.name}'s Workspace")+ tenant.encrypt_public_key = generate_key_pair(tenant.id)+ session.add(tenant)+ session.add(+ TenantAccountJoin(+ tenant_id=tenant.id,+ account_id=account.id,+ role=TenantAccountRole.OWNER,+ )+ )+ for category in TenantPluginAutoUpgradeCategory:+ session.add(+ TenantPluginAutoUpgradeStrategy(+ tenant_id=tenant.id,+ category=category,+ strategy_setting=PluginAutoUpgradeService.default_strategy_setting_for_category(category),+ upgrade_time_of_day=PluginAutoUpgradeService.default_upgrade_time_of_day(tenant.id),+ upgrade_mode=TenantPluginAutoUpgradeMode.EXCLUDE,+ exclude_plugins=[],+ include_plugins=[],+ )+ )+ session.add(+ TenantCreditPool(+ tenant_id=tenant.id,+ quota_limit=dify_config.HOSTED_POOL_CREDITS,+ quota_used=0,+ pool_type=ProviderQuotaType.TRIAL,+ )+ )+ return tenant++ def _bind_owner_rbac_role(self, tenant: Tenant, account_id: str, session: Session) -> None:+ if dify_config.RBAC_ENABLED:+ owner_role_id = self._resolve_owner_role_id(tenant.id, account_id)+ RBACService.MemberRoles.replace(+ tenant_id=tenant.id,+ account_id=account_id,+ member_account_id=account_id,+ role_ids=[owner_role_id],+ session=session,+ )++ def _after_workspace_created(self, tenant: Tenant, account_id: str) -> None:+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:+ BillingService.clean_billing_info_cache(tenant.id)+ tenant_was_created.send(tenant)++ @staticmethod+ def _resolve_owner_role_id(tenant_id: str, account_id: str) -> str:+ roles = RBACService.Roles.list(+ tenant_id,+ account_id,+ options=ListOption(page_number=1, results_per_page=100),+ ).data+ for role in roles:+ if role.is_builtin and role.category == "global_system_default" and role.role_tag == "owner":+ return str(role.id)+ raise ValueError(f"Builtin RBAC owner role not found in tenant {tenant_id}")+++class RedisEmailCodeGateway(EmailCodeGateway):+ def __init__(+ self,+ *,+ redis: RedisClientWrapper | None = None,+ rate_limiter: RateLimiter | None = None,+ ) -> None:+ if rate_limiter is None:+ if redis is None:+ raise ValueError("redis is required when rate_limiter is not provided")+ rate_limiter = RateLimiter(+ prefix="email_code_login_rate_limit",+ max_attempts=_EMAIL_CODE_LOGIN_RATE_LIMIT_ATTEMPTS,+ time_window=_EMAIL_CODE_LOGIN_RATE_LIMIT_SECONDS,+ redis_client=redis,+ )+ self._rate_limiter = rate_limiter++ @override+ def send(+ self,+ *,+ account_id: str | None,+ normalized_email: str,+ recipient_email: str,+ language: str,+ ) -> str:+ normalized_email = normalized_email.lower()+ if self._rate_limiter.is_rate_limited(normalized_email):+ retry_after = int(self._rate_limiter.time_window / 60)+ raise account_errors.EmailCodeSendRateLimitError(retry_after)++ code = "".join(str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6))+ try:+ token = EmailCodeLoginChallengeStore.create(account_id=account_id, email=normalized_email, code=code)+ except EmailCodeLoginChallengeUnavailableError as error:+ logger.warning("Email-code challenge creation is unavailable", exc_info=True)+ raise account_errors.EmailCodeLoginUnavailableError from error+ send_email_code_login_mail_task.delay(language=language, to=recipient_email, code=code)+ self._rate_limiter.increment_rate_limit(normalized_email)+ return token++ @override+ def verify(self, *, normalized_email: str, code: str, token: str) -> EmailCodeChallengeStatus:+ try:+ result = EmailCodeLoginChallengeStore.verify(email=normalized_email.lower(), code=code, token=token)+ except EmailCodeLoginChallengeUnavailableError as error:+ logger.warning("Email-code challenge verification is unavailable", exc_info=True)+ raise account_errors.EmailCodeLoginUnavailableError from error+ return EmailCodeChallengeStatus(result.status.value)+++class RedisResetPasswordEmailGateway(ResetPasswordEmailGateway):+ def __init__(+ self,+ *,+ redis: RedisClientWrapper | None = None,+ rate_limiter: RateLimiter | None = None,+ ) -> None:+ if rate_limiter is None:+ if redis is None:+ raise ValueError("redis is required when rate_limiter is not provided")+ rate_limiter = RateLimiter(+ prefix="reset_password_rate_limit",+ max_attempts=_RESET_PASSWORD_RATE_LIMIT_ATTEMPTS,+ time_window=_RESET_PASSWORD_RATE_LIMIT_SECONDS,+ redis_client=redis,+ )+ self._rate_limiter = rate_limiter++ @override+ def send(+ self,+ *,+ account_id: str | None,+ email: str,+ language: str,+ registration_allowed: bool,+ ) -> str:+ if self._rate_limiter.is_rate_limited(email):+ raise account_errors.ResetPasswordEmailRateLimitError(int(self._rate_limiter.time_window / 60))++ code = "".join(str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6))+ token = TokenManager.generate_token(+ account_id=account_id,+ email=email,+ token_type="reset_password",+ additional_data={"code": code},+ )+ if account_id is not None:+ send_reset_password_mail_task.delay(language=language, to=email, code=code)+ else:+ send_reset_password_mail_task_when_account_not_exist.delay(+ language=language,+ to=email,+ is_allow_register=registration_allowed,+ )+ self._rate_limiter.increment_rate_limit(email)+ return token+++class LoggingConsoleAuthAuditGateway(ConsoleAuthAuditGateway):+ @override+ def login_failed(+ self,+ *,+ email: str,+ reason: LoginFailureReason,+ ip_address: str,+ ) -> None:+ logger.warning(+ "Console login failed: email=%s reason=%s ip_address=%s",+ email,+ reason,+ ip_address,+ )diff --git a/api/services/account_login_service.py b/api/services/account_login_service.pynew file mode 100644index 00000000000..616546a21cb--- /dev/null+++ b/api/services/account_login_service.py@@ -0,0 +1,478 @@+"""Framework-neutral application service for Console authentication use cases."""++from collections.abc import Callable, Sequence+from datetime import datetime+from typing import Never, Protocol++from constants.languages import get_valid_language, language_timezone_mapping+from services import account_errors+from services.account_ports import AccountPasswordHasher+from services.entities.account_login_entities import (+ AccountSessionPreparation,+ AuthTokenPair,+ EmailCodeChallengeStatus,+ EmailCodeLoginCommand,+ EmailCodeSendCommand,+ LoginAccountSnapshot,+ LoginInvitation,+ PasswordLoginCommand,+ PasswordLoginCompletion,+ PasswordLoginResult,+ RefreshAccountStatus,+)+from services.entities.auth_audit_entities import LoginFailureReason++_BANNED_ACCOUNT_STATUS = "banned"+_EMAIL_DOMAIN_SUSPENDED = "email_domain_suspended"+++class ConsoleAuthAccountRepository(Protocol):+ def list_for_login(self, email: str) -> Sequence[LoginAccountSnapshot]: ...++ def complete_password_login(self, completion: PasswordLoginCompletion) -> bool: ...++ def prepare_session(self, account_id: str, preparation: AccountSessionPreparation) -> bool: ...+++class ConsoleAuthWorkspaceQuery(Protocol):+ def has_active_for_account(self, account_id: str) -> bool: ...+++class ConsoleAuthInvitationGateway(Protocol):+ def resolve(self, *, email: str, token: str) -> LoginInvitation | None: ...+++class ConsoleAuthPolicyGateway(Protocol):+ def get_email_freeze_type(self, email: str) -> str | None: ...++ def is_registration_allowed(self) -> bool: ...++ def is_workspace_creation_allowed(self) -> bool: ...++ def has_workspace_capacity(self) -> bool: ...++ def has_account_capacity(self) -> bool: ...+++class ConsoleAuthSecurityGateway(Protocol):+ def is_login_limited(self, email: str) -> bool: ...++ def record_login_failure(self, email: str) -> None: ...++ def reset_login_failures(self, email: str) -> None: ...++ def is_email_send_ip_limited(self, ip_address: str) -> bool: ...+++class HumanVerificationGateway(Protocol):+ def verify(self, *, token: str | None, remote_ip: str, action: str) -> None: ...+++class AccountSessionGateway(Protocol):+ def issue(self, account_id: str) -> AuthTokenPair: ...++ def revoke(self, account_id: str) -> None: ...++ def resolve_refresh_token(self, refresh_token: str) -> str | None: ...++ def rotate(self, *, refresh_token: str, account_id: str) -> AuthTokenPair: ...+++class AccountRefreshPreparationGateway(Protocol):+ def prepare(self, account_id: str) -> RefreshAccountStatus: ...+++class AccountProvisioningGateway(Protocol):+ def create_with_owner_workspace(+ self,+ *,+ email: str,+ name: str,+ interface_language: str,+ timezone: str,+ ip_address: str,+ ) -> str: ...+++class WorkspaceProvisioningGateway(Protocol):+ def create_owner_workspace(self, account_id: str) -> None: ...+++class EmailCodeGateway(Protocol):+ def send(+ self,+ *,+ account_id: str | None,+ normalized_email: str,+ recipient_email: str,+ language: str,+ ) -> str: ...++ def verify(self, *, normalized_email: str, code: str, token: str) -> EmailCodeChallengeStatus: ...+++class ResetPasswordEmailGateway(Protocol):+ def send(+ self,+ *,+ account_id: str | None,+ email: str,+ language: str,+ registration_allowed: bool,+ ) -> str: ...+++class ConsoleAuthAuditGateway(Protocol):+ def login_failed(+ self,+ *,+ email: str,+ reason: LoginFailureReason,+ ip_address: str,+ ) -> None: ...+++class ConsoleAuthenticationService:+ def __init__(+ self,+ *,+ accounts: ConsoleAuthAccountRepository,+ workspaces: ConsoleAuthWorkspaceQuery,+ invitations: ConsoleAuthInvitationGateway,+ policies: ConsoleAuthPolicyGateway,+ security: ConsoleAuthSecurityGateway,+ passwords: AccountPasswordHasher,+ human_verification: HumanVerificationGateway,+ sessions: AccountSessionGateway,+ refresh_preparation: AccountRefreshPreparationGateway,+ account_provisioning: AccountProvisioningGateway,+ workspace_provisioning: WorkspaceProvisioningGateway,+ email_codes: EmailCodeGateway,+ reset_password_emails: ResetPasswordEmailGateway,+ audit: ConsoleAuthAuditGateway,+ now: Callable[[], datetime],+ turnstile_enabled: bool,+ turnstile_verify_required: bool,+ ) -> None:+ self._accounts = accounts+ self._workspaces = workspaces+ self._invitations = invitations+ self._policies = policies+ self._security = security+ self._passwords = passwords+ self._human_verification = human_verification+ self._sessions = sessions+ self._refresh_preparation = refresh_preparation+ self._account_provisioning = account_provisioning+ self._workspace_provisioning = workspace_provisioning+ self._email_codes = email_codes+ self._reset_password_emails = reset_password_emails+ self._audit = audit+ self._now = now+ self._turnstile_enabled = turnstile_enabled+ self._turnstile_verify_required = turnstile_verify_required++ def login_with_password(self, command: PasswordLoginCommand) -> PasswordLoginResult:+ normalized_email = command.email.lower()+ self._ensure_email_eligible(normalized_email, command.ip_address)+ if self._security.is_login_limited(normalized_email):+ self._fail(+ account_errors.LoginRateLimitError(),+ email=normalized_email,+ reason=LoginFailureReason.LOGIN_RATE_LIMITED,+ ip_address=command.ip_address,+ )++ invitation_token = self._resolve_invitation_token(command, normalized_email)+ account = None+ for candidate in self._accounts.list_for_login(command.email):+ completion = self._password_login_completion(+ candidate,+ command,+ invitation_token=invitation_token,+ normalized_email=normalized_email,+ )+ if completion is not None and self._accounts.complete_password_login(completion):+ account = candidate+ break+ if account is None:+ self._invalid_credentials(normalized_email, command.ip_address)++ if not self._workspaces.has_active_for_account(account.id):+ if self._policies.is_workspace_creation_allowed() and not self._policies.has_workspace_capacity():+ raise account_errors.LoginWorkspaceLimitError+ return PasswordLoginResult(token_pair=None, workspace_found=False)++ token_pair = self._issue_session(+ account_id=account.id,+ ip_address=command.ip_address,+ activate_pending_account=False,+ )+ self._security.reset_login_failures(normalized_email)+ return PasswordLoginResult(token_pair=token_pair, workspace_found=True)++ def logout(self, account_id: str) -> None:+ self._sessions.revoke(account_id)++ def send_reset_password_email(self, *, email: str, language: str | None, ip_address: str) -> str:+ normalized_email = email.lower()+ self._ensure_email_eligible(normalized_email, ip_address)+ account = self._preferred_account(email)+ self._ensure_account_not_banned(account, normalized_email, ip_address)+ return self._reset_password_emails.send(+ account_id=account.id if account is not None else None,+ email=account.email if account is not None else normalized_email,+ language=self._email_language(language),+ registration_allowed=self._policies.is_registration_allowed(),+ )++ def send_email_code(self, command: EmailCodeSendCommand) -> str:+ if self._security.is_email_send_ip_limited(command.ip_address):+ raise account_errors.EmailCodeSendIPLimitedError+ if self._turnstile_enabled:+ self._human_verification.verify(+ token=command.turnstile_token,+ remote_ip=command.ip_address,+ action="signin_code",+ )++ normalized_email = command.email.lower()+ self._ensure_email_eligible(normalized_email, command.ip_address)+ account = self._preferred_account(command.email)+ self._ensure_account_not_banned(account, normalized_email, command.ip_address)+ if account is None and not self._policies.is_registration_allowed():+ raise account_errors.AccountNotFoundError++ return self._email_codes.send(+ account_id=account.id if account is not None else None,+ normalized_email=normalized_email,+ recipient_email=account.email if account is not None else normalized_email,+ language=self._email_language(command.language),+ )++ def login_with_email_code(self, command: EmailCodeLoginCommand) -> AuthTokenPair:+ normalized_email = command.email.lower()+ if not self._is_valid_email_code(command.code):+ self._fail(+ account_errors.InvalidEmailCodeError(),+ email=normalized_email,+ reason=LoginFailureReason.INVALID_EMAIL_CODE,+ ip_address=command.ip_address,+ )++ if self._turnstile_enabled and (self._turnstile_verify_required or command.turnstile_token):+ self._human_verification.verify(+ token=command.turnstile_token,+ remote_ip=command.ip_address,+ action="signin_code_verify",+ )++ status = self._email_codes.verify(normalized_email=normalized_email, code=command.code, token=command.token)+ self._ensure_email_code_verified(status, normalized_email, command.ip_address)++ self._ensure_email_eligible(normalized_email, command.ip_address)+ account = self._preferred_account(command.email)+ self._ensure_account_not_banned(account, normalized_email, command.ip_address)+ if account is not None:+ if not self._workspaces.has_active_for_account(account.id):+ if not self._policies.has_workspace_capacity():+ raise account_errors.LoginWorkspaceLimitError+ if not self._policies.is_workspace_creation_allowed():+ raise account_errors.LoginWorkspaceCreationNotAllowedError+ self._workspace_provisioning.create_owner_workspace(account.id)+ account_id = account.id+ else:+ if not self._policies.is_registration_allowed():+ raise account_errors.AccountNotFoundError+ if not self._policies.has_account_capacity():+ raise account_errors.LoginSeatLimitError+ if not self._policies.is_workspace_creation_allowed():+ raise account_errors.LoginWorkspaceCreationNotAllowedError+ if not self._policies.has_workspace_capacity():+ raise account_errors.LoginWorkspaceLimitError+ interface_language = get_valid_language(command.language)+ account_id = self._account_provisioning.create_with_owner_workspace(+ email=normalized_email,+ name=normalized_email,+ interface_language=interface_language,+ timezone=command.timezone or language_timezone_mapping.get(interface_language, "UTC"),+ ip_address=command.ip_address,+ )++ token_pair = self._issue_session(+ account_id=account_id,+ ip_address=command.ip_address,+ activate_pending_account=account is not None and account.status == "pending",+ )+ self._security.reset_login_failures(normalized_email)+ return token_pair++ def refresh(self, refresh_token: str) -> AuthTokenPair:+ account_id = self._sessions.resolve_refresh_token(refresh_token)+ if account_id is None:+ raise account_errors.InvalidRefreshTokenError("Invalid refresh token")+ refresh_status = self._refresh_preparation.prepare(account_id)+ if refresh_status == RefreshAccountStatus.BANNED:+ raise account_errors.InvalidRefreshTokenError("Account is banned.")+ if refresh_status == RefreshAccountStatus.NOT_FOUND:+ raise account_errors.InvalidRefreshTokenError("Invalid account")+ return self._sessions.rotate(refresh_token=refresh_token, account_id=account_id)++ def _password_login_completion(+ self,+ account: LoginAccountSnapshot,+ command: PasswordLoginCommand,+ *,+ invitation_token: str | None,+ normalized_email: str,+ ) -> PasswordLoginCompletion | None:+ if account.status == _BANNED_ACCOUNT_STATUS:+ self._fail(+ account_errors.LoginAccountBannedError(),+ email=normalized_email,+ reason=LoginFailureReason.ACCOUNT_BANNED,+ ip_address=command.ip_address,+ )++ password_update = None+ if account.password_hash is None:+ if invitation_token is None or not command.password:+ return None+ password_update = self._passwords.hash(command.password)+ elif account.password_salt is None or not self._passwords.verify(+ command.password,+ password_hash=account.password_hash,+ password_salt=account.password_salt,+ ):+ return None+ activate_pending_account = account.status == "pending"+ return PasswordLoginCompletion(+ account_id=account.id,+ password=password_update,+ activate_pending_account=activate_pending_account,+ initialized_at=self._now() if activate_pending_account else None,+ )++ def _preferred_account(self, email: str) -> LoginAccountSnapshot | None:+ return next(iter(self._accounts.list_for_login(email)), None)++ def _issue_session(+ self,+ *,+ account_id: str,+ ip_address: str,+ activate_pending_account: bool,+ ) -> AuthTokenPair:+ prepared = self._accounts.prepare_session(+ account_id,+ AccountSessionPreparation(+ logged_in_at=self._now(),+ ip_address=ip_address,+ activate_pending_account=activate_pending_account,+ ),+ )+ if not prepared:+ raise account_errors.AccountNotFoundError+ return self._sessions.issue(account_id)++ def _resolve_invitation_token(self, command: PasswordLoginCommand, normalized_email: str) -> str | None:+ if command.invite_token is None:+ return None+ invitation = self._invitations.resolve(email=command.email, token=command.invite_token)+ if invitation is None:+ return None+ if invitation.email.lower() != normalized_email:+ self._fail(+ account_errors.InvalidLoginInvitationEmailError(),+ email=normalized_email,+ reason=LoginFailureReason.INVALID_INVITATION_EMAIL,+ ip_address=command.ip_address,+ )+ return command.invite_token++ def _ensure_email_eligible(self, email: str, ip_address: str) -> None:+ freeze_type = self._policies.get_email_freeze_type(email)+ if freeze_type is None:+ return+ error: Exception+ if freeze_type == _EMAIL_DOMAIN_SUSPENDED:+ error = account_errors.AccountEmailDomainSuspendedError()+ else:+ error = account_errors.AccountEmailFrozenError()+ self._fail(+ error,+ email=email,+ reason=LoginFailureReason.ACCOUNT_IN_FREEZE,+ ip_address=ip_address,+ )++ def _ensure_account_not_banned(+ self,+ account: LoginAccountSnapshot | None,+ email: str,+ ip_address: str,+ ) -> None:+ if account is not None and account.status == _BANNED_ACCOUNT_STATUS:+ self._fail(+ account_errors.LoginAccountBannedError(),+ email=email,+ reason=LoginFailureReason.ACCOUNT_BANNED,+ ip_address=ip_address,+ )++ def _invalid_credentials(self, email: str, ip_address: str) -> Never:+ self._security.record_login_failure(email)+ self._fail(+ account_errors.InvalidLoginCredentialsError(),+ email=email,+ reason=LoginFailureReason.INVALID_CREDENTIALS,+ ip_address=ip_address,+ )++ def _ensure_email_code_verified(+ self,+ status: EmailCodeChallengeStatus,+ email: str,+ ip_address: str,+ ) -> None:+ if status == EmailCodeChallengeStatus.VERIFIED:+ return+ if status == EmailCodeChallengeStatus.INVALID_TOKEN:+ self._fail(+ account_errors.InvalidEmailCodeTokenError(),+ email=email,+ reason=LoginFailureReason.INVALID_EMAIL_CODE_TOKEN,+ ip_address=ip_address,+ )+ if status == EmailCodeChallengeStatus.EMAIL_MISMATCH:+ self._fail(+ account_errors.EmailCodeEmailMismatchError(),+ email=email,+ reason=LoginFailureReason.EMAIL_CODE_EMAIL_MISMATCH,+ ip_address=ip_address,+ )+ self._fail(+ account_errors.InvalidEmailCodeError(),+ email=email,+ reason=LoginFailureReason.INVALID_EMAIL_CODE,+ ip_address=ip_address,+ )++ def _fail(+ self,+ error: Exception,+ *,+ email: str,+ reason: LoginFailureReason,+ ip_address: str,+ ) -> Never:+ self._audit.login_failed(email=email, reason=reason, ip_address=ip_address)+ raise error++ @staticmethod+ def _email_language(language: str | None) -> str:+ return "zh-Hans" if language == "zh-Hans" else "en-US"++ @staticmethod+ def _is_valid_email_code(code: str) -> bool:+ return len(code) == 6 and code.isascii() and code.isdigit()diff --git a/api/services/account_service.py b/api/services/account_service.pyindex 12a1ece9ac9..e9b91f6af0d 100644--- a/api/services/account_service.py+++ b/api/services/account_service.py@@ -31,7 +31,7 @@ from libs.helper import RateLimiter, TokenManagerfrom libs.helper import timezone as validate_timezonefrom libs.key_providers import generate_key_pairfrom libs.passport import PassportService-from libs.password import compare_password, hash_password, valid_password+from libs.password import hash_password, valid_passwordfrom libs.token import generate_csrf_tokenfrom models.account import (Account,@@ -56,10 +56,6 @@ from services.account_forgot_password_service import (FORGOT_PASSWORD_VERIFICATION_KEY_PREFIX,)from services.billing_service import BillingService-from services.email_code_login_challenge import (- EmailCodeLoginChallengeResult,- EmailCodeLoginChallengeStore,-)from services.enterprise.rbac_service import ListOption, RBACServicefrom services.entities.auth_entities import (ChangeEmailNewEmailToken,@@ -69,10 +65,9 @@ from services.entities.auth_entities import ()from services.errors.account import (AccountAlreadyInTenantError,- AccountLoginError,AccountNormalizedEmailAlreadyInUseError,+ AccountNotFoundError,AccountNotLinkTenantError,- AccountPasswordError,AccountRegisterError,CannotOperateSelfError,EmailDomainSuspendedError,@@ -80,7 +75,6 @@ from services.errors.account import (LinkAccountIntegrateError,MemberNotInTenantError,NoPermissionError,- RefreshTokenAccountNotFoundError,RefreshTokenNotFoundError,RoleAlreadyAssignedError,SeatsLimitExceededError,@@ -93,7 +87,6 @@ from tasks.mail_change_mail_task import (send_change_mail_completed_notification_task,send_change_mail_task,)-from tasks.mail_email_code_login import send_email_code_login_mail_taskfrom tasks.mail_invite_member_task import send_invite_member_mail_taskfrom tasks.mail_owner_transfer_task import (send_new_owner_transfer_notify_email_task,@@ -167,9 +160,6 @@ class AccountService:max_attempts=FORGOT_PASSWORD_SEND_RATE_LIMIT_MAX_ATTEMPTS,time_window=FORGOT_PASSWORD_SEND_RATE_LIMIT_WINDOW_SECONDS,)- email_code_login_rate_limiter = RateLimiter(- prefix="email_code_login_rate_limit", max_attempts=3, time_window=300 * 1- )change_email_rate_limiter = RateLimiter(prefix="change_email_rate_limit", max_attempts=1, time_window=60 * 1)owner_transfer_rate_limiter = RateLimiter(prefix="owner_transfer_rate_limit", max_attempts=1, time_window=60 * 1)@@ -398,10 +388,14 @@ class AccountService:@staticmethoddef get_account_jwt_token(account: Account) -> str:+ return AccountService.get_account_jwt_token_for_account_id(account.id)++ @staticmethod+ def get_account_jwt_token_for_account_id(account_id: str) -> str:exp_dt = datetime.now(UTC) + timedelta(minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES)exp = int(exp_dt.timestamp())payload = {- "user_id": account.id,+ "user_id": account_id,"exp": exp,"iss": dify_config.DEPLOYMENT_EDITION.value,"sub": "Console API Passport",@@ -410,37 +404,6 @@ class AccountService:token: str = PassportService().issue(payload)return token- @staticmethod- def authenticate(email: str, password: str, invite_token: str | None = None, *, session: Session) -> Account:- """authenticate account with email and password"""-- account = session.scalar(select(Account).where(Account.email == email).limit(1))- if not account:- raise AccountPasswordError("Invalid email or password.")-- if account.status == AccountStatus.BANNED:- raise AccountLoginError("Account is banned.")-- if password and invite_token and account.password is None:- # if invite_token is valid, set password and password_salt- salt = secrets.token_bytes(16)- base64_salt = base64.b64encode(salt).decode()- password_hashed = hash_password(password, salt)- base64_password_hashed = base64.b64encode(password_hashed).decode()- account.password = base64_password_hashed- account.password_salt = base64_salt-- if account.password is None or not compare_password(password, account.password, account.password_salt):- raise AccountPasswordError("Invalid email or password.")-- if account.status == AccountStatus.PENDING:- account.status = AccountStatus.ACTIVE- account.initialized_at = naive_utc_now()-- session.commit()-- return account-@staticmethoddef create_account(email: str,@@ -457,9 +420,7 @@ class AccountService:) -> Account:"""Create an account, preferring explicit user timezone over language-derived defaults."""if not SystemFeatureService.is_registration_allowed() and not is_setup:- from controllers.console.error import AccountNotFound-- raise AccountNotFound()+ raise AccountNotFoundError("Account registration is disabled.")if check_normalized_email:AccountService.ensure_registration_email_available(email, session=session)@@ -613,38 +574,39 @@ class AccountService:account.status = AccountStatus.ACTIVEsession.commit()- access_token = AccountService.get_account_jwt_token(account=account)+ return AccountService.issue_token_pair(account.id)++ @staticmethod+ def issue_token_pair(account_id: str) -> TokenPair:+ access_token = AccountService.get_account_jwt_token_for_account_id(account_id)refresh_token = _generate_refresh_token()- csrf_token = generate_csrf_token(account.id)+ csrf_token = generate_csrf_token(account_id)- AccountService._store_refresh_token(refresh_token, account.id)+ AccountService._store_refresh_token(refresh_token, account_id)return TokenPair(access_token=access_token, refresh_token=refresh_token, csrf_token=csrf_token)@staticmethod- def logout(*, account: Account):- refresh_token = redis_client.get(AccountService._get_account_refresh_token_key(account.id))+ def revoke_token_pair(account_id: str) -> None:+ refresh_token = redis_client.get(AccountService._get_account_refresh_token_key(account_id))if refresh_token:- AccountService._delete_refresh_token(refresh_token.decode("utf-8"), account.id)+ AccountService._delete_refresh_token(refresh_token.decode("utf-8"), account_id)@staticmethod- def refresh_token(refresh_token: str, *, session: Session) -> TokenPair:- # Verify the refresh token+ def resolve_refresh_token(refresh_token: str) -> str:account_id = redis_client.get(AccountService._get_refresh_token_key(refresh_token))if not account_id:raise RefreshTokenNotFoundError("Invalid refresh token")+ return account_id.decode("utf-8")- account = AccountService.load_user(account_id.decode("utf-8"), session)- if not account:- raise RefreshTokenAccountNotFoundError("Invalid account")-- # Generate new access token and refresh token- new_access_token = AccountService.get_account_jwt_token(account)+ @staticmethod+ def rotate_token_pair(refresh_token: str, account_id: str) -> TokenPair:+ new_access_token = AccountService.get_account_jwt_token_for_account_id(account_id)new_refresh_token = _generate_refresh_token()- AccountService._delete_refresh_token(refresh_token, account.id)- AccountService._store_refresh_token(new_refresh_token, account.id)- csrf_token = generate_csrf_token(account.id)+ AccountService._delete_refresh_token(refresh_token, account_id)+ AccountService._store_refresh_token(new_refresh_token, account_id)+ csrf_token = generate_csrf_token(account_id)return TokenPair(access_token=new_access_token, refresh_token=new_refresh_token, csrf_token=csrf_token)@@ -903,36 +865,6 @@ class AccountService:def get_owner_transfer_data(cls, token: str) -> dict[str, Any] | None:return TokenManager.get_token_data(token, "owner_transfer")- @classmethod- def send_email_code_login_email(- cls,- account: Account | None = None,- email: str | None = None,- language: str = "en-US",- ):- email = account.email if account else email- if email is None:- raise ValueError("Email must be provided.")- email = email.lower()- if cls.email_code_login_rate_limiter.is_rate_limited(email):- from controllers.console.auth.error import EmailCodeLoginRateLimitExceededError-- raise EmailCodeLoginRateLimitExceededError(int(cls.email_code_login_rate_limiter.time_window / 60))-- code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])- token = EmailCodeLoginChallengeStore.create(- account_id=str(account.id) if account else None,- email=email,- code=code,- )- send_email_code_login_mail_task.delay(- language=language,- to=account.email if account else email,- code=code,- )- cls.email_code_login_rate_limiter.increment_rate_limit(email)- return token-@staticmethoddef get_account_by_email_with_case_fallback(email: str, *, session: Session) -> Account | None:"""@@ -947,38 +879,6 @@ class AccountService:return session.execute(select(Account).where(Account.email == email.lower())).scalar_one_or_none()- @classmethod- def verify_email_code_login_challenge(cls, *, email: str, code: str, token: str) -> EmailCodeLoginChallengeResult:- return EmailCodeLoginChallengeStore.verify(email=email, code=code, token=token)-- @classmethod- def get_user_through_email(cls, email: str, *, session: Session):- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD and BillingService.is_email_in_freeze(email):- freeze_type = BillingService.get_email_freeze_type(email) or "freeze"- if freeze_type == "email_domain_suspended":- raise EmailDomainSuspendedError()- raise AccountRegisterError(- description=(- "This email account has been deleted within the past "- "30 days and is temporarily unavailable for new account registration"- )- )-- account = session.scalar(select(Account).where(Account.email == email).limit(1))- if not account:- return None-- if account.status == AccountStatus.BANNED:- raise Unauthorized("Account is banned.")-- return account-- @classmethod- def get_account_freeze_type(cls, email: str):- if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:- return None- return BillingService.get_email_freeze_type(email)-@staticmethod@redis_fallback(default_return=None)def add_login_error_rate_limit(email: str):diff --git a/api/services/entities/account_login_entities.py b/api/services/entities/account_login_entities.pynew file mode 100644index 00000000000..140a42522d2--- /dev/null+++ b/api/services/entities/account_login_entities.py@@ -0,0 +1,94 @@+"""Framework-neutral values shared by Console authentication use cases."""++from dataclasses import dataclass+from datetime import datetime+from enum import StrEnum++from services.entities.account_entities import AccountPasswordDigest+++class EmailCodeChallengeStatus(StrEnum):+ VERIFIED = "verified"+ INVALID_TOKEN = "invalid_token"+ EMAIL_MISMATCH = "email_mismatch"+ INVALID_CODE = "invalid_code"+ EXHAUSTED = "exhausted"+++class RefreshAccountStatus(StrEnum):+ READY = "ready"+ NOT_FOUND = "not_found"+ BANNED = "banned"+++@dataclass(frozen=True, slots=True)+class LoginAccountSnapshot:+ id: str+ email: str+ status: str+ password_hash: str | None+ password_salt: str | None+++@dataclass(frozen=True, slots=True)+class LoginInvitation:+ email: str+++@dataclass(frozen=True, slots=True)+class PasswordLoginCompletion:+ account_id: str+ password: AccountPasswordDigest | None+ activate_pending_account: bool+ initialized_at: datetime | None++ def __post_init__(self) -> None:+ if self.activate_pending_account != (self.initialized_at is not None):+ raise ValueError("pending-account activation requires an initialization timestamp")+++@dataclass(frozen=True, slots=True)+class AccountSessionPreparation:+ logged_in_at: datetime+ ip_address: str+ activate_pending_account: bool+++@dataclass(frozen=True, slots=True)+class AuthTokenPair:+ access_token: str+ refresh_token: str+ csrf_token: str+++@dataclass(frozen=True, slots=True)+class PasswordLoginCommand:+ email: str+ password: str+ invite_token: str | None+ ip_address: str+++@dataclass(frozen=True, slots=True)+class EmailCodeSendCommand:+ email: str+ language: str | None+ turnstile_token: str | None+ ip_address: str+++@dataclass(frozen=True, slots=True)+class EmailCodeLoginCommand:+ email: str+ code: str+ token: str+ turnstile_token: str | None+ language: str | None+ timezone: str | None+ ip_address: str+++@dataclass(frozen=True, slots=True)+class PasswordLoginResult:+ token_pair: AuthTokenPair | None+ workspace_found: booldiff --git a/api/services/entities/auth_audit_entities.py b/api/services/entities/auth_audit_entities.pynew file mode 100644index 00000000000..2b3a7872124--- /dev/null+++ b/api/services/entities/auth_audit_entities.py@@ -0,0 +1,17 @@+"""Shared contracts for authentication audit events."""++from enum import StrEnum, auto+++class LoginFailureReason(StrEnum):+ """Bounded reason codes shared by Console and Web login audit logs."""++ ACCOUNT_BANNED = auto()+ ACCOUNT_IN_FREEZE = auto()+ ACCOUNT_NOT_FOUND = auto()+ EMAIL_CODE_EMAIL_MISMATCH = auto()+ INVALID_CREDENTIALS = auto()+ INVALID_EMAIL_CODE = auto()+ INVALID_EMAIL_CODE_TOKEN = auto()+ INVALID_INVITATION_EMAIL = auto()+ LOGIN_RATE_LIMITED = auto()diff --git a/api/services/entities/auth_entities.py b/api/services/entities/auth_entities.pyindex 55d46257779..344dbe8b56c 100644--- a/api/services/entities/auth_entities.py+++ b/api/services/entities/auth_entities.py@@ -1,4 +1,4 @@-from enum import StrEnum, auto+from enum import StrEnumfrom typing import Annotated, Literalfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator@@ -7,20 +7,6 @@ from libs.helper import EmailStrfrom libs.password import valid_password-class LoginFailureReason(StrEnum):- """Bounded reason codes for failed login audit logs."""-- ACCOUNT_BANNED = auto()- ACCOUNT_IN_FREEZE = auto()- ACCOUNT_NOT_FOUND = auto()- EMAIL_CODE_EMAIL_MISMATCH = auto()- INVALID_CREDENTIALS = auto()- INVALID_EMAIL_CODE = auto()- INVALID_EMAIL_CODE_TOKEN = auto()- INVALID_INVITATION_EMAIL = auto()- LOGIN_RATE_LIMITED = auto()--class ChangeEmailPhase(StrEnum):"""Change-email token state machine.diff --git a/api/services/errors/account.py b/api/services/errors/account.pyindex 3706f9da246..fc1d6772174 100644--- a/api/services/errors/account.py+++ b/api/services/errors/account.py@@ -34,10 +34,6 @@ class RefreshTokenNotFoundError(BaseServiceError):pass-class RefreshTokenAccountNotFoundError(BaseServiceError):- pass--class AccountNotLinkTenantError(BaseServiceError):passdiff --git a/api/tests/test_containers_integration_tests/services/test_account_service.py b/api/tests/test_containers_integration_tests/services/test_account_service.pyindex 80000b06f13..30292d43826 100644--- a/api/tests/test_containers_integration_tests/services/test_account_service.py+++ b/api/tests/test_containers_integration_tests/services/test_account_service.py@@ -1,6 +1,6 @@import jsonfrom hashlib import sha256-from unittest.mock import patch+from unittest.mock import MagicMock, patchimport pytestfrom faker import Faker@@ -8,14 +8,18 @@ from sqlalchemy.orm import Sessionfrom werkzeug.exceptions import Unauthorizedfrom configs import dify_config-from controllers.console.error import AccountNotFound, NotAllowedCreateWorkspace+from controllers.console.error import NotAllowedCreateWorkspacefrom enums import DeploymentEdition+from extensions.ext_application_services import application_services+from extensions.ext_redis import redis_clientfrom models import AccountStatus, App, Dataset, TenantAccountJoin, TenantStatus+from services import account_errors+from services.account_login_adapters import RedisAccountSessionGatewayfrom services.account_service import AccountService, RegisterService, TenantService, TokenPair+from services.entities.account_login_entities import AuthTokenPairfrom services.errors.account import (AccountAlreadyInTenantError,- AccountLoginError,- AccountPasswordError,+ AccountNotFoundError,AccountRegisterError,SeatsLimitExceededError,)@@ -33,6 +37,7 @@ class TestAccountService:patch("services.account_service.SystemFeatureService") as mock_feature_service,patch("services.account_service.BillingService") as mock_billing_service,patch("services.account_service.PassportService") as mock_passport_service,+ patch("services.account_login_adapters.PassportService") as mock_login_passport_service,):# Setup default mock returnsmock_feature_service.is_registration_allowed.return_value = True@@ -40,7 +45,10 @@ class TestAccountService:mock_feature_service.get_license.return_value.workspaces.is_available.return_value = Truemock_feature_service.get_license.return_value.seats.is_available.return_value = Truemock_billing_service.is_email_in_freeze.return_value = False- mock_passport_service.return_value.issue.return_value = "mock_jwt_token"+ passport_service = MagicMock()+ passport_service.issue.return_value = "mock_jwt_token"+ mock_passport_service.return_value = passport_service+ mock_login_passport_service.return_value = passport_serviceyield {"feature_service": mock_feature_service,@@ -48,9 +56,9 @@ class TestAccountService:"passport_service": mock_passport_service,}- def test_create_account_and_login(self, db_session_with_containers: Session, mock_external_service_dependencies):+ def test_create_account(self, db_session_with_containers: Session, mock_external_service_dependencies):"""- Test account creation and login with correct password.+ Test account creation with a password."""fake = Faker()email = fake.email()@@ -70,10 +78,6 @@ class TestAccountService:assert account.email == emailassert account.status == AccountStatus.ACTIVE- # Login with correct password- logged_in = AccountService.authenticate(email, password, session=db_session_with_containers)- assert logged_in.id == account.id-def test_create_account_without_password(self, db_session_with_containers: Session, mock_external_service_dependencies):@@ -133,7 +137,7 @@ class TestAccountService:# Setup mocks to disable registrationmock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = False- with pytest.raises(AccountNotFound): # AccountNotFound exception+ with pytest.raises(AccountNotFoundError):AccountService.create_account(email=email,name=name,@@ -168,138 +172,6 @@ class TestAccountService:dify_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY # Reset config for other tests- def test_authenticate_account_not_found(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test authentication with non-existent account.- """- fake = Faker()- email = fake.email()- password = generate_valid_password(fake)- with pytest.raises(AccountPasswordError):- AccountService.authenticate(email, password, session=db_session_with_containers)-- def test_authenticate_banned_account(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test authentication with banned account.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Create account first- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Ban the account- account.status = AccountStatus.BANNED-- db_session_with_containers.commit()-- with pytest.raises(AccountLoginError):- AccountService.authenticate(email, password, session=db_session_with_containers)-- def test_authenticate_wrong_password(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test authentication with wrong password.- """- fake = Faker()- email = fake.email()- name = fake.name()- correct_password = generate_valid_password(fake)- wrong_password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Create account first- AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=correct_password,- session=db_session_with_containers,- )-- with pytest.raises(AccountPasswordError):- AccountService.authenticate(email, wrong_password, session=db_session_with_containers)-- def test_authenticate_with_invite_token(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test authentication with invite token to set password for account without password.- """- fake = Faker()- email = fake.email()- name = fake.name()- new_password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Create account without password- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=None,- session=db_session_with_containers,- )-- # Authenticate with invite token to set password- authenticated_account = AccountService.authenticate(- email,- new_password,- invite_token="valid_invite_token",- session=db_session_with_containers,- )-- assert authenticated_account.id == account.id- assert authenticated_account.password is not None- assert authenticated_account.password_salt is not None-- def test_authenticate_pending_account_activation(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test authentication activates pending account.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Create account with pending status- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )- account.status = AccountStatus.PENDING-- db_session_with_containers.commit()-- # Authenticate should activate the account- authenticated_account = AccountService.authenticate(email, password, session=db_session_with_containers)- assert authenticated_account.status == AccountStatus.ACTIVE- assert authenticated_account.initialized_at is not None-def test_create_account_and_tenant(self, db_session_with_containers: Session, mock_external_service_dependencies):"""Test account creation with automatic tenant creation.@@ -590,7 +462,9 @@ class TestAccountService:db_session_with_containers.refresh(account)assert account.status == AccountStatus.ACTIVE- def test_logout(self, db_session_with_containers: Session, mock_external_service_dependencies):+ def test_authentication_service_logout(+ self, db_session_with_containers: Session, mock_external_service_dependencies+ ):"""Test logout functionality."""@@ -612,19 +486,18 @@ class TestAccountService:session=db_session_with_containers,)- # Login first to get refresh token- token_pair = AccountService.login(account, session=db_session_with_containers)+ # Issue a refresh token through the session adapter used by the application service.+ RedisAccountSessionGateway(redis=redis_client).issue(account.id)- # Logout- AccountService.logout(account=account)+ application_services().accounts.authentication.logout(account.id)# Verify refresh token was deleted from Redis- from extensions.ext_redis import redis_client-refresh_token_key = f"account_refresh_token:{account.id}"assert redis_client.get(refresh_token_key) is None- def test_refresh_token_success(self, db_session_with_containers: Session, mock_external_service_dependencies):+ def test_authentication_service_refresh_success(+ self, db_session_with_containers: Session, mock_external_service_dependencies+ ):"""Test successful token refresh."""@@ -651,28 +524,26 @@ class TestAccountService:account=account, name=tenant_name, is_setup=True, session=db_session_with_containers)- # Login to get initial tokens- initial_token_pair = AccountService.login(account, session=db_session_with_containers)+ initial_token_pair = RedisAccountSessionGateway(redis=redis_client).issue(account.id)- # Refresh token- new_token_pair = AccountService.refresh_token(- initial_token_pair.refresh_token, session=db_session_with_containers- )+ new_token_pair = application_services().accounts.authentication.refresh(initial_token_pair.refresh_token)- assert isinstance(new_token_pair, TokenPair)+ assert isinstance(new_token_pair, AuthTokenPair)assert new_token_pair.access_token == "new_mock_access_token"assert new_token_pair.refresh_token != initial_token_pair.refresh_token- def test_refresh_token_invalid_token(self, db_session_with_containers: Session, mock_external_service_dependencies):+ def test_authentication_service_refresh_rejects_invalid_token(+ self, db_session_with_containers: Session, mock_external_service_dependencies+ ):"""Test refresh token with invalid token."""fake = Faker()invalid_token = fake.uuid4()- with pytest.raises(ValueError, match="Invalid refresh token"):- AccountService.refresh_token(invalid_token, session=db_session_with_containers)+ with pytest.raises(account_errors.InvalidRefreshTokenError, match="Invalid refresh token"):+ application_services().accounts.authentication.refresh(invalid_token)- def test_refresh_token_invalid_account(+ def test_authentication_service_refresh_rejects_missing_account(self, db_session_with_containers: Session, mock_external_service_dependencies):"""@@ -696,17 +567,15 @@ class TestAccountService:session=db_session_with_containers,)- # Login to get tokens- token_pair = AccountService.login(account, session=db_session_with_containers)+ token_pair = RedisAccountSessionGateway(redis=redis_client).issue(account.id)# Delete accountdb_session_with_containers.delete(account)db_session_with_containers.commit()- # Try to refresh token with deleted account- with pytest.raises(ValueError, match="Invalid account"):- AccountService.refresh_token(token_pair.refresh_token, session=db_session_with_containers)+ with pytest.raises(account_errors.InvalidRefreshTokenError, match="Invalid account"):+ application_services().accounts.authentication.refresh(token_pair.refresh_token)def test_load_user_success(self, db_session_with_containers: Session, mock_external_service_dependencies):"""@@ -848,96 +717,6 @@ class TestAccountService:assert loaded_account is not Noneassert loaded_account.id == account.id- def test_get_user_through_email_success(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting user through email successfully.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Get user through email- found_user = AccountService.get_user_through_email(email, session=db_session_with_containers)-- assert found_user is not None- assert found_user.id == account.id-- def test_get_user_through_email_not_found(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting user through non-existent email.- """- fake = Faker()- domain = f"test-{fake.random_letters(10)}.com"- non_existent_email = fake.email(domain=domain)- found_user = AccountService.get_user_through_email(non_existent_email, session=db_session_with_containers)- assert found_user is None-- def test_get_user_through_email_banned_account(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting banned user through email raises Unauthorized.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Ban the account- account.status = AccountStatus.BANNED-- db_session_with_containers.commit()-- with pytest.raises(Unauthorized): # Unauthorized exception- AccountService.get_user_through_email(email, session=db_session_with_containers)-- def test_get_user_through_email_in_freeze(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting user through email that is in freeze period.- """- fake = Faker()- email_in_freeze = fake.email()- # Setup mocks- dify_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = True-- with pytest.raises(AccountRegisterError):- AccountService.get_user_through_email(email_in_freeze, session=db_session_with_containers)-- # Reset config- dify_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY-class TestTenantService:"""Integration tests for TenantService using testcontainers."""diff --git a/api/tests/unit_tests/controllers/console/auth/test_authentication_security.py b/api/tests/unit_tests/controllers/console/auth/test_authentication_security.pydeleted file mode 100644index c5ea4d69ace..00000000000--- a/api/tests/unit_tests/controllers/console/auth/test_authentication_security.py+++ /dev/null@@ -1,149 +0,0 @@-"""Test authentication security to prevent user enumeration."""--import base64-from unittest.mock import patch--import pytest-from flask import Flask-from flask_restx import Api--import services.errors.account-from controllers.console.auth.error import AuthenticationFailedError-from controllers.console.auth.login import LoginApi-from enums import DeploymentEdition-from models.account import Account-from tests.unit_tests.config_override import config_overrides_context---def encode_password(password: str) -> str:- """Helper to encode password as Base64 for testing."""- return base64.b64encode(password.encode("utf-8")).decode()---class TestAuthenticationSecurity:- """Test authentication endpoints for security against user enumeration."""-- def setup_method(self):- """Set up test fixtures."""- self.app = Flask(__name__)- self.api = Api(self.app)- self.api.add_resource(LoginApi, "/login")- self.client = self.app.test_client()- self.app.config["TESTING"] = True-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.SystemFeatureService.is_registration_allowed")- @patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")- @patch("controllers.console.auth.login.AccountService.authenticate")- @patch("controllers.console.auth.login.AccountService.add_login_error_rate_limit")- @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)- @patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")- def test_login_invalid_email_with_registration_allowed(- self, mock_get_invitation, mock_add_rate_limit, mock_authenticate, mock_is_rate_limit, mock_features, mock_db- ):- """Test that invalid email raises AuthenticationFailedError when account not found."""- # Arrange- mock_is_rate_limit.return_value = False- mock_get_invitation.return_value = None- mock_authenticate.side_effect = services.errors.account.AccountPasswordError("Invalid email or password.")- mock_features.return_value = True-- # Act- with self.app.test_request_context(- "/login",- method="POST",- json={"email": "[email protected]", "password": encode_password("WrongPass123!")},- ):- login_api = LoginApi()-- # Assert- with pytest.raises(AuthenticationFailedError) as exc_info:- login_api.post()-- assert exc_info.value.error_code == "authentication_failed"- assert exc_info.value.description == "Invalid email or password."- mock_add_rate_limit.assert_called_once_with("[email protected]")-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")- @patch("controllers.console.auth.login.AccountService.authenticate")- @patch("controllers.console.auth.login.AccountService.add_login_error_rate_limit")- @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)- @patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")- def test_login_wrong_password_returns_error(- self, mock_get_invitation, mock_add_rate_limit, mock_authenticate, mock_is_rate_limit, mock_db- ):- """Test that wrong password returns AuthenticationFailedError."""- # Arrange- mock_is_rate_limit.return_value = False- mock_get_invitation.return_value = None- mock_authenticate.side_effect = services.errors.account.AccountPasswordError("Wrong password")-- # Act- with self.app.test_request_context(- "/login",- method="POST",- json={"email": "[email protected]", "password": encode_password("WrongPass123!")},- ):- login_api = LoginApi()-- # Assert- with pytest.raises(AuthenticationFailedError) as exc_info:- login_api.post()-- assert exc_info.value.error_code == "authentication_failed"- assert exc_info.value.description == "Invalid email or password."- mock_add_rate_limit.assert_called_once_with("[email protected]")-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.SystemFeatureService.is_registration_allowed")- @patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")- @patch("controllers.console.auth.login.AccountService.authenticate")- @patch("controllers.console.auth.login.AccountService.add_login_error_rate_limit")- @config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)- @patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")- def test_login_invalid_email_with_registration_disabled(- self, mock_get_invitation, mock_add_rate_limit, mock_authenticate, mock_is_rate_limit, mock_features, mock_db- ):- """Test that invalid email raises AuthenticationFailedError when account not found."""- # Arrange- mock_is_rate_limit.return_value = False- mock_get_invitation.return_value = None- mock_authenticate.side_effect = services.errors.account.AccountPasswordError("Invalid email or password.")- mock_features.return_value = False-- # Act- with self.app.test_request_context(- "/login",- method="POST",- json={"email": "[email protected]", "password": encode_password("WrongPass123!")},- ):- login_api = LoginApi()-- # Assert- with pytest.raises(AuthenticationFailedError) as exc_info:- login_api.post()-- assert exc_info.value.error_code == "authentication_failed"- assert exc_info.value.description == "Invalid email or password."- mock_add_rate_limit.assert_called_once_with("[email protected]")-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.SystemFeatureService.is_registration_allowed")- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.AccountService.send_reset_password_email")- def test_reset_password_with_existing_account(self, mock_send_email, mock_get_user, mock_features, mock_db):- """Test that reset password returns success with token for existing accounts."""- # Mock the setup check-- # Test with existing account- mock_get_user.return_value = Account(name="Existing User", email="[email protected]")- mock_send_email.return_value = "token123"-- with self.app.test_request_context("/reset-password", method="POST", json={"email": "[email protected]"}):- from controllers.console.auth.login import ResetPasswordSendEmailApi-- api = ResetPasswordSendEmailApi()- result = api.post()-- assert result == {"result": "success", "data": "token123"}diff --git a/api/tests/unit_tests/controllers/console/auth/test_email_verification.py b/api/tests/unit_tests/controllers/console/auth/test_email_verification.pydeleted file mode 100644index aedea3033e7..00000000000--- a/api/tests/unit_tests/controllers/console/auth/test_email_verification.py+++ /dev/null@@ -1,884 +0,0 @@-"""-Test suite for email verification authentication flows.--This module tests the email code login mechanism including:-- Email code sending with rate limiting-- Code verification and validation-- Account creation via email verification-- Workspace creation for new users-"""--import base64-from collections.abc import Callable-from unittest.mock import ANY, MagicMock, patch--import pytest-from flask import Flask-from pydantic import ValidationError--from controllers.console.auth.error import (- EmailCodeError,- EmailCodeLoginServiceUnavailableError,- InvalidEmailError,- InvalidTokenError,- TurnstileServiceUnavailableError,- TurnstileVerificationFailedError,-)-from controllers.console.auth.login import (- EmailCodeLoginApi,- EmailCodeLoginPayload,- EmailCodeLoginSendEmailApi,- EmailCodeSendPayload,- EmailPayload,-)-from controllers.console.error import (- AccountInFreezeError,- AccountNotFound,- EmailDomainSuspendedError,- EmailSendIpLimitError,- NotAllowedCreateWorkspace,- WorkspacesLimitExceeded,-)-from enums import DeploymentEdition-from models.account import Account, Tenant-from services.email_code_login_challenge import (- EmailCodeLoginChallengeResult,- EmailCodeLoginChallengeStatus,- EmailCodeLoginChallengeUnavailableError,-)-from services.errors.account import (- AccountRegisterError,-)-from services.errors.account import (- EmailDomainSuspendedError as EmailDomainSuspendedRegistrationError,-)-from services.turnstile_service import TurnstileChallengeRejectedError, TurnstileUpstreamError--TEST_TOKEN = "00000000-0000-4000-8000-000000000001"--[email protected](autouse=True)-def _default_edition(config_overrides: Callable[..., None]) -> None:- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)---def encode_code(code: str) -> str:- """Helper to encode verification code as Base64 for testing."""- return base64.b64encode(code.encode("utf-8")).decode()---def test_email_code_login_payload_rejects_invalid_timezone():- with pytest.raises(ValidationError):- EmailCodeLoginPayload.model_validate(- {- "email": "[email protected]",- "code": "123456",- "token": TEST_TOKEN,- "timezone": "",- }- )---def test_turnstile_token_is_scoped_to_email_code_send_payload():- assert "turnstile_token" in EmailCodeSendPayload.model_fields- assert "turnstile_token" not in EmailPayload.model_fields- assert "turnstile_token" in EmailCodeLoginPayload.model_fields---def test_email_code_login_code_schema_does_not_describe_plaintext_format():- code_schema = EmailCodeLoginPayload.model_json_schema()["properties"]["code"]-- assert "pattern" not in code_schema---def test_email_code_login_payload_rejects_non_uuid_token():- with pytest.raises(ValidationError):- EmailCodeLoginPayload.model_validate({"email": "[email protected]", "code": "123456", "token": "not-a-uuid"})---class TestEmailCodeLoginSendEmailApi:- """Test cases for sending email verification codes."""-- @pytest.fixture- def app(self):- """Create Flask test application."""- app = Flask(__name__)- app.config["TESTING"] = True- return app-- @pytest.fixture- def mock_account(self) -> Account:- """Create a real transient account for the mail service boundary."""- return Account(name="Test User", email="[email protected]")-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_email_send_ip_limit")- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.AccountService.send_email_code_login_email")- def test_send_email_code_existing_user(- self, mock_send_email, mock_get_user, mock_is_ip_limit, mock_db, app, mock_account- ):- """- Test sending email code to existing user.-- Verifies that:- - Email code is sent to existing account- - Token is generated and returned- - IP rate limiting is checked- """- # Arrange- mock_is_ip_limit.return_value = False- mock_get_user.return_value = mock_account- mock_send_email.return_value = "email_token_123"-- # Act- with app.test_request_context(- "/email-code-login", method="POST", json={"email": "[email protected]", "language": "en-US"}- ):- api = EmailCodeLoginSendEmailApi()- response = api.post()-- # Assert- assert response["result"] == "success"- assert response["data"] == "email_token_123"- mock_send_email.assert_called_once_with(account=mock_account, language="en-US")-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_email_send_ip_limit")- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.SystemFeatureService.is_registration_allowed")- @patch("controllers.console.auth.login.AccountService.send_email_code_login_email")- def test_send_email_code_new_user_registration_allowed(- self, mock_send_email, mock_get_features, mock_get_user, mock_is_ip_limit, mock_db, app- ):- """- Test sending email code to new user when registration is allowed.-- Verifies that:- - Email code is sent even for non-existent accounts- - Registration is allowed by system features- """- # Arrange- mock_is_ip_limit.return_value = False- mock_get_user.return_value = None- mock_get_features.return_value = True- mock_send_email.return_value = "email_token_123"-- # Act- with app.test_request_context(- "/email-code-login", method="POST", json={"email": "[email protected]", "language": "en-US"}- ):- api = EmailCodeLoginSendEmailApi()- response = api.post()-- # Assert- assert response["result"] == "success"- mock_send_email.assert_called_once_with(email="[email protected]", language="en-US")-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_email_send_ip_limit")- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.SystemFeatureService.is_registration_allowed")- def test_send_email_code_new_user_registration_disabled(- self, mock_get_features, mock_get_user, mock_is_ip_limit, mock_db, app- ):- """- Test sending email code to new user when registration is disabled.-- Verifies that:- - AccountNotFound is raised for non-existent accounts- - Registration is blocked by system features- """- # Arrange- mock_is_ip_limit.return_value = False- mock_get_user.return_value = None- mock_get_features.return_value = False-- # Act & Assert- with app.test_request_context("/email-code-login", method="POST", json={"email": "[email protected]"}):- api = EmailCodeLoginSendEmailApi()- with pytest.raises(AccountNotFound):- api.post()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_email_send_ip_limit")- @patch("controllers.console.auth.login.TurnstileService.verify")- def test_send_email_code_ip_rate_limited(- self,- mock_verify,- mock_is_ip_limit,- mock_db,- app: Flask,- config_overrides: Callable[..., None],- ):- """- Test email code sending blocked by IP rate limit.-- Verifies that:- - EmailSendIpLimitError is raised when IP limit exceeded- - Prevents spam and abuse- """- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)- mock_is_ip_limit.return_value = True-- # Act & Assert- with (- app.test_request_context("/email-code-login", method="POST", json={"email": "[email protected]"}),- ):- with pytest.raises(EmailSendIpLimitError):- EmailCodeLoginSendEmailApi().post()-- mock_verify.assert_not_called()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_email_send_ip_limit", return_value=False)- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.AccountService.send_email_code_login_email", return_value="token")- @patch("controllers.console.auth.login.TurnstileService.verify")- def test_cloud_send_verifies_turnstile_before_sending_email(- self,- mock_verify,- mock_send_email,- mock_get_user,- mock_is_ip_limit,- mock_db,- app: Flask,- mock_account,- config_overrides: Callable[..., None],- ):- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)- mock_get_user.return_value = mock_account-- with (- app.test_request_context(- "/email-code-login",- method="POST",- json={"email": "[email protected]", "turnstile_token": "verified-token"},- headers={"CF-Connecting-IP": "203.0.113.8"},- ),- ):- response = EmailCodeLoginSendEmailApi().post()-- assert response["result"] == "success"- mock_verify.assert_called_once_with(token="verified-token", remote_ip="203.0.113.8")- mock_send_email.assert_called_once()-- @pytest.mark.parametrize(- ("service_error", "http_error"),- [- (TurnstileChallengeRejectedError(), TurnstileVerificationFailedError),- (TurnstileUpstreamError(), TurnstileServiceUnavailableError),- ],- )- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_email_send_ip_limit", return_value=False)- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- def test_cloud_send_maps_turnstile_errors_without_looking_up_account(- self,- mock_get_user,- mock_is_ip_limit,- mock_db,- app: Flask,- service_error: Exception,- http_error: type[Exception],- config_overrides: Callable[..., None],- ):- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)- with (- patch("controllers.console.auth.login.TurnstileService.verify", side_effect=service_error),- app.test_request_context(- "/email-code-login",- method="POST",- json={"email": "[email protected]", "turnstile_token": "challenge-token"},- ),- pytest.raises(http_error),- ):- EmailCodeLoginSendEmailApi().post()-- mock_get_user.assert_not_called()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_email_send_ip_limit", return_value=False)- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.AccountService.send_email_code_login_email", return_value="token")- @patch("controllers.console.auth.login.TurnstileService.verify")- def test_self_hosted_send_does_not_call_turnstile(- self,- mock_verify,- mock_send_email,- mock_get_user,- mock_is_ip_limit,- mock_db,- app: Flask,- mock_account,- config_overrides: Callable[..., None],- ):- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)- mock_get_user.return_value = mock_account-- with (- app.test_request_context("/email-code-login", method="POST", json={"email": "[email protected]"}),- ):- response = EmailCodeLoginSendEmailApi().post()-- assert response["result"] == "success"- mock_verify.assert_not_called()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_email_send_ip_limit")- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @pytest.mark.parametrize(- ("service_error", "expected_error"),- [- (AccountRegisterError("Account frozen"), AccountInFreezeError),- (EmailDomainSuspendedRegistrationError(), EmailDomainSuspendedError),- ],- )- def test_send_email_code_frozen_account(- self,- mock_get_user,- mock_is_ip_limit,- mock_db,- app: Flask,- service_error,- expected_error,- ):- """- Test email code sending to frozen account.-- Verifies that:- - AccountInFreezeError is raised for frozen accounts- """- # Arrange- mock_is_ip_limit.return_value = False- mock_get_user.side_effect = service_error-- # Act & Assert- with app.test_request_context("/email-code-login", method="POST", json={"email": "[email protected]"}):- api = EmailCodeLoginSendEmailApi()- with pytest.raises(expected_error):- api.post()-- @pytest.mark.parametrize(- ("language_input", "expected_language"),- [- ("zh-Hans", "zh-Hans"),- ("en-US", "en-US"),- (None, "en-US"),- ],- )- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_email_send_ip_limit")- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.AccountService.send_email_code_login_email")- def test_send_email_code_language_handling(- self,- mock_send_email,- mock_get_user,- mock_is_ip_limit,- mock_db,- app: Flask,- mock_account,- language_input,- expected_language,- ):- """- Test email code sending with different language preferences.-- Verifies that:- - Language parameter is correctly processed- - Defaults to en-US when not specified- """- # Arrange- mock_is_ip_limit.return_value = False- mock_get_user.return_value = mock_account- mock_send_email.return_value = "token"-- # Act- with app.test_request_context(- "/email-code-login", method="POST", json={"email": "[email protected]", "language": language_input}- ):- api = EmailCodeLoginSendEmailApi()- api.post()-- # Assert- call_args = mock_send_email.call_args- assert call_args.kwargs["language"] == expected_language---class TestEmailCodeLoginApi:- """Test cases for email code verification and login."""-- @pytest.fixture- def app(self):- """Create Flask test application."""- app = Flask(__name__)- app.config["TESTING"] = True- return app-- @pytest.fixture- def mock_account(self) -> Account:- """Create a real transient account for login orchestration."""- return Account(name="Test User", email="[email protected]")-- @pytest.fixture- def mock_token_pair(self):- """Create mock token pair object."""- token_pair = MagicMock()- token_pair.access_token = "access_token"- token_pair.refresh_token = "refresh_token"- token_pair.csrf_token = "csrf_token"- return token_pair-- @pytest.mark.parametrize("code", ["12345", "1234567", "abcdef", "١٢٣٤٥٦"])- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- def test_rejects_malformed_code_after_wire_decode(- self,- mock_verify_challenge,- mock_db,- app: Flask,- code: str,- ):- with (- app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code(code), "token": TEST_TOKEN},- ),- pytest.raises(EmailCodeError),- ):- EmailCodeLoginApi().post()-- mock_verify_challenge.assert_not_called()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- @patch("controllers.console.auth.login.TurnstileService.verify")- def test_cloud_verify_uses_separate_turnstile_action_when_required(- self,- mock_turnstile_verify,- mock_verify_challenge,- mock_db,- app: Flask,- config_overrides: Callable[..., None],- ):- config_overrides(- DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,- TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED=True,- )- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.INVALID_TOKEN- )-- with (- app.test_request_context(- "/email-code-login/validity",- method="POST",- json={- "email": "[email protected]",- "code": encode_code("123456"),- "token": TEST_TOKEN,- "turnstile_token": "verify-challenge-token",- },- headers={"CF-Connecting-IP": "203.0.113.8"},- ),- pytest.raises(InvalidTokenError),- ):- EmailCodeLoginApi().post()-- mock_turnstile_verify.assert_called_once_with(- token="verify-challenge-token",- remote_ip="203.0.113.8",- expected_action="signin_code_verify",- )-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- @patch(- "controllers.console.auth.login.TurnstileService.verify",- side_effect=TurnstileChallengeRejectedError,- )- def test_cloud_verify_rejects_missing_turnstile_before_consuming_code(- self,- mock_turnstile_verify,- mock_verify_challenge,- mock_db,- app: Flask,- config_overrides: Callable[..., None],- ):- config_overrides(- DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,- TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED=True,- )- with (- app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ),- pytest.raises(TurnstileVerificationFailedError),- ):- EmailCodeLoginApi().post()-- mock_turnstile_verify.assert_called_once()- mock_verify_challenge.assert_not_called()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- @patch("controllers.console.auth.login.TurnstileService.verify")- def test_cloud_verify_flag_off_allows_legacy_client_without_turnstile(- self,- mock_turnstile_verify,- mock_verify_challenge,- mock_db,- app: Flask,- config_overrides: Callable[..., None],- ):- config_overrides(- DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,- TURNSTILE_EMAIL_CODE_VERIFY_REQUIRED=False,- )- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.INVALID_TOKEN- )-- with (- app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ),- pytest.raises(InvalidTokenError),- ):- EmailCodeLoginApi().post()-- mock_turnstile_verify.assert_not_called()- mock_verify_challenge.assert_called_once()-- @patch("controllers.console.wraps.db")- @patch(- "controllers.console.auth.login.AccountService.verify_email_code_login_challenge",- side_effect=EmailCodeLoginChallengeUnavailableError,- )- def test_verify_maps_redis_failure_to_service_unavailable(- self,- mock_verify_challenge,- mock_db,- app: Flask,- ):- with (- app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ),- pytest.raises(EmailCodeLoginServiceUnavailableError),- ):- EmailCodeLoginApi().post()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.AccountService.login")- @patch("controllers.console.auth.login.AccountService.reset_login_error_rate_limit")- def test_email_code_login_existing_user(- self,- mock_reset_rate_limit,- mock_login,- mock_get_tenants,- mock_get_user,- mock_verify_challenge,- mock_db,- app: Flask,- mock_account,- mock_token_pair,- ):- """- Test successful email code login for existing user.-- Verifies that:- - Email and code are validated- - Token is revoked after use- - User is logged in with token pair- """- # Arrange- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.VERIFIED- )- mock_get_user.return_value = mock_account- mock_get_tenants.return_value = [Tenant(name="Test Workspace")]- mock_login.return_value = mock_token_pair-- # Act- with app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ):- api = EmailCodeLoginApi()- response = api.post()-- # Assert- assert response.json["result"] == "success"- mock_verify_challenge.assert_called_once_with(email="[email protected]", code="123456", token=TEST_TOKEN)- mock_login.assert_called_once()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.AccountService.create_account_and_tenant")- @patch("controllers.console.auth.login.AccountService.login")- @patch("controllers.console.auth.login.AccountService.reset_login_error_rate_limit")- def test_email_code_login_new_user_creates_account(- self,- mock_reset_rate_limit,- mock_login,- mock_create_account,- mock_get_user,- mock_verify_challenge,- mock_db,- app: Flask,- mock_account,- mock_token_pair,- ):- """- Test email code login creates new account for new user.-- Verifies that:- - New account is created when user doesn't exist- - Workspace is created for new user- - User is logged in after account creation- """- # Arrange- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.VERIFIED- )- mock_get_user.return_value = None- mock_create_account.return_value = mock_account- mock_login.return_value = mock_token_pair-- # Act- with (- patch("controllers.console.auth.login.extract_remote_ip", return_value="203.0.113.10"),- app.test_request_context(- "/email-code-login/validity",- method="POST",- json={- "email": "[email protected]",- "code": encode_code("123456"),- "token": TEST_TOKEN,- "language": "en-US",- "timezone": "Asia/Shanghai",- },- ),- ):- api = EmailCodeLoginApi()- response = api.post()-- # Assert- assert response.json["result"] == "success"- mock_create_account.assert_called_once_with(- email="[email protected]",- name="[email protected]",- interface_language="en-US",- timezone="Asia/Shanghai",- ip_address="203.0.113.10",- check_normalized_email=True,- session=ANY,- )-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- def test_email_code_login_invalid_token(self, mock_verify_challenge, mock_db, app: Flask):- """- Test email code login with invalid token.-- Verifies that:- - InvalidTokenError is raised for invalid/expired tokens- """- # Arrange- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.INVALID_TOKEN- )-- # Act & Assert- with app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ):- api = EmailCodeLoginApi()- with pytest.raises(InvalidTokenError):- api.post()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- def test_email_code_login_email_mismatch(self, mock_verify_challenge, mock_db, app: Flask):- """- Test email code login with mismatched email.-- Verifies that:- - InvalidEmailError is raised when email doesn't match token- """- # Arrange- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.EMAIL_MISMATCH- )-- # Act & Assert- with app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ):- api = EmailCodeLoginApi()- with pytest.raises(InvalidEmailError):- api.post()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- def test_email_code_login_wrong_code(self, mock_verify_challenge, mock_db, app: Flask):- """- Test email code login with incorrect code.-- Verifies that:- - EmailCodeError is raised for wrong verification code- """- # Arrange- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.INVALID_CODE,- remaining_attempts=4,- )-- # Act & Assert- with app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("654321"), "token": TEST_TOKEN},- ):- api = EmailCodeLoginApi()- with pytest.raises(EmailCodeError):- api.post()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.SystemFeatureService.is_workspace_creation_allowed")- def test_email_code_login_creates_workspace_for_user_without_tenant(- self,- mock_is_workspace_creation_allowed,- mock_get_tenants,- mock_get_user,- mock_verify_challenge,- mock_db,- app: Flask,- mock_account,- ):- """- Test email code login creates workspace for user without tenant.-- Verifies that:- - Workspace is created when user has no tenants- - User is added as owner of new workspace- """- # Arrange- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.VERIFIED- )- mock_get_user.return_value = mock_account- mock_get_tenants.return_value = []- mock_is_workspace_creation_allowed.return_value = True-- # Act & Assert - Should not raise WorkspacesLimitExceeded- with app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ):- api = EmailCodeLoginApi()- # This would complete the flow, but we're testing workspace creation logic- # In real implementation, TenantService.create_tenant would be called-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.SystemFeatureService.get_license")- @patch("controllers.console.auth.login.SystemFeatureService.is_workspace_creation_allowed")- def test_email_code_login_workspace_limit_exceeded(- self,- mock_is_workspace_creation_allowed,- mock_get_license,- mock_get_tenants,- mock_get_user,- mock_verify_challenge,- mock_db,- app: Flask,- mock_account,- ):- """- Test email code login fails when workspace limit exceeded.-- Verifies that:- - WorkspacesLimitExceeded is raised when limit reached- """- # Arrange- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.VERIFIED- )- mock_get_user.return_value = mock_account- mock_get_tenants.return_value = []- mock_get_license.return_value.workspaces.is_available.return_value = False- mock_is_workspace_creation_allowed.return_value = True-- # Act & Assert- with app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ):- api = EmailCodeLoginApi()- with pytest.raises(WorkspacesLimitExceeded):- api.post()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- @patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.SystemFeatureService.is_workspace_creation_allowed")- def test_email_code_login_workspace_creation_not_allowed(- self,- mock_is_workspace_creation_allowed,- mock_get_tenants,- mock_get_user,- mock_verify_challenge,- mock_db,- app: Flask,- mock_account,- ):- """- Test email code login fails when workspace creation not allowed.-- Verifies that:- - NotAllowedCreateWorkspace is raised when creation disabled- """- # Arrange- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.VERIFIED- )- mock_get_user.return_value = mock_account- mock_get_tenants.return_value = []- mock_is_workspace_creation_allowed.return_value = False-- # Act & Assert- with app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ):- api = EmailCodeLoginApi()- with pytest.raises(NotAllowedCreateWorkspace):- api.post()diff --git a/api/tests/unit_tests/controllers/console/auth/test_login_logout.py b/api/tests/unit_tests/controllers/console/auth/test_login_logout.pyindex 61a78011987..7425178fd3f 100644--- a/api/tests/unit_tests/controllers/console/auth/test_login_logout.py+++ b/api/tests/unit_tests/controllers/console/auth/test_login_logout.py@@ -1,727 +1,386 @@-"""-Test suite for login and logout authentication flows.+"""Transport-boundary tests for Console authentication endpoints."""-This module tests the core authentication endpoints including:-- Email/password login with rate limiting-- Session management and logout-- Cookie-based token handling-- Account status validation-"""+from __future__ import annotationsimport base64-import loggingfrom collections.abc import Callable-from unittest.mock import ANY, MagicMock, Mock, patch+from dataclasses import dataclass, field+from types import SimpleNamespaceimport pytestfrom flask import Flask-from flask_restx import Api-from werkzeug.exceptions import Unauthorized+from controllers.console import wraps+from controllers.console.auth import loginfrom controllers.console.auth.error import (AuthenticationFailedError,+ EmailCodeError,+ EmailCodeLoginRateLimitExceededError,+ EmailCodeLoginServiceUnavailableError,EmailPasswordLoginLimitError,InvalidEmailError,+ InvalidTokenError,NormalizedEmailAlreadyInUseError,+ PasswordResetRateLimitExceededError,+ TurnstileServiceUnavailableError,+ TurnstileVerificationFailedError,)-from controllers.console.auth.login import EmailCodeLoginApi, LoginApi, LogoutApi, ResetPasswordSendEmailApifrom controllers.console.error import (AccountBannedError,AccountInFreezeError,+ AccountNotFound,EmailDomainSuspendedError,+ EmailSendIpLimitError,+ InvalidAccountPasswordRequestError,+ NotAllowedCreateWorkspace,SeatsLimitExceeded,WorkspacesLimitExceeded,)from enums import DeploymentEdition-from models.account import Account, Tenant-from services.email_code_login_challenge import EmailCodeLoginChallengeResult, EmailCodeLoginChallengeStatus-from services.entities.auth_entities import LoginFailureReason-from services.errors.account import (- AccountLoginError,- AccountNormalizedEmailAlreadyInUseError,- AccountPasswordError,- AccountRegisterError,- SeatsLimitExceededError,-)-from services.errors.account import (- EmailDomainSuspendedError as EmailDomainSuspendedRegistrationError,+from services import account_errors+from services.entities.account_login_entities import (+ AuthTokenPair,+ EmailCodeLoginCommand,+ EmailCodeSendCommand,+ PasswordLoginCommand,+ PasswordLoginResult,)TEST_TOKEN = "00000000-0000-4000-8000-000000000001"+TOKEN_PAIR = AuthTokenPair(access_token="access-token", refresh_token="refresh-token", csrf_token="csrf-token")+++@dataclass+class FakeAuthenticationService:+ error: account_errors.AccountApplicationError | None = None+ password_commands: list[PasswordLoginCommand] = field(default_factory=list)+ email_code_send_commands: list[EmailCodeSendCommand] = field(default_factory=list)+ email_code_login_commands: list[EmailCodeLoginCommand] = field(default_factory=list)+ reset_arguments: list[tuple[str, str | None, str]] = field(default_factory=list)+ logout_account_ids: list[str] = field(default_factory=list)+ refresh_tokens: list[str] = field(default_factory=list)+ workspace_found: bool = True++ def _raise_if_needed(self) -> None:+ if self.error is not None:+ raise self.error++ def login_with_password(self, command: PasswordLoginCommand) -> PasswordLoginResult:+ self.password_commands.append(command)+ self._raise_if_needed()+ return PasswordLoginResult(+ token_pair=TOKEN_PAIR if self.workspace_found else None,+ workspace_found=self.workspace_found,+ )+ def logout(self, account_id: str) -> None:+ self.logout_account_ids.append(account_id)[email protected](autouse=True)-def _login_config(config_overrides: Callable[..., None]) -> None:- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)+ def send_reset_password_email(self, *, email: str, language: str | None, ip_address: str) -> str:+ self.reset_arguments.append((email, language, ip_address))+ self._raise_if_needed()+ return "reset-token"+ def send_email_code(self, command: EmailCodeSendCommand) -> str:+ self.email_code_send_commands.append(command)+ self._raise_if_needed()+ return "email-code-token"-def encode_password(password: str) -> str:- """Helper to encode password as Base64 for testing."""- return base64.b64encode(password.encode("utf-8")).decode()---def encode_code(code: str) -> str:- """Helper to encode verification code as Base64 for testing."""- return base64.b64encode(code.encode("utf-8")).decode()---from inspect import unwrap---class TestLoginApi:- """Test cases for the LoginApi endpoint."""-- @pytest.fixture- def app(self):- """Create Flask test application."""- app = Flask(__name__)- app.config["TESTING"] = True- return app-- @pytest.fixture- def api(self, app: Flask):- """Create Flask-RESTX API instance."""- return Api(app)-- @pytest.fixture- def client(self, app: Flask, api: Api):- """Create test client."""- api.add_resource(LoginApi, "/login")- return app.test_client()-- @pytest.fixture- def mock_account(self) -> Account:- """Create a real transient account for the service boundary."""- account = Account(name="Test User", email="[email protected]")- account.id = "test-account-id"- return account-- @pytest.fixture- def mock_token_pair(self):- """Create mock token pair object."""- token_pair = MagicMock()- token_pair.access_token = "mock_access_token"- token_pair.refresh_token = "mock_refresh_token"- token_pair.csrf_token = "mock_csrf_token"- return token_pair-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")- @patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")- @patch("controllers.console.auth.login.AccountService.authenticate")- @patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.AccountService.login")- @patch("controllers.console.auth.login.AccountService.reset_login_error_rate_limit")- def test_successful_login_without_invitation(- self,- mock_reset_rate_limit,- mock_login,- mock_get_tenants,- mock_authenticate,- mock_get_invitation,- mock_is_rate_limit,- mock_db,- app: Flask,- mock_account,- mock_token_pair,- ):- """- Test successful login flow without invitation token.-- Verifies that:- - Valid credentials authenticate successfully- - Tokens are generated and set in cookies- - Rate limit is reset after successful login- """- # Arrange- mock_is_rate_limit.return_value = False- mock_get_invitation.return_value = None- mock_authenticate.return_value = mock_account- mock_get_tenants.return_value = [Tenant(name="Test Workspace")]- mock_login.return_value = mock_token_pair-- # Act- with app.test_request_context(- "/login",- method="POST",- json={"email": "[email protected]", "password": encode_password("ValidPass123!")},- ):- login_api = LoginApi()- response = login_api.post()-- # Assert- mock_authenticate.assert_called_once_with("[email protected]", "ValidPass123!", None, session=ANY)- mock_login.assert_called_once()- mock_reset_rate_limit.assert_called_once_with("[email protected]")- assert response.json["result"] == "success"-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")- @patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")- @patch("controllers.console.auth.login.AccountService.authenticate")- @patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.AccountService.login")- @patch("controllers.console.auth.login.AccountService.reset_login_error_rate_limit")- def test_successful_login_with_valid_invitation(- self,- mock_reset_rate_limit: Mock,- mock_login,- mock_get_tenants,- mock_authenticate,- mock_get_invitation,- mock_is_rate_limit,- mock_db,- app: Flask,- mock_account,- mock_token_pair,- ):- """- Test successful login with valid invitation token.-- Verifies that:- - Invitation token is validated- - Email matches invitation email- - Authentication proceeds with invitation token- """- # Arrange- mock_is_rate_limit.return_value = False- mock_get_invitation.return_value = {"data": {"email": "[email protected]"}}- mock_authenticate.return_value = mock_account- mock_get_tenants.return_value = [Tenant(name="Test Workspace")]- mock_login.return_value = mock_token_pair-- # Act- with app.test_request_context(- "/login",- method="POST",- json={- "email": "[email protected]",- "password": encode_password("ValidPass123!"),- "invite_token": "valid_token",- },- ):- login_api = LoginApi()- response = login_api.post()-- # Assert- mock_authenticate.assert_called_once_with("[email protected]", "ValidPass123!", "valid_token", session=ANY)- assert response.json["result"] == "success"-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")- @patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")- def test_login_fails_when_rate_limited(- self, mock_get_invitation, mock_is_rate_limit, mock_db, app: Flask, caplog: pytest.LogCaptureFixture- ):- """- Test login rejection when rate limit is exceeded.-- Verifies that:- - Rate limit check is performed before authentication- - EmailPasswordLoginLimitError is raised when limit exceeded- """- # Arrange- mock_is_rate_limit.return_value = True- mock_get_invitation.return_value = None-- # Act & Assert- with app.test_request_context(- "/login", method="POST", json={"email": "[email protected]", "password": encode_password("password")}- ):- login_api = LoginApi()- with pytest.raises(EmailPasswordLoginLimitError):- login_api.post()-- warn_records = [- r for r in caplog.records if r.name == "controllers.console.auth.login" and r.levelno == logging.WARNING- ]- assert len(warn_records) == 1- assert warn_records[0].args[0] == "[email protected]"- assert warn_records[0].args[1] == LoginFailureReason.LOGIN_RATE_LIMITED-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.BillingService.get_email_freeze_type")- def test_login_fails_when_account_frozen(- self,- mock_get_freeze_type,- mock_db,- app: Flask,- caplog: pytest.LogCaptureFixture,- config_overrides: Callable[..., None],- ):- """- Test login rejection for frozen accounts.-- Verifies that:- - Billing freeze status is checked when billing enabled- - AccountInFreezeError is raised for frozen accounts- """- # Arrange- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)- mock_get_freeze_type.return_value = "freeze"-- # Act & Assert- with app.test_request_context(- "/login", method="POST", json={"email": "[email protected]", "password": encode_password("password")}- ):- login_api = LoginApi()- with pytest.raises(AccountInFreezeError):- login_api.post()-- warn_records = [- r for r in caplog.records if r.name == "controllers.console.auth.login" and r.levelno == logging.WARNING- ]- assert len(warn_records) == 1- assert warn_records[0].args[0] == "[email protected]"- assert warn_records[0].args[1] == LoginFailureReason.ACCOUNT_IN_FREEZE-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.BillingService.get_email_freeze_type")- def test_login_fails_when_email_domain_is_suspended(- self,- mock_get_freeze_type,- mock_db,- app: Flask,- config_overrides: Callable[..., None],- ):- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)- mock_get_freeze_type.return_value = "email_domain_suspended"-- with app.test_request_context(- "/login",- method="POST",- json={"email": "[email protected]", "password": encode_password("password")},- ):- with pytest.raises(EmailDomainSuspendedError):- LoginApi().post()-- @pytest.mark.parametrize(- ("service_error", "expected_error"),- [- (EmailDomainSuspendedRegistrationError(), EmailDomainSuspendedError),- (AccountRegisterError("frozen"), AccountInFreezeError),- ],- )- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login._get_account_with_case_fallback")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- def test_email_code_login_translates_freeze_errors(- self,- mock_verify_challenge,- mock_get_account,- mock_db,- app: Flask,- service_error,- expected_error,- ):- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.VERIFIED- )- mock_get_account.side_effect = service_error-- with app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ):- with pytest.raises(expected_error):- EmailCodeLoginApi().post()-- @pytest.mark.parametrize(- ("service_error", "expected_error"),- [- (EmailDomainSuspendedRegistrationError(), EmailDomainSuspendedError),- (AccountNormalizedEmailAlreadyInUseError(), NormalizedEmailAlreadyInUseError),- (AccountRegisterError("frozen"), AccountInFreezeError),- ],- )- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.db")- @patch("controllers.console.auth.login.AccountService.create_account_and_tenant")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- @patch("controllers.console.auth.login._get_account_with_case_fallback")- def test_email_code_login_translates_account_creation_freeze_errors(- self,- mock_get_account,- mock_verify_challenge,- mock_create_account,- mock_login_db,- mock_db,- app: Flask,- service_error,- expected_error,+ def login_with_email_code(self, command: EmailCodeLoginCommand) -> AuthTokenPair:+ self.email_code_login_commands.append(command)+ self._raise_if_needed()+ return TOKEN_PAIR++ def refresh(self, refresh_token: str) -> AuthTokenPair:+ self.refresh_tokens.append(refresh_token)+ self._raise_if_needed()+ return TOKEN_PAIR++[email protected](autouse=True)+def admit_authentication_requests(+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)+ monkeypatch.setattr(wraps.SystemFeatureService, "is_email_password_login_enabled", lambda: True)+++def service(monkeypatch: pytest.MonkeyPatch) -> FakeAuthenticationService:+ service = FakeAuthenticationService()+ services = SimpleNamespace(accounts=SimpleNamespace(authentication=service))+ monkeypatch.setattr(login, "application_services", lambda: services)+ monkeypatch.setattr(login, "extract_remote_ip", lambda _request: "127.0.0.1")+ return service+++def _encode(value: str) -> str:+ return base64.b64encode(value.encode()).decode()+++def test_password_login_parses_input_and_serializes_cookies(+ app: Flask,+ service: FakeAuthenticationService,+) -> None:+ with app.test_request_context(+ "/login",+ method="POST",+ json={+ "email": "[email protected]",+ "password": _encode("password"),+ "invite_token": "invite-token",+ },):- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.VERIFIED+ response = login.LoginApi().post()++ assert response.json == {"result": "success", "data": None}+ assert service.password_commands == [+ PasswordLoginCommand(+ email="[email protected]",+ password="password",+ invite_token="invite-token",+ ip_address="127.0.0.1",)- mock_get_account.return_value = None- mock_create_account.side_effect = service_error-- with app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ):- with pytest.raises(expected_error):- EmailCodeLoginApi().post()-- @pytest.mark.parametrize(- ("service_error", "expected_error"),- [- (EmailDomainSuspendedRegistrationError(), EmailDomainSuspendedError),- (AccountRegisterError("frozen"), AccountInFreezeError),- ],- )- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login._get_account_with_case_fallback")- def test_reset_password_translates_freeze_errors(- self,- mock_get_account,- mock_db,- app: Flask,- service_error,- expected_error,+ ]+ cookies = response.headers.getlist("Set-Cookie")+ assert any("access_token=" in cookie for cookie in cookies)+ assert any("refresh_token=" in cookie for cookie in cookies)+ assert any("csrf_token=" in cookie for cookie in cookies)+++def test_password_login_serializes_missing_workspace(+ app: Flask,+ service: FakeAuthenticationService,+) -> None:+ service.workspace_found = False+ with app.test_request_context(+ "/login",+ method="POST",+ json={"email": "[email protected]", "password": _encode("password")},):- mock_get_account.side_effect = service_error-- with app.test_request_context(- "/reset-password",- method="POST",- json={"email": "[email protected]"},- ):- with pytest.raises(expected_error):- ResetPasswordSendEmailApi().post()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")- @patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")- @patch("controllers.console.auth.login.AccountService.authenticate")- @patch("controllers.console.auth.login.AccountService.add_login_error_rate_limit")- def test_login_fails_with_invalid_credentials(- self,- mock_add_rate_limit,- mock_authenticate,- mock_get_invitation,- mock_is_rate_limit,- mock_db,- app: Flask,- caplog: pytest.LogCaptureFixture,- ):- """- Test login failure with invalid credentials.-- Verifies that:- - AuthenticationFailedError is raised for wrong password- - Login error rate limit counter is incremented- - Generic error message prevents user enumeration- """- # Arrange- mock_is_rate_limit.return_value = False- mock_get_invitation.return_value = None- mock_authenticate.side_effect = AccountPasswordError("Invalid password")-- # Act & Assert- with app.test_request_context(- "/login",- method="POST",- json={"email": "[email protected]", "password": encode_password("WrongPass123!")},- ):- login_api = LoginApi()- with pytest.raises(AuthenticationFailedError):- login_api.post()-- mock_add_rate_limit.assert_called_once_with("[email protected]")- warn_records = [- r for r in caplog.records if r.name == "controllers.console.auth.login" and r.levelno == logging.WARNING- ]- assert len(warn_records) == 1- assert warn_records[0].args[0] == "[email protected]"- assert warn_records[0].args[1] == LoginFailureReason.INVALID_CREDENTIALS-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")- @patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")- @patch("controllers.console.auth.login.AccountService.authenticate")- def test_login_fails_for_banned_account(- self, mock_authenticate, mock_get_invitation, mock_is_rate_limit, mock_db, app: Flask, caplog+ response = login.LoginApi().post()++ assert response["result"] == "fail"+ assert "workspace not found" in response["data"]+++def test_invitation_login_with_empty_password_returns_authentication_failure(+ app: Flask,+ service: FakeAuthenticationService,+) -> None:+ service.error = account_errors.InvalidLoginCredentialsError()+ with app.test_request_context(+ "/login",+ method="POST",+ json={"email": "[email protected]", "password": _encode(""), "invite_token": "invite-token"},):- """- Test login rejection for banned accounts.-- Verifies that:- - AccountBannedError is raised for banned accounts- - Login is prevented even with valid credentials- """- # Arrange- mock_is_rate_limit.return_value = False- mock_get_invitation.return_value = None- mock_authenticate.side_effect = AccountLoginError("Account is banned")-- # Act & Assert- with app.test_request_context(- "/login",- method="POST",- json={"email": "[email protected]", "password": encode_password("ValidPass123!")},- ):- login_api = LoginApi()- with pytest.raises(AccountBannedError):- login_api.post()-- warn_records = [- r for r in caplog.records if r.name == "controllers.console.auth.login" and r.levelno == logging.WARNING- ]- assert len(warn_records) == 1- assert warn_records[0].args[0] == "[email protected]"- assert warn_records[0].args[1] == LoginFailureReason.ACCOUNT_BANNED-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")- @patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")- @patch("controllers.console.auth.login.AccountService.authenticate")- @patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.SystemFeatureService.get_license")- @patch("controllers.console.auth.login.SystemFeatureService.is_workspace_creation_allowed")- def test_login_fails_when_no_workspace_and_limit_exceeded(- self,- mock_is_workspace_creation_allowed: MagicMock,- mock_get_license: MagicMock,- mock_get_tenants: MagicMock,- mock_authenticate: MagicMock,- mock_get_invitation: MagicMock,- mock_is_rate_limit: MagicMock,- mock_db: MagicMock,- app: Flask,- mock_account: MagicMock,+ with pytest.raises(AuthenticationFailedError):+ login.LoginApi().post()++ assert service.password_commands == [+ PasswordLoginCommand(+ email="[email protected]",+ password="",+ invite_token="invite-token",+ ip_address="127.0.0.1",+ )+ ]+++def test_invitation_login_with_weak_password_returns_policy_failure(+ app: Flask,+ service: FakeAuthenticationService,+) -> None:+ service.error = account_errors.InvalidAccountPasswordError("Password must contain letters and numbers")+ with app.test_request_context(+ "/login",+ method="POST",+ json={"email": "[email protected]", "password": _encode("letters-only"), "invite_token": "invite-token"},):- """- Test login failure when user has no workspace and workspace limit exceeded.-- Verifies that:- - WorkspacesLimitExceeded is raised when limit reached- - User cannot login without an assigned workspace- """- # Arrange- mock_is_rate_limit.return_value = False- mock_get_invitation.return_value = None- mock_authenticate.return_value = mock_account- mock_get_tenants.return_value = [] # No tenants-- mock_is_workspace_creation_allowed.return_value = True- mock_get_license.return_value.workspaces.is_available.return_value = False-- # Act & Assert- with app.test_request_context(- "/login", method="POST", json={"email": "[email protected]", "password": encode_password("ValidPass123!")}- ):- login_api = LoginApi()- with pytest.raises(WorkspacesLimitExceeded):- login_api.post()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")- @patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")- def test_login_invitation_email_mismatch(self, mock_get_invitation, mock_is_rate_limit, mock_db, app: Flask):- """- Test login failure when invitation email doesn't match login email.-- Verifies that:- - InvalidEmailError is raised for email mismatch- - Security check prevents invitation token abuse- """- # Arrange- mock_is_rate_limit.return_value = False- mock_get_invitation.return_value = {"data": {"email": "[email protected]"}}-- # Act & Assert- with app.test_request_context(- "/login",- method="POST",- json={- "email": "[email protected]",- "password": encode_password("ValidPass123!"),- "invite_token": "token",- },- ):- login_api = LoginApi()- with pytest.raises(InvalidEmailError):- login_api.post()-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")- @patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")- @patch("controllers.console.auth.login.AccountService.authenticate")- @patch("controllers.console.auth.login.AccountService.add_login_error_rate_limit")- @patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.AccountService.login")- @patch("controllers.console.auth.login.AccountService.reset_login_error_rate_limit")- def test_login_retries_with_lowercase_email(- self,- mock_reset_rate_limit: MagicMock,- mock_login_service: MagicMock,- mock_get_tenants: MagicMock,- mock_add_rate_limit: MagicMock,- mock_authenticate: MagicMock,- mock_get_invitation: MagicMock,- mock_is_rate_limit: MagicMock,- mock_db,- app: Flask,- mock_account,- mock_token_pair,+ with pytest.raises(InvalidAccountPasswordRequestError, match="letters and numbers"):+ login.LoginApi().post()+++def test_reset_password_delegates_transport_values(app: Flask, service: FakeAuthenticationService) -> None:+ with app.test_request_context(+ "/reset-password",+ method="POST",+ json={"email": "[email protected]", "language": "zh-Hans"},):- """Test that login retries with lowercase email when uppercase lookup fails."""- mock_is_rate_limit.return_value = False- mock_get_invitation.return_value = None- mock_authenticate.side_effect = [AccountPasswordError("Invalid"), mock_account]- mock_get_tenants.return_value = [Tenant(name="Test Workspace")]- mock_login_service.return_value = mock_token_pair-- with app.test_request_context(- "/login",- method="POST",- json={"email": "[email protected]", "password": encode_password("ValidPass123!")},- ):- response = LoginApi().post()-- assert response.json["result"] == "success"- assert mock_authenticate.call_args_list == [- (("[email protected]", "ValidPass123!", None), {"session": ANY}),- (("[email protected]", "ValidPass123!", None), {"session": ANY}),- ]- mock_add_rate_limit.assert_not_called()- mock_reset_rate_limit.assert_called_once_with("[email protected]")-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- @patch("controllers.console.auth.login._get_account_with_case_fallback")- def test_email_code_login_logs_banned_account(- self,- mock_get_account: MagicMock,- mock_verify_challenge: MagicMock,- mock_db: MagicMock,- app: Flask,- caplog: pytest.LogCaptureFixture,+ response = login.ResetPasswordSendEmailApi().post()++ assert response == {"result": "success", "data": "reset-token"}+ assert service.reset_arguments == [("[email protected]", "zh-Hans", "127.0.0.1")]+++def test_email_code_send_delegates_validated_command(app: Flask, service: FakeAuthenticationService) -> None:+ with app.test_request_context(+ "/email-code-login",+ method="POST",+ json={"email": "[email protected]", "turnstile_token": "challenge"},):- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.VERIFIED+ response = login.EmailCodeLoginSendEmailApi().post()++ assert response == {"result": "success", "data": "email-code-token"}+ assert service.email_code_send_commands == [+ EmailCodeSendCommand(+ email="[email protected]",+ language=None,+ turnstile_token="challenge",+ ip_address="127.0.0.1",)- mock_get_account.side_effect = Unauthorized("Account is banned.")-- with app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ):- with pytest.raises(AccountBannedError):- EmailCodeLoginApi().post()-- warn_records = [- r for r in caplog.records if r.name == "controllers.console.auth.login" and r.levelno == logging.WARNING- ]- assert len(warn_records) == 1- assert warn_records[0].args[0] == "[email protected]"- assert warn_records[0].args[1] == LoginFailureReason.ACCOUNT_BANNED-- @patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.db")- @patch("controllers.console.auth.login.AccountService.create_account_and_tenant")- @patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")- @patch("controllers.console.auth.login._get_account_with_case_fallback")- def test_email_code_login_fails_when_seats_limit_exceeded(- self,- mock_get_account: MagicMock,- mock_verify_challenge: MagicMock,- mock_create_account: MagicMock,- mock_login_db: MagicMock,- mock_db: MagicMock,- app: Flask,+ ]+++def test_email_code_login_decodes_code_and_serializes_tokens(+ app: Flask,+ service: FakeAuthenticationService,+) -> None:+ with app.test_request_context(+ "/email-code-login/validity",+ method="POST",+ json={+ "email": "[email protected]",+ "code": _encode("123456"),+ "token": TEST_TOKEN,+ "timezone": "Asia/Singapore",+ },):- """- Test email-code login failure when creating the account would exceed the licensed seats.-- Verifies that:- - the new-account path is taken when no account exists for the email- - the service-layer SeatsLimitExceededError is translated to the SeatsLimitExceeded HTTP error- """- # Arrange: valid token, no existing account -> account-creation path- mock_verify_challenge.return_value = EmailCodeLoginChallengeResult(- status=EmailCodeLoginChallengeStatus.VERIFIED+ response = login.EmailCodeLoginApi().post()++ assert response.json == {"result": "success"}+ assert service.email_code_login_commands == [+ EmailCodeLoginCommand(+ email="[email protected]",+ code="123456",+ token=TEST_TOKEN,+ turnstile_token=None,+ language=None,+ timezone="Asia/Singapore",+ ip_address="127.0.0.1",)- mock_get_account.return_value = None- mock_create_account.side_effect = SeatsLimitExceededError("licensed seats limit exceeded")-- # Act & Assert- with app.test_request_context(- "/email-code-login/validity",- method="POST",- json={"email": "[email protected]", "code": encode_code("123456"), "token": TEST_TOKEN},- ):- with pytest.raises(SeatsLimitExceeded):- EmailCodeLoginApi().post()-- mock_create_account.assert_called_once()---class TestLogoutApi:- """Test cases for the LogoutApi endpoint."""-- @pytest.fixture- def app(self):- """Create Flask test application."""- app = Flask(__name__)- app.config["TESTING"] = True- return app-- @pytest.fixture- def mock_account(self) -> Account:- """Create a real transient account for the logout service boundary."""- account = Account(name="Test User", email="[email protected]")- account.id = "test-account-id"- return account-- @patch("controllers.console.auth.login.AccountService.logout")- @patch("controllers.console.auth.login.flask_login.logout_user")- def test_successful_logout(- self, mock_logout_user: MagicMock, mock_service_logout: MagicMock, app: Flask, mock_account- ):- """- Test successful logout flow.-- Verifies that:- - User session is terminated- - AccountService.logout is called- - All authentication cookies are cleared- - Success response is returned- """- # Act- with app.test_request_context("/logout", method="POST"):- logout_api = LogoutApi()- response = unwrap(logout_api.post)(logout_api, mock_account)-- # Assert- mock_service_logout.assert_called_once_with(account=mock_account)- mock_logout_user.assert_called_once()- assert response.json["result"] == "success"-- @patch("controllers.console.auth.login.flask_login")- def test_logout_anonymous_user(self, mock_flask_login, app: Flask):- """- Test logout for anonymous (not logged in) user.-- Verifies that:- - Anonymous users can call logout endpoint- - No errors are raised- - Success response is returned- """- # Arrange- # Create a mock anonymous user that will pass isinstance check- anonymous_user = MagicMock()- mock_flask_login.AnonymousUserMixin = type("AnonymousUserMixin", (), {})- anonymous_user.__class__ = mock_flask_login.AnonymousUserMixin-- # Act- with app.test_request_context("/logout", method="POST"):- logout_api = LogoutApi()- response = unwrap(logout_api.post)(logout_api, anonymous_user)-- # Assert- assert response.json["result"] == "success"+ ]+++def test_logout_uses_optional_current_account(+ app: Flask,+ service: FakeAuthenticationService,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ logout_calls: list[bool] = []+ monkeypatch.setattr(login.flask_login, "logout_user", lambda: logout_calls.append(True))+ monkeypatch.setattr(+ login,+ "current_account_with_tenant_optional",+ lambda: (SimpleNamespace(id="account-1"), "workspace-1"),+ )++ with app.test_request_context("/logout", method="POST"):+ response = login.LogoutApi().post()++ assert response.json == {"result": "success"}+ assert service.logout_account_ids == ["account-1"]+ assert logout_calls == [True]+++def test_logout_clears_cookies_without_current_account(+ app: Flask,+ service: FakeAuthenticationService,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ logout_calls: list[bool] = []+ monkeypatch.setattr(login.flask_login, "logout_user", lambda: logout_calls.append(True))+ monkeypatch.setattr(login, "current_account_with_tenant_optional", lambda: (None, None))++ with app.test_request_context("/logout", method="POST"):+ response = login.LogoutApi().post()++ assert response.json == {"result": "success"}+ assert service.logout_account_ids == []+ assert logout_calls == []+ cookies = response.headers.getlist("Set-Cookie")+ assert any("access_token=" in cookie for cookie in cookies)+ assert any("refresh_token=" in cookie for cookie in cookies)+ assert any("csrf_token=" in cookie for cookie in cookies)+++def test_refresh_maps_invalid_session_to_unauthorized(+ app: Flask,+ service: FakeAuthenticationService,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ service.error = account_errors.InvalidRefreshTokenError("Invalid refresh token")+ monkeypatch.setattr(login, "extract_refresh_token", lambda _request: "bad-token")++ with app.test_request_context("/refresh-token", method="POST"):+ response, status = login.RefreshTokenApi().post()++ assert status == 401+ assert response == {"result": "fail", "message": "Invalid refresh token"}+++def test_refresh_rejects_missing_cookie(+ app: Flask,+ service: FakeAuthenticationService,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(login, "extract_refresh_token", lambda _request: None)++ with app.test_request_context("/refresh-token", method="POST"):+ response, status = login.RefreshTokenApi().post()++ assert status == 401+ assert response["message"] == "No refresh token provided"+ assert service.refresh_tokens == []+++def test_refresh_does_not_require_completed_setup(+ app: Flask,+ service: FakeAuthenticationService,+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)+ monkeypatch.setattr(wraps, "_is_setup_completed", lambda: False)+ monkeypatch.setattr(login, "extract_refresh_token", lambda _request: "old-refresh")++ with app.test_request_context("/refresh-token", method="POST"):+ response = login.RefreshTokenApi().post()++ assert response.json == {"result": "success"}+ assert service.refresh_tokens == ["old-refresh"]+++ ("application_error", "request_error"),+ [+ (account_errors.AccountEmailDomainSuspendedError(), EmailDomainSuspendedError),+ (account_errors.AccountEmailFrozenError(), AccountInFreezeError),+ (account_errors.LoginRateLimitError(), EmailPasswordLoginLimitError),+ (account_errors.InvalidLoginCredentialsError(), AuthenticationFailedError),+ (account_errors.InvalidAccountPasswordError("invalid password"), InvalidAccountPasswordRequestError),+ (account_errors.LoginAccountBannedError(), AccountBannedError),+ (account_errors.InvalidLoginInvitationEmailError(), InvalidEmailError),+ (account_errors.LoginWorkspaceLimitError(), WorkspacesLimitExceeded),+ (account_errors.LoginWorkspaceCreationNotAllowedError(), NotAllowedCreateWorkspace),+ (account_errors.LoginSeatLimitError(), SeatsLimitExceeded),+ (account_errors.AccountNormalizedEmailAlreadyInUseError(), NormalizedEmailAlreadyInUseError),+ (account_errors.EmailCodeSendIPLimitedError(), EmailSendIpLimitError),+ (account_errors.EmailCodeSendRateLimitError(5), EmailCodeLoginRateLimitExceededError),+ (account_errors.HumanVerificationRejectedError(), TurnstileVerificationFailedError),+ (account_errors.HumanVerificationUnavailableError(), TurnstileServiceUnavailableError),+ (account_errors.EmailCodeLoginUnavailableError(), EmailCodeLoginServiceUnavailableError),+ (account_errors.InvalidEmailCodeTokenError(), InvalidTokenError),+ (account_errors.EmailCodeEmailMismatchError(), InvalidEmailError),+ (account_errors.InvalidEmailCodeError(), EmailCodeError),+ (account_errors.AccountNotFoundError(), AccountNotFound),+ (account_errors.ResetPasswordEmailRateLimitError(1), PasswordResetRateLimitExceededError),+ ],+)+def test_maps_application_errors_to_transport_errors(+ application_error: account_errors.AccountApplicationError,+ request_error: type[Exception],+) -> None:+ with pytest.raises(request_error):+ login._raise_request_error(application_error)diff --git a/api/tests/unit_tests/controllers/console/auth/test_token_refresh.py b/api/tests/unit_tests/controllers/console/auth/test_token_refresh.pydeleted file mode 100644index 8effbb96887..00000000000--- a/api/tests/unit_tests/controllers/console/auth/test_token_refresh.py+++ /dev/null@@ -1,264 +0,0 @@-"""-Test suite for token refresh authentication flows.--This module tests the token refresh mechanism including:-- Access token refresh using refresh token-- Cookie-based token extraction and renewal-- Token expiration and validation-- Error handling for invalid tokens-"""--from unittest.mock import ANY, MagicMock, patch--import pytest-from flask import Flask-from flask_restx import Api-from werkzeug.exceptions import Unauthorized--from controllers.console.auth.login import RefreshTokenApi-from services.errors.account import RefreshTokenAccountNotFoundError, RefreshTokenNotFoundError---class TestRefreshTokenApi:- """Test cases for the RefreshTokenApi endpoint."""-- @pytest.fixture- def app(self):- """Create Flask test application."""- app = Flask(__name__)- app.config["TESTING"] = True- return app-- @pytest.fixture- def api(self, app: Flask):- """Create Flask-RESTX API instance."""- return Api(app)-- @pytest.fixture- def client(self, app: Flask, api: Api):- """Create test client."""- api.add_resource(RefreshTokenApi, "/refresh-token")- return app.test_client()-- @pytest.fixture- def mock_token_pair(self):- """Create mock token pair object."""- token_pair = MagicMock()- token_pair.access_token = "new_access_token"- token_pair.refresh_token = "new_refresh_token"- token_pair.csrf_token = "new_csrf_token"- return token_pair-- @patch("controllers.console.auth.login.extract_refresh_token", autospec=True)- @patch("controllers.console.auth.login.AccountService.refresh_token", autospec=True)- def test_successful_token_refresh(self, mock_refresh_token, mock_extract_token, app: Flask, mock_token_pair):- """- Test successful token refresh flow.-- Verifies that:- - Refresh token is extracted from cookies- - New token pair is generated- - New tokens are set in response cookies- - Success response is returned- """- # Arrange- mock_extract_token.return_value = "valid_refresh_token"- mock_refresh_token.return_value = mock_token_pair-- # Act- with app.test_request_context("/refresh-token", method="POST"):- refresh_api = RefreshTokenApi()- response = refresh_api.post()-- # Assert- mock_extract_token.assert_called_once()- mock_refresh_token.assert_called_once_with("valid_refresh_token", session=ANY)- assert response.json["result"] == "success"-- @patch("controllers.console.auth.login.extract_refresh_token", autospec=True)- def test_refresh_fails_without_token(self, mock_extract_token, app: Flask):- """- Test token refresh failure when no refresh token provided.-- Verifies that:- - Error is returned when refresh token is missing- - 401 status code is returned- - Appropriate error message is provided- """- # Arrange- mock_extract_token.return_value = None-- # Act- with app.test_request_context("/refresh-token", method="POST"):- refresh_api = RefreshTokenApi()- response, status_code = refresh_api.post()-- # Assert- assert status_code == 401- assert response["result"] == "fail"- assert "No refresh token provided" in response["message"]-- @patch("controllers.console.auth.login.extract_refresh_token", autospec=True)- @patch("controllers.console.auth.login.AccountService.refresh_token", autospec=True)- def test_refresh_returns_unauthorized_for_invalid_refresh_token(- self, mock_refresh_token, mock_extract_token, app: Flask- ):- """- Test token refresh maps invalid refresh tokens to unauthorized responses.-- Verifies that:- - Invalid refresh token validation failures return 401- - The failure response preserves the validation message- """- # Arrange- mock_extract_token.return_value = "invalid_refresh_token"- mock_refresh_token.side_effect = RefreshTokenNotFoundError("Invalid refresh token")-- # Act- with app.test_request_context("/refresh-token", method="POST"):- refresh_api = RefreshTokenApi()- response, status_code = refresh_api.post()-- # Assert- assert status_code == 401- assert response["result"] == "fail"- assert response["message"] == "Invalid refresh token"-- @patch("controllers.console.auth.login.extract_refresh_token", autospec=True)- @patch("controllers.console.auth.login.AccountService.refresh_token", autospec=True)- def test_refresh_returns_unauthorized_for_invalid_account(self, mock_refresh_token, mock_extract_token, app: Flask):- """- Test token refresh maps missing accounts to unauthorized responses.-- Verifies that:- - Invalid account validation failures return 401- - The failure response preserves the validation message- """- # Arrange- mock_extract_token.return_value = "refresh_token_for_missing_account"- mock_refresh_token.side_effect = RefreshTokenAccountNotFoundError("Invalid account")-- # Act- with app.test_request_context("/refresh-token", method="POST"):- refresh_api = RefreshTokenApi()- response, status_code = refresh_api.post()-- # Assert- assert status_code == 401- assert response["result"] == "fail"- assert response["message"] == "Invalid account"-- @patch("controllers.console.auth.login.extract_refresh_token", autospec=True)- @patch("controllers.console.auth.login.AccountService.refresh_token", autospec=True)- def test_refresh_returns_unauthorized_for_banned_account(self, mock_refresh_token, mock_extract_token, app: Flask):- """- Test token refresh maps banned accounts to unauthorized responses.-- Verifies that:- - Authorization failures raised during account loading return 401- - The failure response preserves the authorization message- """- # Arrange- mock_extract_token.return_value = "refresh_token_for_banned_account"- mock_refresh_token.side_effect = Unauthorized("Account is banned.")-- # Act- with app.test_request_context("/refresh-token", method="POST"):- refresh_api = RefreshTokenApi()- response, status_code = refresh_api.post()-- # Assert- assert status_code == 401- assert response["result"] == "fail"- assert response["message"] == "Account is banned."-- @patch("controllers.console.auth.login.extract_refresh_token", autospec=True)- @patch("controllers.console.auth.login.AccountService.refresh_token", autospec=True)- def test_refresh_propagates_non_whitelisted_value_error(self, mock_refresh_token, mock_extract_token, app: Flask):- """- Test token refresh preserves non-whitelisted ValueError failures.-- Verifies that:- - Only known refresh-token validation errors are mapped to 401- - Unexpected ValueError instances continue to propagate- """- # Arrange- mock_extract_token.return_value = "valid_refresh_token"- mock_refresh_token.side_effect = ValueError("unexpected parse failure")-- # Act & Assert- with app.test_request_context("/refresh-token", method="POST"):- refresh_api = RefreshTokenApi()- with pytest.raises(ValueError, match="unexpected parse failure"):- refresh_api.post()-- @patch("controllers.console.auth.login.extract_refresh_token", autospec=True)- @patch("controllers.console.auth.login.AccountService.refresh_token", autospec=True)- def test_refresh_propagates_unexpected_service_errors(self, mock_refresh_token, mock_extract_token, app: Flask):- """- Test token refresh preserves unexpected service failures.-- Verifies that:- - Operational errors are not misreported as authentication failures- - The original exception is preserved for higher-level error handling- """- # Arrange- mock_extract_token.return_value = "valid_refresh_token"- mock_refresh_token.side_effect = RuntimeError("redis unavailable")-- # Act & Assert- with app.test_request_context("/refresh-token", method="POST"):- refresh_api = RefreshTokenApi()- with pytest.raises(RuntimeError, match="redis unavailable"):- refresh_api.post()-- @patch("controllers.console.auth.login.extract_refresh_token", autospec=True)- @patch("controllers.console.auth.login.AccountService.refresh_token", autospec=True)- def test_refresh_with_empty_token(self, mock_refresh_token, mock_extract_token, app: Flask):- """- Test token refresh with empty string token.-- Verifies that:- - Empty string is treated as no token- - 401 status code is returned- """- # Arrange- mock_extract_token.return_value = ""-- # Act- with app.test_request_context("/refresh-token", method="POST"):- refresh_api = RefreshTokenApi()- response, status_code = refresh_api.post()-- # Assert- assert status_code == 401- assert response["result"] == "fail"-- @patch("controllers.console.auth.login.extract_refresh_token", autospec=True)- @patch("controllers.console.auth.login.AccountService.refresh_token", autospec=True)- def test_refresh_updates_all_tokens(self, mock_refresh_token, mock_extract_token, app: Flask, mock_token_pair):- """- Test that token refresh updates all three tokens.-- Verifies that:- - Access token is updated- - Refresh token is rotated- - CSRF token is regenerated- """- # Arrange- mock_extract_token.return_value = "valid_refresh_token"- mock_refresh_token.return_value = mock_token_pair-- # Act- with app.test_request_context("/refresh-token", method="POST"):- refresh_api = RefreshTokenApi()- response = refresh_api.post()-- # Assert- assert response.json["result"] == "success"- # Verify new token pair was generated- mock_refresh_token.assert_called_once_with("valid_refresh_token", session=ANY)- # In real implementation, cookies would be set with new values- assert mock_token_pair.access_token == "new_access_token"- assert mock_token_pair.refresh_token == "new_refresh_token"- assert mock_token_pair.csrf_token == "new_csrf_token"diff --git a/api/tests/unit_tests/controllers/console/workspace/test_accounts.py b/api/tests/unit_tests/controllers/console/workspace/test_accounts.pyindex 4ddce9a1b62..e469fa5555d 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_accounts.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_accounts.py@@ -16,7 +16,11 @@ from controllers.console.auth.error import (EmailCodeAccountDeletionRateLimitExceededError,EmailCodeError,)-from controllers.console.error import AccountInFreezeError, EmailDomainSuspendedError+from controllers.console.error import (+ AccountInFreezeError,+ EmailDomainSuspendedError,+ InvalidAccountPasswordRequestError,+)from controllers.console.workspace.account import (AccountAvatarApi,AccountAvatarPayload,@@ -50,7 +54,6 @@ from controllers.console.workspace.error import (AccountAlreadyInitedError,CurrentPasswordIncorrectError,InvalidAccountDeletionCodeError,- InvalidAccountPasswordRequestError,MissingInvitationCodeRequestError,)from machinery.context import RequestContextdiff --git a/api/tests/unit_tests/controllers/console/workspace/test_workspace.py b/api/tests/unit_tests/controllers/console/workspace/test_workspace.pyindex 986816fea26..76a87aeac66 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_workspace.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_workspace.py@@ -214,6 +214,8 @@ class TestWorkspaceQueryRepository:result = repository.list_for_account("account-1")membership_ids = repository.list_ids_for_account("account-1")+ assert repository.has_active_for_account("account-1") is True+ assert repository.has_active_for_account("missing-account") is Falseassert result == (WorkspaceRecord(id=earlier.id,diff --git a/api/tests/unit_tests/controllers/web/test_web_login.py b/api/tests/unit_tests/controllers/web/test_web_login.pyindex 54079b96c80..b1adb66f2a9 100644--- a/api/tests/unit_tests/controllers/web/test_web_login.py+++ b/api/tests/unit_tests/controllers/web/test_web_login.py@@ -16,7 +16,7 @@ from controllers.web.login import EmailCodeLoginApi, EmailCodeLoginSendEmailApi,from enums import DeploymentEditionfrom models.account import Accountfrom models.model import DifySetup-from services.entities.auth_entities import LoginFailureReason+from services.entities.auth_audit_entities import LoginFailureReasonpytestmark = pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)diff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.pyindex ac359b958c8..d0c60c0f4e2 100644--- a/api/tests/unit_tests/extensions/test_ext_application_services.py+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py@@ -25,12 +25,12 @@ from repositories.account_repository import SQLAlchemyAccountRepositoryfrom repositories.app_site_command_repository import AppSiteCommandRepositoryfrom repositories.workflow_run_archive_repository import WorkflowRunArchiveBundleQueryRepositoryfrom services import account_forgot_password_service, recommended_app_catalog_gateway-from services.account_activation_adapters import (+from services.account_adapters import (BillingAccountActivationEligibility,BillingWorkspaceMembershipCache,DeploymentWorkspaceInvitePolicy,RBACWorkspaceMemberAccessSync,- RegisterServiceInvitationTokenStore,+ RedisInvitationTokenStore,)from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGatewayfrom services.account_email_registration_adapters import (@@ -50,7 +50,6 @@ from services.billing_portal_service import BillingPortalServicefrom services.billing_service import BillingServicefrom services.compliance_download_service import ComplianceDownloadServicefrom services.enterprise.enterprise_service import WebAppSettings-from services.entities.mail_entities import InnerMailMessagefrom services.errors.enterprise import EnterpriseAPIError, EnterpriseAPINotFoundErrorfrom services.file_service import FileServicefrom services.init_validation_service import InvalidInitializationPasswordError@@ -393,6 +392,7 @@ def test_build_application_services_wires_account_profile_repository(assert isinstance(accounts, SQLAlchemyAccountRepository)assert accounts._session_factory is sqlite_session_factoryassert services.accounts.password._accounts is accounts+ assert services.accounts.authentication._passwords is services.accounts.password._passwordsforgot_password = services.accounts.forgot_passwordassert forgot_password._accounts is accountsassert forgot_password._passwords is services.accounts.password._passwords@@ -422,6 +422,8 @@ def test_build_application_services_wires_account_profile_repository(assert email_registration._registration._session_factory is sqlite_session_factoryassert services.accounts.education._accounts is accountsassert services.accounts.deletion._accounts is accounts+ assert services.accounts.authentication._accounts is accounts+ assert services.accounts.authentication._workspaces is services.workspace_queries._workspacesassert services.notifications._accounts is accountsassert services.step_by_step_tour._accounts is accountsassert services.accounts.deletion._memberships is services.workspace_queries._workspaces@@ -467,7 +469,7 @@ def test_build_application_services_wires_account_activation()activation = services.account_activation- assert isinstance(activation._tokens, RegisterServiceInvitationTokenStore)+ assert isinstance(activation._tokens, RedisInvitationTokenStore)assert isinstance(activation._accounts, SQLAlchemyAccountActivationRepository)assert activation._accounts._session_factory is sqlite_session_factoryassert isinstance(activation._workspace_policy, DeploymentWorkspaceInvitePolicy)@@ -491,59 +493,6 @@ def test_build_application_services_wires_data_source_api_key_auth(assert isinstance(services.data_source_api_key_auth, DataSourceApiKeyAuthService)- ("substitutions", "expected_substitutions"),- [- pytest.param({"name": "Ada"}, {"name": "Ada"}, id="configured"),- pytest.param(None, {}, id="omitted-or-null"),- ],-)-def test_build_application_services_wires_inner_mail_dispatcher(- sqlite_session_factory: sessionmaker[Session],- substitutions: dict[str, object] | None,- expected_substitutions: dict[str, object],-) -> None:- services = ext_application_services.build_application_services(- database_client=sqlite_session_factory,- deployment_edition=DeploymentEdition.COMMUNITY,- initialization_password="",- redis=MagicMock(spec=RedisClientWrapper),- )- message = InnerMailMessage(- recipients=("[email protected]", "[email protected]"),- subject="Subject",- body="Body",- substitutions=substitutions,- )-- with patch("tasks.mail_inner_task.send_inner_email_task.delay") as delay:- services.inner_mail.send(message)-- delay.assert_called_once_with(- to=["[email protected]", "[email protected]"],- subject="Subject",- body="Body",- substitutions=expected_substitutions,- )---def test_build_application_services_uses_passed_edition_for_webapp_auth(- monkeypatch: pytest.MonkeyPatch,- sqlite_session_factory: sessionmaker[Session],-) -> None:- apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)-- with patch("extensions.ext_application_services.DeploymentWebPassportAuthGateway") as auth_gateway:- ext_application_services.build_application_services(- database_client=sqlite_session_factory,- deployment_edition=DeploymentEdition.ENTERPRISE,- initialization_password="",- redis=MagicMock(spec=RedisClientWrapper),- )-- assert auth_gateway.call_args.kwargs["webapp_auth_enabled"] is True--def test_build_application_services_wires_trial_app_usage(sqlite_session_factory: sessionmaker[Session],) -> None:diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.tomlindex b76a91281a7..c36941f0469 100644--- a/api/tests/unit_tests/pyrefly.toml+++ b/api/tests/unit_tests/pyrefly.toml@@ -68,17 +68,14 @@ project-excludes = ["controllers/console/app/test_wraps.py","controllers/console/app/workflow_draft_variables_test.py","controllers/console/auth/test_account_activation.py",- "controllers/console/auth/test_authentication_security.py","controllers/console/auth/test_data_source_bearer_auth.py","controllers/console/auth/test_email_register.py","controllers/console/auth/test_email_register_language.py",- "controllers/console/auth/test_email_verification.py","controllers/console/auth/test_forgot_password.py","controllers/console/auth/test_login_logout.py","controllers/console/auth/test_oauth.py","controllers/console/auth/test_oauth_timezone.py","controllers/console/auth/test_password_reset.py",- "controllers/console/auth/test_token_refresh.py","controllers/console/billing/test_billing.py","controllers/console/datasets/rag_pipeline/test_datasource_auth.py","controllers/console/datasets/rag_pipeline/test_datasource_content_preview.py",diff --git a/api/tests/unit_tests/repositories/test_account_repository.py b/api/tests/unit_tests/repositories/test_account_repository.pyindex 11a43faf6bb..df182e62818 100644--- a/api/tests/unit_tests/repositories/test_account_repository.py+++ b/api/tests/unit_tests/repositories/test_account_repository.py@@ -8,6 +8,10 @@ from models.account import Account, AccountIntegrate, AccountStatus, InvitationCfrom repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepositoryfrom repositories.account_repository import SQLAlchemyAccountRepositoryfrom services.entities.account_entities import AccountInitialization, AccountPasswordDigest, AccountProfileChanges+from services.entities.account_login_entities import (+ AccountSessionPreparation,+ PasswordLoginCompletion,+)def _persist_account(session: Session) -> Account:@@ -98,6 +102,85 @@ def test_account_repository_updates_password(assert persisted.password_salt == "new-salt"+def test_account_repository_returns_exact_then_lowercase_login_candidates(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ lowercase_account = _persist_account(sqlite_session)+ lowercase_account.password = "lowercase-hash"+ lowercase_account.password_salt = "lowercase-salt"+ mixed_case_account = Account(name="Mixed", email="[email protected]")+ mixed_case_account.id = "account-2"+ mixed_case_account.password = "mixed-case-hash"+ mixed_case_account.password_salt = "mixed-case-salt"+ sqlite_session.add(mixed_case_account)+ sqlite_session.commit()+ repository = SQLAlchemyAccountRepository(sqlite_session_factory)++ candidates = repository.list_for_login("[email protected]")++ assert [candidate.id for candidate in candidates] == ["account-2", "account-1"]+ assert [candidate.email for candidate in candidates] == ["[email protected]", "[email protected]"]+ assert [candidate.password_hash for candidate in candidates] == ["mixed-case-hash", "lowercase-hash"]+++def test_account_repository_sets_invitation_login_password(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ account = _persist_account(sqlite_session)+ account.status = AccountStatus.PENDING+ sqlite_session.commit()+ repository = SQLAlchemyAccountRepository(sqlite_session_factory)+ initialized_at = datetime(2026, 8, 24, 12, 0, 0)++ updated = repository.complete_password_login(+ PasswordLoginCompletion(+ account_id="account-1",+ password=AccountPasswordDigest(password_hash="login-hash", password_salt="login-salt"),+ activate_pending_account=True,+ initialized_at=initialized_at,+ )+ )++ assert updated is True+ sqlite_session.expire_all()+ persisted = sqlite_session.get(Account, "account-1")+ assert persisted is not None+ assert persisted.password == "login-hash"+ assert persisted.password_salt == "login-salt"+ assert persisted.status == AccountStatus.ACTIVE+ assert persisted.initialized_at == initialized_at+++def test_account_repository_prepares_login_session(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ account = _persist_account(sqlite_session)+ account.status = AccountStatus.PENDING+ sqlite_session.commit()+ repository = SQLAlchemyAccountRepository(sqlite_session_factory)+ logged_in_at = datetime(2026, 8, 24, 13, 0, 0)++ prepared = repository.prepare_session(+ "account-1",+ AccountSessionPreparation(+ logged_in_at=logged_in_at,+ ip_address="203.0.113.10",+ activate_pending_account=True,+ ),+ )++ assert prepared is True+ sqlite_session.expire_all()+ persisted = sqlite_session.get(Account, "account-1")+ assert persisted is not None+ assert persisted.last_login_at == logged_in_at+ assert persisted.last_login_ip == "203.0.113.10"+ assert persisted.status == AccountStatus.ACTIVE++def test_account_repository_finds_email_with_lowercase_fallback(sqlite_session: Session,sqlite_session_factory: sessionmaker[Session],diff --git a/api/tests/unit_tests/services/test_account_activation_adapters.py b/api/tests/unit_tests/services/test_account_activation_adapters.pydeleted file mode 100644index 7bfdd87ddf4..00000000000--- a/api/tests/unit_tests/services/test_account_activation_adapters.py+++ /dev/null@@ -1,93 +0,0 @@-from unittest.mock import patch--from services.account_activation_adapters import (- BillingAccountActivationEligibility,- BillingWorkspaceMembershipCache,- DeploymentWorkspaceInvitePolicy,- RBACWorkspaceMemberAccessSync,- RegisterServiceInvitationTokenStore,-)-from services.entities.account_activation_entities import InvitationLookup, InvitationToken---def test_invitation_token_store_converts_legacy_service_data() -> None:- lookup = InvitationLookup(workspace_id="workspace-1", email="[email protected]", token="token-1")- with patch(- "services.account_activation_adapters.RegisterService.get_invitation_by_token",- return_value={- "account_id": "account-1",- "email": "[email protected]",- "workspace_id": "workspace-1",- "role": "editor",- "requires_setup": False,- },- ) as find:- result = RegisterServiceInvitationTokenStore().find(lookup)-- assert result == InvitationToken(- account_id="account-1",- email="[email protected]",- workspace_id="workspace-1",- role="editor",- requires_setup=False,- )- find.assert_called_once_with("token-1", "workspace-1", "[email protected]")---def test_invitation_token_store_revokes_with_legacy_key_inputs() -> None:- lookup = InvitationLookup(workspace_id="workspace-1", email="[email protected]", token="token-1")- with patch("services.account_activation_adapters.RegisterService.revoke_token") as revoke:- RegisterServiceInvitationTokenStore().revoke(lookup)-- revoke.assert_called_once_with("workspace-1", "[email protected]", "token-1")---def test_billing_eligibility_skips_gateway_when_disabled() -> None:- with patch("services.account_activation_adapters.BillingService.get_email_freeze_type") as get_freeze_type:- result = BillingAccountActivationEligibility(enabled=False).get_freeze_type("[email protected]")-- assert result is None- get_freeze_type.assert_not_called()---def test_billing_eligibility_returns_freeze_type_when_enabled() -> None:- with patch(- "services.account_activation_adapters.BillingService.get_email_freeze_type",- return_value="email_domain_suspended",- ) as get_freeze_type:- result = BillingAccountActivationEligibility(enabled=True).get_freeze_type("[email protected]")-- assert result == "email_domain_suspended"- get_freeze_type.assert_called_once_with("[email protected]")---def test_membership_cache_skips_gateway_when_disabled() -> None:- with patch("services.account_activation_adapters.BillingService.clean_billing_info_cache") as invalidate:- BillingWorkspaceMembershipCache(enabled=False).invalidate("workspace-1")-- invalidate.assert_not_called()---def test_workspace_policy_delegates_to_existing_policy_owner() -> None:- with patch("services.account_activation_adapters.check_workspace_member_invite_permission") as ensure_allowed:- DeploymentWorkspaceInvitePolicy().ensure_allowed("workspace-1")-- ensure_allowed.assert_called_once_with("workspace-1")---def test_rbac_member_access_sync_skips_gateway_when_disabled() -> None:- with patch(- "tasks.initialize_created_app_rbac_access_task.sync_joined_workspace_member_rbac_access_task.delay"- ) as delay:- RBACWorkspaceMemberAccessSync(enabled=False).sync("workspace-1", "account-1")-- delay.assert_not_called()---def test_rbac_member_access_sync_enqueues_joined_member_sync_when_enabled() -> None:- with patch(- "tasks.initialize_created_app_rbac_access_task.sync_joined_workspace_member_rbac_access_task.delay"- ) as delay:- RBACWorkspaceMemberAccessSync(enabled=True).sync("workspace-1", "account-1")-- delay.assert_called_once_with("workspace-1", "account-1", operator_account_id=None)diff --git a/api/tests/unit_tests/services/test_account_adapters.py b/api/tests/unit_tests/services/test_account_adapters.pynew file mode 100644index 00000000000..0ef41bea71e--- /dev/null+++ b/api/tests/unit_tests/services/test_account_adapters.py@@ -0,0 +1,316 @@+from datetime import UTC, datetime+from hashlib import sha256+from typing import cast+from unittest.mock import MagicMock, patch++import pytest++from extensions.ext_redis import RedisClientWrapper+from libs.helper import RateLimiter+from services.account_adapters import (+ BillingAccountActivationEligibility,+ BillingAccountEducationGateway,+ BillingAccountEmailPolicyGateway,+ BillingWorkspaceMembershipCache,+ CeleryAccountDeletionVerificationNotifier,+ DeploymentWorkspaceInvitePolicy,+ RBACWorkspaceMemberAccessSync,+ RedisChangeEmailSecurityGateway,+ RedisInvitationTokenStore,+ TokenManagerAccountDeletionVerificationGateway,+ TokenManagerChangeEmailTokenGateway,+)+from services.account_errors import AccountDeletionRateLimitError+from services.entities.account_activation_entities import InvitationLookup, InvitationToken+from services.entities.account_entities import (+ AccountChangeEmailNewEmailToken,+ AccountEducationActivation,+ AccountEducationAutocomplete,+ AccountEducationStatus,+)+++def test_invitation_token_store_reads_workspace_invitation_key() -> None:+ redis = MagicMock(spec=RedisClientWrapper)+ redis.get.return_value = b"account-1"+ lookup = InvitationLookup(workspace_id="workspace-1", email="[email protected]", token="token-1")++ result = RedisInvitationTokenStore(redis=cast(RedisClientWrapper, redis)).find(lookup)++ assert result == InvitationToken(+ account_id="account-1",+ email="[email protected]",+ workspace_id="workspace-1",+ )+ email_hash = sha256(b"[email protected]").hexdigest()+ redis.get.assert_called_once_with(f"member_invite_token:workspace-1, {email_hash}:token-1")+++def test_invitation_token_store_reads_global_invitation_payload() -> None:+ redis = MagicMock(spec=RedisClientWrapper)+ redis.get.return_value = (+ b'{"account_id":"account-1","email":"[email protected]","workspace_id":"workspace-1",'+ b'"role":"editor","requires_setup":false}'+ )+ lookup = InvitationLookup(workspace_id=None, email="[email protected]", token="token-1")++ result = RedisInvitationTokenStore(redis=cast(RedisClientWrapper, redis)).find(lookup)++ assert result == InvitationToken(+ account_id="account-1",+ email="[email protected]",+ workspace_id="workspace-1",+ role="editor",+ requires_setup=False,+ )+ redis.get.assert_called_once_with("member_invite:token:token-1")+++def test_invitation_token_store_revokes_its_redis_key() -> None:+ redis = MagicMock(spec=RedisClientWrapper)+ lookup = InvitationLookup(workspace_id="workspace-1", email="[email protected]", token="token-1")++ RedisInvitationTokenStore(redis=cast(RedisClientWrapper, redis)).revoke(lookup)++ email_hash = sha256(b"[email protected]").hexdigest()+ redis.delete.assert_called_once_with(f"member_invite_token:workspace-1, {email_hash}:token-1")+++def test_billing_eligibility_skips_gateway_when_disabled() -> None:+ with patch("services.account_adapters.BillingService.get_email_freeze_type") as get_freeze_type:+ result = BillingAccountActivationEligibility(enabled=False).get_freeze_type("[email protected]")++ assert result is None+ get_freeze_type.assert_not_called()+++def test_billing_eligibility_returns_freeze_type_when_enabled() -> None:+ with patch(+ "services.account_adapters.BillingService.get_email_freeze_type",+ return_value="email_domain_suspended",+ ) as get_freeze_type:+ result = BillingAccountActivationEligibility(enabled=True).get_freeze_type("[email protected]")++ assert result == "email_domain_suspended"+ get_freeze_type.assert_called_once_with("[email protected]")+++def test_membership_cache_skips_gateway_when_disabled() -> None:+ with patch("services.account_adapters.BillingService.clean_billing_info_cache") as invalidate:+ BillingWorkspaceMembershipCache(enabled=False).invalidate("workspace-1")++ invalidate.assert_not_called()+++def test_workspace_policy_delegates_to_existing_policy_owner() -> None:+ with patch("services.account_adapters.check_workspace_member_invite_permission") as ensure_allowed:+ DeploymentWorkspaceInvitePolicy().ensure_allowed("workspace-1")++ ensure_allowed.assert_called_once_with("workspace-1")+++def test_rbac_member_access_sync_skips_gateway_when_disabled() -> None:+ with patch(+ "tasks.initialize_created_app_rbac_access_task.sync_joined_workspace_member_rbac_access_task.delay"+ ) as delay:+ RBACWorkspaceMemberAccessSync(enabled=False).sync("workspace-1", "account-1")++ delay.assert_not_called()+++def test_rbac_member_access_sync_enqueues_joined_member_sync_when_enabled() -> None:+ with patch(+ "tasks.initialize_created_app_rbac_access_task.sync_joined_workspace_member_rbac_access_task.delay"+ ) as delay:+ RBACWorkspaceMemberAccessSync(enabled=True).sync("workspace-1", "account-1")++ delay.assert_called_once_with("workspace-1", "account-1", operator_account_id=None)+++def test_education_gateway_normalizes_billing_status_timestamp() -> None:+ gateway = BillingAccountEducationGateway()++ with patch(+ "services.account_adapters.BillingService.EducationIdentity.status",+ return_value={+ "result": True,+ "is_student": True,+ "expire_at": "2027-01-01T00:00:00+00:00",+ "allow_refresh": False,+ },+ ):+ result = gateway.status("account-1")++ assert result == AccountEducationStatus(+ result=True,+ is_student=True,+ expire_at=datetime(2027, 1, 1, tzinfo=UTC),+ allow_refresh=False,+ )+++def test_education_gateway_activates_with_primitive_account_context() -> None:+ gateway = BillingAccountEducationGateway()++ with patch(+ "services.account_adapters.BillingService.EducationIdentity.activate",+ return_value={"message": "success"},+ ) as activate:+ result = gateway.activate(+ account_id="account-1",+ tenant_id="workspace-1",+ token="education-token",+ institution="Dify University",+ role="Student",+ )++ assert result == AccountEducationActivation(message="success")+ activate.assert_called_once_with(+ account_id="account-1",+ tenant_id="workspace-1",+ token="education-token",+ institution="Dify University",+ role="Student",+ )+++def test_education_gateway_normalizes_autocomplete_defaults() -> None:+ gateway = BillingAccountEducationGateway()++ with patch(+ "services.account_adapters.BillingService.EducationIdentity.autocomplete",+ return_value=None,+ ):+ result = gateway.autocomplete(keywords="Example", page=0, limit=20)++ assert result == AccountEducationAutocomplete(data=(), curr_page=None, has_next=None)+++def test_billing_email_policy_preserves_suspended_domain_reason() -> None:+ gateway = BillingAccountEmailPolicyGateway(billing_enabled=True)++ with (+ patch("services.account_adapters.BillingService.is_email_in_freeze", return_value=True),+ patch(+ "services.account_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_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_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)+++def test_verification_gateway_binds_token_to_the_target_account() -> None:+ gateway = TokenManagerAccountDeletionVerificationGateway()++ with patch(+ "services.account_adapters.TokenManager.get_token_data",+ return_value={"account_id": "account-1", "code": "123456"},+ ):+ assert gateway.verify(account_id="account-1", token="token", code="123456") is True+ assert gateway.verify(account_id="account-2", token="token", code="123456") is False+++def test_verification_gateway_creates_six_digit_account_bound_challenge() -> None:+ gateway = TokenManagerAccountDeletionVerificationGateway()++ with (+ patch("services.account_adapters.secrets.randbelow", side_effect=[1, 2, 3, 4, 5, 6]),+ patch(+ "services.account_adapters.TokenManager.generate_token",+ return_value="token",+ ) as generate_token,+ ):+ challenge = gateway.create(account_id="account-1", email="[email protected]")++ assert challenge.token == "token"+ assert challenge.code == "123456"+ 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"}+++def test_verification_notifier_preserves_rate_limit_before_enqueuing_email() -> None:+ limiter = MagicMock(spec=RateLimiter)+ limiter.is_rate_limited.return_value = True+ limiter.time_window = 60+ notifier = CeleryAccountDeletionVerificationNotifier(rate_limiter=limiter)++ with (+ patch("services.account_adapters.send_account_deletion_verification_code") as mail_task,+ pytest.raises(AccountDeletionRateLimitError) as error,+ ):+ notifier.send(email="[email protected]", code="123456")++ assert error.value.retry_after_minutes == 1+ mail_task.delay.assert_not_called()diff --git a/api/tests/unit_tests/services/test_account_billing_adapters.py b/api/tests/unit_tests/services/test_account_billing_adapters.pydeleted file mode 100644index f2e76c60161..00000000000--- a/api/tests/unit_tests/services/test_account_billing_adapters.py+++ /dev/null@@ -1,68 +0,0 @@-from datetime import UTC, datetime-from unittest.mock import patch--from services.account_billing_adapters import BillingAccountEducationGateway-from services.entities.account_entities import (- AccountEducationActivation,- AccountEducationAutocomplete,- AccountEducationStatus,-)---def test_education_gateway_normalizes_billing_status_timestamp() -> None:- gateway = BillingAccountEducationGateway()-- with patch(- "services.account_billing_adapters.BillingService.EducationIdentity.status",- return_value={- "result": True,- "is_student": True,- "expire_at": "2027-01-01T00:00:00+00:00",- "allow_refresh": False,- },- ):- result = gateway.status("account-1")-- assert result == AccountEducationStatus(- result=True,- is_student=True,- expire_at=datetime(2027, 1, 1, tzinfo=UTC),- allow_refresh=False,- )---def test_education_gateway_activates_with_primitive_account_context() -> None:- gateway = BillingAccountEducationGateway()-- with patch(- "services.account_billing_adapters.BillingService.EducationIdentity.activate",- return_value={"message": "success"},- ) as activate:- result = gateway.activate(- account_id="account-1",- tenant_id="workspace-1",- token="education-token",- institution="Dify University",- role="Student",- )-- assert result == AccountEducationActivation(message="success")- activate.assert_called_once_with(- account_id="account-1",- tenant_id="workspace-1",- token="education-token",- institution="Dify University",- role="Student",- )---def test_education_gateway_normalizes_autocomplete_defaults() -> None:- gateway = BillingAccountEducationGateway()-- with patch(- "services.account_billing_adapters.BillingService.EducationIdentity.autocomplete",- return_value=None,- ):- result = gateway.autocomplete(keywords="Example", page=0, limit=20)-- assert result == AccountEducationAutocomplete(data=(), curr_page=None, has_next=None)diff --git a/api/tests/unit_tests/services/test_account_change_email_adapters.py b/api/tests/unit_tests/services/test_account_change_email_adapters.pydeleted file mode 100644index 1b59e53f278..00000000000--- a/api/tests/unit_tests/services/test_account_change_email_adapters.py+++ /dev/null@@ -1,93 +0,0 @@-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_deletion_adapters.py b/api/tests/unit_tests/services/test_account_deletion_adapters.pydeleted file mode 100644index 880b5e8a094..00000000000--- a/api/tests/unit_tests/services/test_account_deletion_adapters.py+++ /dev/null@@ -1,56 +0,0 @@-from unittest.mock import MagicMock, patch--import pytest--from libs.helper import RateLimiter-from services.account_deletion_adapters import (- CeleryAccountDeletionVerificationNotifier,- TokenManagerAccountDeletionVerificationGateway,-)-from services.account_errors import AccountDeletionRateLimitError---def test_verification_gateway_binds_token_to_the_target_account() -> None:- gateway = TokenManagerAccountDeletionVerificationGateway()-- with patch(- "services.account_deletion_adapters.TokenManager.get_token_data",- return_value={"account_id": "account-1", "code": "123456"},- ):- assert gateway.verify(account_id="account-1", token="token", code="123456") is True- assert gateway.verify(account_id="account-2", token="token", code="123456") is False---def test_verification_gateway_creates_six_digit_account_bound_challenge() -> None:- gateway = TokenManagerAccountDeletionVerificationGateway()-- with (- patch("services.account_deletion_adapters.secrets.randbelow", side_effect=[1, 2, 3, 4, 5, 6]),- patch(- "services.account_deletion_adapters.TokenManager.generate_token",- return_value="token",- ) as generate_token,- ):- challenge = gateway.create(account_id="account-1", email="[email protected]")-- assert challenge.token == "token"- assert challenge.code == "123456"- 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"}---def test_verification_notifier_preserves_rate_limit_before_enqueuing_email() -> None:- limiter = MagicMock(spec=RateLimiter)- limiter.is_rate_limited.return_value = True- limiter.time_window = 60- notifier = CeleryAccountDeletionVerificationNotifier(rate_limiter=limiter)-- with (- patch("services.account_deletion_adapters.send_account_deletion_verification_code") as mail_task,- pytest.raises(AccountDeletionRateLimitError) as error,- ):- notifier.send(email="[email protected]", code="123456")-- assert error.value.retry_after_minutes == 1- mail_task.delay.assert_not_called()diff --git a/api/tests/unit_tests/services/test_account_login_adapters.py b/api/tests/unit_tests/services/test_account_login_adapters.pynew file mode 100644index 00000000000..0c113377a3b--- /dev/null+++ b/api/tests/unit_tests/services/test_account_login_adapters.py@@ -0,0 +1,423 @@+from __future__ import annotations++import logging+from collections.abc import Callable+from dataclasses import dataclass, field+from typing import cast, override+from unittest.mock import MagicMock++import pytest+from sqlalchemy import select+from sqlalchemy.orm import Session, sessionmaker++from extensions.ext_redis import RedisClientWrapper+from libs.helper import RateLimiter+from models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole+from services import account_errors+from services import account_login_adapters as adapters+from services.email_code_login_challenge import (+ EmailCodeLoginChallengeResult,+ EmailCodeLoginChallengeStatus,+ EmailCodeLoginChallengeUnavailableError,+)+from services.entities.account_login_entities import AuthTokenPair, EmailCodeChallengeStatus, RefreshAccountStatus+from services.turnstile_service import TurnstileChallengeRejectedError, TurnstileUpstreamError+++class FakeRateLimiter(RateLimiter):+ def __init__(self, *, limited: bool = False, time_window: int = 300) -> None:+ self.limited = limited+ self.time_window = time_window+ self.recorded: list[str] = []++ @override+ def is_rate_limited(self, email: str) -> bool:+ return self.limited++ @override+ def increment_rate_limit(self, email: str) -> None:+ self.recorded.append(email)+++@dataclass+class FakeTask:+ calls: list[dict[str, object]] = field(default_factory=list)++ def delay(self, **kwargs: object) -> None:+ self.calls.append(kwargs)+++def _persist_account(session: Session) -> Account:+ account = Account(name="User", email="[email protected]")+ account.id = "account-1"+ session.add(account)+ session.commit()+ return account+++def test_security_gateway_owns_login_failure_state() -> None:+ redis = MagicMock(spec=RedisClientWrapper)+ redis.get.side_effect = [b"6", b"2"]+ gateway = adapters.RedisConsoleAuthSecurityGateway(redis=cast(RedisClientWrapper, redis))++ assert gateway.is_login_limited("[email protected]") is True+ gateway.record_login_failure("[email protected]")+ gateway.reset_login_failures("[email protected]")++ redis.setex.assert_called_once_with(+ "login_error_rate_limit:[email protected]",+ adapters.dify_config.LOGIN_LOCKOUT_DURATION,+ 3,+ )+ redis.delete.assert_called_once_with("login_error_rate_limit:[email protected]")+++def test_security_gateway_owns_email_send_ip_limit(config_overrides: Callable[..., None]) -> None:+ redis = MagicMock(spec=RedisClientWrapper)+ redis.get.side_effect = [None, b"2", None]+ redis.set.return_value = True+ config_overrides(EMAIL_SEND_IP_LIMIT_PER_MINUTE=1)+ gateway = adapters.RedisConsoleAuthSecurityGateway(redis=cast(RedisClientWrapper, redis))++ assert gateway.is_email_send_ip_limited("127.0.0.1") is True+ redis.set.assert_called_once_with("email_send_ip_limit_hour:127.0.0.1", 1, ex=600, nx=True)+++def test_session_gateway_owns_refresh_token_storage(monkeypatch: pytest.MonkeyPatch) -> None:+ redis = MagicMock(spec=RedisClientWrapper)+ issued_payloads: list[dict[str, object]] = []++ class FakePassportService:+ def issue(self, payload: dict[str, object]) -> str:+ issued_payloads.append(payload)+ return "access"++ monkeypatch.setattr(adapters, "PassportService", FakePassportService)+ monkeypatch.setattr(adapters.secrets, "token_hex", lambda _length: "refresh")+ monkeypatch.setattr(adapters, "generate_csrf_token", lambda _account_id: "csrf")+ gateway = adapters.RedisAccountSessionGateway(redis=cast(RedisClientWrapper, redis))++ result = gateway.issue("account-1")++ assert result == AuthTokenPair(access_token="access", refresh_token="refresh", csrf_token="csrf")+ assert issued_payloads[0]["user_id"] == "account-1"+ assert redis.setex.call_args_list[0].args[0] == "refresh_token:refresh"+ assert redis.setex.call_args_list[1].args[0] == "account_refresh_token:account-1"+++def test_session_gateway_resolves_rotates_and_revokes_refresh_tokens(monkeypatch: pytest.MonkeyPatch) -> None:+ redis = MagicMock(spec=RedisClientWrapper)+ redis.get.side_effect = [b"account-1", b"stored-refresh"]+ gateway = adapters.RedisAccountSessionGateway(redis=cast(RedisClientWrapper, redis))+ monkeypatch.setattr(+ gateway,+ "_issue",+ lambda _account_id: AuthTokenPair(access_token="new-access", refresh_token="new-refresh", csrf_token="csrf"),+ )++ assert gateway.resolve_refresh_token("refresh") == "account-1"+ assert gateway.rotate(refresh_token="refresh", account_id="account-1").refresh_token == "new-refresh"+ gateway.revoke("account-1")++ deleted_keys = [call.args[0] for call in redis.delete.call_args_list]+ assert deleted_keys == [+ "refresh_token:refresh",+ "account_refresh_token:account-1",+ "refresh_token:stored-refresh",+ "account_refresh_token:account-1",+ ]+++def test_session_gateway_returns_none_for_unknown_refresh_token() -> None:+ redis = MagicMock(spec=RedisClientWrapper)+ redis.get.return_value = None++ assert (+ adapters.RedisAccountSessionGateway(redis=cast(RedisClientWrapper, redis)).resolve_refresh_token("bad-token")+ is None+ )+++def test_workspace_provisioning_gateway_persists_owner_workspace(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _persist_account(sqlite_session)+ gateway = adapters.SQLAlchemyConsoleAuthProvisioningGateway(session_factory=sqlite_session_factory)+ monkeypatch.setattr(adapters, "generate_key_pair", lambda _tenant_id: "public-key")+ monkeypatch.setattr(gateway, "_after_workspace_created", lambda _tenant, _account_id: None)++ gateway.create_owner_workspace("account-1")++ with sqlite_session_factory() as session:+ membership = session.scalar(select(TenantAccountJoin).where(TenantAccountJoin.account_id == "account-1"))+ assert membership is not None+ assert membership.role == TenantAccountRole.OWNER+ assert session.get(Tenant, membership.tenant_id) is not None+++def test_workspace_provisioning_gateway_rejects_missing_account(+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ gateway = adapters.SQLAlchemyConsoleAuthProvisioningGateway(session_factory=sqlite_session_factory)++ with pytest.raises(account_errors.AccountNotFoundError):+ gateway.create_owner_workspace("missing-account")+++ ("status", "with_workspace", "expected_status"),+ [+ (AccountStatus.ACTIVE, True, RefreshAccountStatus.READY),+ (AccountStatus.ACTIVE, False, RefreshAccountStatus.NOT_FOUND),+ (AccountStatus.BANNED, False, RefreshAccountStatus.BANNED),+ ],+)+def test_refresh_preparation_gateway_owns_account_state_query(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+ status: AccountStatus,+ with_workspace: bool,+ expected_status: RefreshAccountStatus,+) -> None:+ account = _persist_account(sqlite_session)+ account.status = status+ if with_workspace:+ tenant = Tenant(name="Workspace")+ sqlite_session.add(tenant)+ sqlite_session.add(+ TenantAccountJoin(+ tenant_id=tenant.id,+ account_id=account.id,+ role=TenantAccountRole.OWNER,+ current=True,+ )+ )+ sqlite_session.commit()+ gateway = adapters.SQLAlchemyAccountRefreshPreparationGateway(session_factory=sqlite_session_factory)++ assert gateway.prepare("account-1") == expected_status+++ ("provider_error", "application_error", "level", "message", "has_exception_info"),+ [+ (+ TurnstileChallengeRejectedError(),+ account_errors.HumanVerificationRejectedError,+ logging.INFO,+ "Turnstile rejected an email-code verification challenge",+ False,+ ),+ (+ TurnstileUpstreamError(),+ account_errors.HumanVerificationUnavailableError,+ logging.WARNING,+ "Turnstile verification is unavailable",+ True,+ ),+ ],+)+def test_turnstile_gateway_maps_provider_failures(+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ provider_error: Exception,+ application_error: type[Exception],+ level: int,+ message: str,+ has_exception_info: bool,+) -> None:+ def verify(**_kwargs: object) -> None:+ raise provider_error++ monkeypatch.setattr(adapters.TurnstileService, "verify", verify)++ with caplog.at_level(level, logger=adapters.__name__):+ with pytest.raises(application_error):+ adapters.TurnstileHumanVerificationGateway().verify(+ token="challenge",+ remote_ip="127.0.0.1",+ action="signin_code_verify",+ )++ record = caplog.records[-1]+ assert record.getMessage() == message+ assert (record.exc_info is not None) is has_exception_info+++def test_provisioning_gateway_persists_account_and_workspace_atomically(+ sqlite_session_factory: sessionmaker[Session],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ gateway = adapters.SQLAlchemyConsoleAuthProvisioningGateway(session_factory=sqlite_session_factory)+ monkeypatch.setattr(adapters, "generate_key_pair", lambda _tenant_id: "public-key")+ monkeypatch.setattr(gateway, "_after_workspace_created", lambda _tenant, _account_id: None)++ account_id = gateway.create_with_owner_workspace(+ email="[email protected]",+ name="User",+ interface_language="en-US",+ timezone="UTC",+ ip_address="127.0.0.1",+ )++ with sqlite_session_factory() as session:+ account = session.get(Account, account_id)+ membership = session.scalar(select(TenantAccountJoin).where(TenantAccountJoin.account_id == account_id))+ assert account is not None+ assert account.normalized_email == "[email protected]"+ assert account.timezone == "UTC"+ assert membership is not None+++def test_provisioning_gateway_rejects_equivalent_normalized_email(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ sqlite_session.add(+ Account(+ name="Existing User",+ email="[email protected]",+ normalized_email="[email protected]",+ )+ )+ sqlite_session.commit()+ gateway = adapters.SQLAlchemyConsoleAuthProvisioningGateway(session_factory=sqlite_session_factory)++ with pytest.raises(account_errors.AccountNormalizedEmailAlreadyInUseError):+ gateway.create_with_owner_workspace(+ email="[email protected]",+ name="New User",+ interface_language="en-US",+ timezone="UTC",+ ip_address="127.0.0.1",+ )+++def test_email_code_gateway_sends_and_maps_shared_challenge_status(monkeypatch: pytest.MonkeyPatch) -> None:+ limiter = FakeRateLimiter()+ task = FakeTask()+ created: list[tuple[str | None, str, str]] = []+ verified: list[tuple[str, str, str]] = []++ def create(*, account_id: str | None, email: str, code: str) -> str:+ created.append((account_id, email, code))+ return "challenge-token"++ def verify(*, email: str, code: str, token: str) -> EmailCodeLoginChallengeResult:+ verified.append((email, code, token))+ return EmailCodeLoginChallengeResult(status=EmailCodeLoginChallengeStatus.EMAIL_MISMATCH)++ monkeypatch.setattr(adapters.EmailCodeLoginChallengeStore, "create", create)+ monkeypatch.setattr(adapters.EmailCodeLoginChallengeStore, "verify", verify)+ monkeypatch.setattr(adapters, "send_email_code_login_mail_task", task)+ gateway = adapters.RedisEmailCodeGateway(rate_limiter=limiter)++ token = gateway.send(+ account_id="account-1",+ normalized_email="[email protected]",+ recipient_email="[email protected]",+ language="en-US",+ )++ assert token == "challenge-token"+ assert created[0][1] == "[email protected]"+ assert len(created[0][2]) == 6+ assert task.calls[0]["to"] == "[email protected]"+ assert limiter.recorded == ["[email protected]"]+ assert (+ gateway.verify(normalized_email="[email protected]", code="123456", token="challenge-token")+ == EmailCodeChallengeStatus.EMAIL_MISMATCH+ )+ assert verified == [("[email protected]", "123456", "challenge-token")]+++def test_email_code_gateway_maps_challenge_store_outage(+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+) -> None:+ def create(**_kwargs: object) -> str:+ raise EmailCodeLoginChallengeUnavailableError++ monkeypatch.setattr(adapters.EmailCodeLoginChallengeStore, "create", create)+ gateway = adapters.RedisEmailCodeGateway(rate_limiter=FakeRateLimiter())++ with caplog.at_level(logging.WARNING, logger=adapters.__name__):+ with pytest.raises(account_errors.EmailCodeLoginUnavailableError):+ gateway.send(+ account_id=None,+ normalized_email="[email protected]",+ recipient_email="[email protected]",+ language="en-US",+ )++ record = caplog.records[-1]+ assert record.getMessage() == "Email-code challenge creation is unavailable"+ assert record.exc_info is not None+++def test_email_code_gateway_logs_challenge_verification_outage(+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+) -> None:+ def verify(**_kwargs: object) -> EmailCodeLoginChallengeResult:+ raise EmailCodeLoginChallengeUnavailableError++ monkeypatch.setattr(adapters.EmailCodeLoginChallengeStore, "verify", verify)+ gateway = adapters.RedisEmailCodeGateway(rate_limiter=FakeRateLimiter())++ with caplog.at_level(logging.WARNING, logger=adapters.__name__):+ with pytest.raises(account_errors.EmailCodeLoginUnavailableError):+ gateway.verify(normalized_email="[email protected]", code="123456", token="challenge-token")++ record = caplog.records[-1]+ assert record.getMessage() == "Email-code challenge verification is unavailable"+ assert record.exc_info is not None+++def test_reset_password_gateway_uses_neutral_identity_values(monkeypatch: pytest.MonkeyPatch) -> None:+ limiter = FakeRateLimiter(time_window=60)+ existing_task = FakeTask()+ missing_task = FakeTask()+ token_calls: list[dict[str, object]] = []++ def generate_token(**kwargs: object) -> str:+ token_calls.append(kwargs)+ return "reset-token"++ monkeypatch.setattr(adapters.TokenManager, "generate_token", generate_token)+ monkeypatch.setattr(adapters, "send_reset_password_mail_task", existing_task)+ monkeypatch.setattr(adapters, "send_reset_password_mail_task_when_account_not_exist", missing_task)+ gateway = adapters.RedisResetPasswordEmailGateway(rate_limiter=limiter)++ result = gateway.send(+ account_id="account-1",+ email="[email protected]",+ language="en-US",+ registration_allowed=True,+ )++ assert result == "reset-token"+ assert token_calls[0]["account_id"] == "account-1"+ assert existing_task.calls[0]["to"] == "[email protected]"+ assert missing_task.calls == []+ assert limiter.recorded == ["[email protected]"]+++def test_email_gateways_raise_framework_neutral_rate_limit_errors() -> None:+ with pytest.raises(account_errors.EmailCodeSendRateLimitError) as email_code_error:+ adapters.RedisEmailCodeGateway(rate_limiter=FakeRateLimiter(limited=True)).send(+ account_id=None,+ normalized_email="[email protected]",+ recipient_email="[email protected]",+ language="en-US",+ )+ with pytest.raises(account_errors.ResetPasswordEmailRateLimitError) as reset_error:+ adapters.RedisResetPasswordEmailGateway(rate_limiter=FakeRateLimiter(limited=True, time_window=60)).send(+ account_id=None,+ email="[email protected]",+ language="en-US",+ registration_allowed=True,+ )++ assert email_code_error.value.retry_after_minutes == 5+ assert reset_error.value.retry_after_minutes == 1diff --git a/api/tests/unit_tests/services/test_account_login_service.py b/api/tests/unit_tests/services/test_account_login_service.pynew file mode 100644index 00000000000..4820c3771fb--- /dev/null+++ b/api/tests/unit_tests/services/test_account_login_service.py@@ -0,0 +1,833 @@+from __future__ import annotations++from dataclasses import dataclass, field+from datetime import datetime++import pytest++from services import account_errors+from services.account_login_service import ConsoleAuthenticationService+from services.entities.account_entities import AccountPasswordDigest+from services.entities.account_login_entities import (+ AccountSessionPreparation,+ AuthTokenPair,+ EmailCodeChallengeStatus,+ EmailCodeLoginCommand,+ EmailCodeSendCommand,+ LoginAccountSnapshot,+ LoginInvitation,+ PasswordLoginCommand,+ PasswordLoginCompletion,+ RefreshAccountStatus,+)+from services.entities.auth_audit_entities import LoginFailureReason++TOKEN_PAIR = AuthTokenPair(access_token="access", refresh_token="refresh", csrf_token="csrf")+LOGIN_TIME = datetime(2026, 8, 24, 12, 0, 0)+++@dataclass+class FakeAccounts:+ candidates: list[LoginAccountSnapshot] = field(default_factory=list)+ lookup_email: str | None = None+ session_prepared: bool = True+ completions: list[PasswordLoginCompletion] = field(default_factory=list)+ session_preparations: list[tuple[str, AccountSessionPreparation]] = field(default_factory=list)++ def list_for_login(self, email: str) -> tuple[LoginAccountSnapshot, ...]:+ self.lookup_email = email+ return tuple(self.candidates)++ def complete_password_login(self, completion: PasswordLoginCompletion) -> bool:+ self.completions.append(completion)+ return any(completion.account_id == account.id for account in self.candidates)++ def prepare_session(self, account_id: str, preparation: AccountSessionPreparation) -> bool:+ self.session_preparations.append((account_id, preparation))+ return self.session_prepared+++@dataclass+class FakeWorkspaces:+ active: bool = False++ def has_active_for_account(self, account_id: str) -> bool:+ _ = account_id+ return self.active+++@dataclass+class FakeInvitations:+ invitation: LoginInvitation | None = None++ def resolve(self, *, email: str, token: str) -> LoginInvitation | None:+ _ = email, token+ return self.invitation+++@dataclass+class FakePolicies:+ freeze_type: str | None = None+ registration_allowed: bool = True+ workspace_creation_allowed: bool = True+ workspace_capacity: bool = True+ account_capacity: bool = True++ def get_email_freeze_type(self, email: str) -> str | None:+ _ = email+ return self.freeze_type++ def is_registration_allowed(self) -> bool:+ return self.registration_allowed++ def is_workspace_creation_allowed(self) -> bool:+ return self.workspace_creation_allowed++ def has_workspace_capacity(self) -> bool:+ return self.workspace_capacity++ def has_account_capacity(self) -> bool:+ return self.account_capacity+++@dataclass+class FakeSecurity:+ login_limited: bool = False+ ip_limited: bool = False+ failures: list[str] = field(default_factory=list)+ resets: list[str] = field(default_factory=list)++ def is_login_limited(self, email: str) -> bool:+ _ = email+ return self.login_limited++ def record_login_failure(self, email: str) -> None:+ self.failures.append(email)++ def reset_login_failures(self, email: str) -> None:+ self.resets.append(email)++ def is_email_send_ip_limited(self, ip_address: str) -> bool:+ _ = ip_address+ return self.ip_limited+++@dataclass+class FakePasswords:+ valid: bool = True+ valid_password_hashes: set[str] | None = None+ hash_error: account_errors.InvalidAccountPasswordError | None = None+ hashed_passwords: list[str] = field(default_factory=list)++ def verify(self, password: str, *, password_hash: str, password_salt: str) -> bool:+ _ = password, password_hash, password_salt+ if self.valid_password_hashes is not None:+ return password_hash in self.valid_password_hashes+ return self.valid++ def hash(self, password: str) -> AccountPasswordDigest:+ self.hashed_passwords.append(password)+ if self.hash_error is not None:+ raise self.hash_error+ return AccountPasswordDigest(password_hash=f"hashed:{password}", password_salt="salt")+++@dataclass+class FakeHumanVerification:+ calls: list[tuple[str | None, str, str]] = field(default_factory=list)++ def verify(self, *, token: str | None, remote_ip: str, action: str) -> None:+ self.calls.append((token, remote_ip, action))+++@dataclass+class FakeSessions:+ issued: list[str] = field(default_factory=list)+ revoked: list[str] = field(default_factory=list)+ refresh_account_id: str | None = "account-1"+ rotations: list[tuple[str, str]] = field(default_factory=list)++ def issue(self, account_id: str) -> AuthTokenPair:+ self.issued.append(account_id)+ return TOKEN_PAIR++ def revoke(self, account_id: str) -> None:+ self.revoked.append(account_id)++ def resolve_refresh_token(self, refresh_token: str) -> str | None:+ assert refresh_token == "old-refresh"+ return self.refresh_account_id++ def rotate(self, *, refresh_token: str, account_id: str) -> AuthTokenPair:+ self.rotations.append((refresh_token, account_id))+ return TOKEN_PAIR+++@dataclass+class FakeRefreshPreparation:+ status: RefreshAccountStatus = RefreshAccountStatus.READY+ account_ids: list[str] = field(default_factory=list)++ def prepare(self, account_id: str) -> RefreshAccountStatus:+ self.account_ids.append(account_id)+ return self.status+++@dataclass+class FakeAccountProvisioning:+ calls: list[dict[str, str]] = field(default_factory=list)++ def create_with_owner_workspace(+ self,+ *,+ email: str,+ name: str,+ interface_language: str,+ timezone: str,+ ip_address: str,+ ) -> str:+ self.calls.append(+ {+ "email": email,+ "name": name,+ "interface_language": interface_language,+ "timezone": timezone,+ "ip_address": ip_address,+ }+ )+ return "new-account"+++@dataclass+class FakeWorkspaceProvisioning:+ account_ids: list[str] = field(default_factory=list)++ def create_owner_workspace(self, account_id: str) -> None:+ self.account_ids.append(account_id)+++@dataclass+class FakeEmailCodes:+ status: EmailCodeChallengeStatus = EmailCodeChallengeStatus.VERIFIED+ sent: list[tuple[str | None, str, str, str]] = field(default_factory=list)++ def send(+ self,+ *,+ account_id: str | None,+ normalized_email: str,+ recipient_email: str,+ language: str,+ ) -> str:+ self.sent.append((account_id, normalized_email, recipient_email, language))+ return "email-token"++ def verify(self, *, normalized_email: str, code: str, token: str) -> EmailCodeChallengeStatus:+ _ = normalized_email, code, token+ return self.status+++@dataclass+class FakeResetPasswordEmails:+ sent: list[tuple[str | None, str, str, bool]] = field(default_factory=list)++ def send(+ self,+ *,+ account_id: str | None,+ email: str,+ language: str,+ registration_allowed: bool,+ ) -> str:+ self.sent.append((account_id, email, language, registration_allowed))+ return "reset-token"+++@dataclass+class FakeAudit:+ failures: list[tuple[str, LoginFailureReason, str]] = field(default_factory=list)++ def login_failed(self, *, email: str, reason: LoginFailureReason, ip_address: str) -> None:+ self.failures.append((email, reason, ip_address))+++@dataclass+class Dependencies:+ accounts: FakeAccounts = field(default_factory=FakeAccounts)+ workspaces: FakeWorkspaces = field(default_factory=FakeWorkspaces)+ invitations: FakeInvitations = field(default_factory=FakeInvitations)+ policies: FakePolicies = field(default_factory=FakePolicies)+ security: FakeSecurity = field(default_factory=FakeSecurity)+ passwords: FakePasswords = field(default_factory=FakePasswords)+ human: FakeHumanVerification = field(default_factory=FakeHumanVerification)+ sessions: FakeSessions = field(default_factory=FakeSessions)+ refresh_preparation: FakeRefreshPreparation = field(default_factory=FakeRefreshPreparation)+ accounts_provisioning: FakeAccountProvisioning = field(default_factory=FakeAccountProvisioning)+ workspaces_provisioning: FakeWorkspaceProvisioning = field(default_factory=FakeWorkspaceProvisioning)+ email_codes: FakeEmailCodes = field(default_factory=FakeEmailCodes)+ reset_emails: FakeResetPasswordEmails = field(default_factory=FakeResetPasswordEmails)+ audit: FakeAudit = field(default_factory=FakeAudit)++ def service(+ self,+ *,+ turnstile_enabled: bool = False,+ turnstile_verify_required: bool = False,+ ) -> ConsoleAuthenticationService:+ return ConsoleAuthenticationService(+ accounts=self.accounts,+ workspaces=self.workspaces,+ invitations=self.invitations,+ policies=self.policies,+ security=self.security,+ passwords=self.passwords,+ human_verification=self.human,+ sessions=self.sessions,+ refresh_preparation=self.refresh_preparation,+ account_provisioning=self.accounts_provisioning,+ workspace_provisioning=self.workspaces_provisioning,+ email_codes=self.email_codes,+ reset_password_emails=self.reset_emails,+ audit=self.audit,+ now=lambda: LOGIN_TIME,+ turnstile_enabled=turnstile_enabled,+ turnstile_verify_required=turnstile_verify_required,+ )+++def _account(+ *,+ account_id: str = "account-1",+ password: bool = True,+ password_hash: str = "hash",+ status: str = "active",+ email: str = "[email protected]",+) -> LoginAccountSnapshot:+ return LoginAccountSnapshot(+ id=account_id,+ email=email,+ status=status,+ password_hash=password_hash if password else None,+ password_salt="salt" if password else None,+ )+++def _password_command(**changes: str | None) -> PasswordLoginCommand:+ values = {+ "email": "[email protected]",+ "password": "password",+ "invite_token": None,+ "ip_address": "127.0.0.1",+ }+ values.update(changes)+ return PasswordLoginCommand(**values) # type: ignore[arg-type]+++def _email_code_command(**changes: str | None) -> EmailCodeLoginCommand:+ values = {+ "email": "[email protected]",+ "code": "123456",+ "token": "challenge-token",+ "turnstile_token": None,+ "language": "zh-Hans",+ "timezone": "Asia/Singapore",+ "ip_address": "127.0.0.1",+ }+ values.update(changes)+ return EmailCodeLoginCommand(**values) # type: ignore[arg-type]+++def test_password_login_issues_session_and_resets_failures() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account()]+ dependencies.workspaces.active = True++ result = dependencies.service().login_with_password(_password_command())++ assert result.token_pair == TOKEN_PAIR+ assert dependencies.accounts.lookup_email == "[email protected]"+ assert dependencies.accounts.completions == [+ PasswordLoginCompletion(+ account_id="account-1",+ password=None,+ activate_pending_account=False,+ initialized_at=None,+ )+ ]+ assert dependencies.accounts.session_preparations == [+ (+ "account-1",+ AccountSessionPreparation(+ logged_in_at=LOGIN_TIME,+ ip_address="127.0.0.1",+ activate_pending_account=False,+ ),+ )+ ]+ assert dependencies.sessions.issued == ["account-1"]+ assert dependencies.security.resets == ["[email protected]"]+++def test_password_login_rejects_account_removed_during_session_preparation() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account()]+ dependencies.accounts.session_prepared = False+ dependencies.workspaces.active = True++ with pytest.raises(account_errors.AccountNotFoundError):+ dependencies.service().login_with_password(_password_command())++ assert dependencies.sessions.issued == []+ assert dependencies.security.resets == []+++def test_invitation_login_sets_missing_password() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account(password=False, status="pending")]+ dependencies.invitations.invitation = LoginInvitation(email="[email protected]")+ dependencies.workspaces.active = True++ dependencies.service().login_with_password(_password_command(password="password123", invite_token="invite"))++ assert dependencies.accounts.completions == [+ PasswordLoginCompletion(+ account_id="account-1",+ password=AccountPasswordDigest(password_hash="hashed:password123", password_salt="salt"),+ activate_pending_account=True,+ initialized_at=LOGIN_TIME,+ )+ ]+++def test_invitation_login_rejects_empty_password_without_completing_account() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account(password=False, status="pending")]+ dependencies.invitations.invitation = LoginInvitation(email="[email protected]")++ with pytest.raises(account_errors.InvalidLoginCredentialsError):+ dependencies.service().login_with_password(_password_command(password="", invite_token="invite"))++ assert dependencies.passwords.hashed_passwords == []+ assert dependencies.accounts.completions == []+ assert dependencies.security.failures == ["[email protected]"]+++def test_invitation_login_does_not_initialize_password_when_token_is_unknown() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account(password=False, status="pending")]++ with pytest.raises(account_errors.InvalidLoginCredentialsError):+ dependencies.service().login_with_password(_password_command(invite_token="unknown-invite"))++ assert dependencies.passwords.hashed_passwords == []+ assert dependencies.accounts.completions == []+++def test_invitation_login_applies_new_password_policy_before_completion() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account(password=False, status="pending")]+ dependencies.invitations.invitation = LoginInvitation(email="[email protected]")+ dependencies.passwords.hash_error = account_errors.InvalidAccountPasswordError(+ "Password must contain letters and numbers"+ )++ with pytest.raises(account_errors.InvalidAccountPasswordError, match="letters and numbers"):+ dependencies.service().login_with_password(_password_command(password="letters-only", invite_token="invite"))++ assert dependencies.passwords.hashed_passwords == ["letters-only"]+ assert dependencies.accounts.completions == []+++def test_invalid_password_records_rate_limit_and_audit() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account()]+ dependencies.passwords.valid = False++ with pytest.raises(account_errors.InvalidLoginCredentialsError):+ dependencies.service().login_with_password(_password_command())++ assert dependencies.security.failures == ["[email protected]"]+ assert dependencies.audit.failures == [("[email protected]", LoginFailureReason.INVALID_CREDENTIALS, "127.0.0.1")]+++def test_password_login_rejects_locked_account_before_loading_candidates() -> None:+ dependencies = Dependencies()+ dependencies.security.login_limited = True++ with pytest.raises(account_errors.LoginRateLimitError):+ dependencies.service().login_with_password(_password_command())++ assert dependencies.accounts.lookup_email is None+ assert dependencies.audit.failures == [("[email protected]", LoginFailureReason.LOGIN_RATE_LIMITED, "127.0.0.1")]+++ ("freeze_type", "error_type"),+ [+ ("freeze", account_errors.AccountEmailFrozenError),+ ("email_domain_suspended", account_errors.AccountEmailDomainSuspendedError),+ ],+)+def test_password_login_enforces_email_freeze_policy(+ freeze_type: str,+ error_type: type[account_errors.AccountApplicationError],+) -> None:+ dependencies = Dependencies()+ dependencies.policies.freeze_type = freeze_type++ with pytest.raises(error_type):+ dependencies.service().login_with_password(_password_command())++ assert dependencies.accounts.lookup_email is None+ assert dependencies.audit.failures == [("[email protected]", LoginFailureReason.ACCOUNT_IN_FREEZE, "127.0.0.1")]+++def test_password_login_rejects_banned_account() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account(status="banned")]++ with pytest.raises(account_errors.LoginAccountBannedError):+ dependencies.service().login_with_password(_password_command())++ assert dependencies.accounts.completions == []+ assert dependencies.audit.failures == [("[email protected]", LoginFailureReason.ACCOUNT_BANNED, "127.0.0.1")]+++def test_password_login_rejects_invitation_for_another_email() -> None:+ dependencies = Dependencies()+ dependencies.invitations.invitation = LoginInvitation(email="[email protected]")++ with pytest.raises(account_errors.InvalidLoginInvitationEmailError):+ dependencies.service().login_with_password(_password_command(invite_token="invite"))++ assert dependencies.accounts.lookup_email is None+ assert dependencies.audit.failures == [+ ("[email protected]", LoginFailureReason.INVALID_INVITATION_EMAIL, "127.0.0.1")+ ]+++def test_password_login_tries_lowercase_candidate_after_exact_candidate_password_fails() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [+ _account(account_id="mixed-case", email="[email protected]", password_hash="mixed-hash"),+ _account(account_id="lowercase", email="[email protected]", password_hash="lower-hash"),+ ]+ dependencies.passwords.valid_password_hashes = {"lower-hash"}+ dependencies.workspaces.active = True++ result = dependencies.service().login_with_password(_password_command(email="[email protected]"))++ assert result.token_pair == TOKEN_PAIR+ assert [completion.account_id for completion in dependencies.accounts.completions] == ["lowercase"]+ assert dependencies.sessions.issued == ["lowercase"]+ assert dependencies.security.failures == []+++def test_password_login_returns_no_workspace_without_creating_one() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account()]++ result = dependencies.service().login_with_password(_password_command())++ assert not result.workspace_found+ assert result.token_pair is None+ assert dependencies.workspaces_provisioning.account_ids == []+++def test_password_login_enforces_workspace_capacity() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account()]+ dependencies.policies.workspace_capacity = False++ with pytest.raises(account_errors.LoginWorkspaceLimitError):+ dependencies.service().login_with_password(_password_command())+++def test_send_email_code_normalizes_identity_and_preserves_account_recipient_address() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account(email="[email protected]")]++ token = dependencies.service(turnstile_enabled=True).send_email_code(+ EmailCodeSendCommand(+ email="[email protected]",+ language="zh-Hans",+ turnstile_token="turnstile",+ ip_address="127.0.0.1",+ )+ )++ assert token == "email-token"+ assert dependencies.human.calls == [("turnstile", "127.0.0.1", "signin_code")]+ assert dependencies.email_codes.sent == [("account-1", "[email protected]", "[email protected]", "zh-Hans")]+++def test_send_email_code_rejects_unknown_account_when_registration_is_disabled() -> None:+ dependencies = Dependencies()+ dependencies.policies.registration_allowed = False++ with pytest.raises(account_errors.AccountNotFoundError):+ dependencies.service().send_email_code(+ EmailCodeSendCommand(+ email="[email protected]",+ language=None,+ turnstile_token=None,+ ip_address="127.0.0.1",+ )+ )+++def test_send_email_code_rejects_ip_rate_limit_before_human_verification() -> None:+ dependencies = Dependencies()+ dependencies.security.ip_limited = True++ with pytest.raises(account_errors.EmailCodeSendIPLimitedError):+ dependencies.service(turnstile_enabled=True).send_email_code(+ EmailCodeSendCommand(+ email="[email protected]",+ language=None,+ turnstile_token="turnstile",+ ip_address="127.0.0.1",+ )+ )++ assert dependencies.human.calls == []+ assert dependencies.email_codes.sent == []+++def test_send_email_code_skips_turnstile_when_disabled() -> None:+ dependencies = Dependencies()++ dependencies.service(turnstile_enabled=False).send_email_code(+ EmailCodeSendCommand(+ email="[email protected]",+ language=None,+ turnstile_token="ignored-token",+ ip_address="127.0.0.1",+ )+ )++ assert dependencies.human.calls == []++[email protected]("code", ["12345", "1234567", "abcdef", "١٢٣٤٥٦"])+def test_email_code_login_rejects_malformed_codes(code: str) -> None:+ dependencies = Dependencies()++ with pytest.raises(account_errors.InvalidEmailCodeError):+ dependencies.service().login_with_email_code(_email_code_command(code=code))++ assert dependencies.audit.failures[0][1] == LoginFailureReason.INVALID_EMAIL_CODE+++ ("status", "error_type", "reason"),+ [+ (+ EmailCodeChallengeStatus.INVALID_TOKEN,+ account_errors.InvalidEmailCodeTokenError,+ LoginFailureReason.INVALID_EMAIL_CODE_TOKEN,+ ),+ (+ EmailCodeChallengeStatus.EMAIL_MISMATCH,+ account_errors.EmailCodeEmailMismatchError,+ LoginFailureReason.EMAIL_CODE_EMAIL_MISMATCH,+ ),+ (+ EmailCodeChallengeStatus.INVALID_CODE,+ account_errors.InvalidEmailCodeError,+ LoginFailureReason.INVALID_EMAIL_CODE,+ ),+ (+ EmailCodeChallengeStatus.EXHAUSTED,+ account_errors.InvalidEmailCodeError,+ LoginFailureReason.INVALID_EMAIL_CODE,+ ),+ ],+)+def test_email_code_login_maps_challenge_status(+ status: EmailCodeChallengeStatus,+ error_type: type[account_errors.AccountApplicationError],+ reason: LoginFailureReason,+) -> None:+ dependencies = Dependencies()+ dependencies.email_codes.status = status++ with pytest.raises(error_type):+ dependencies.service().login_with_email_code(_email_code_command())++ assert dependencies.audit.failures == [("[email protected]", reason, "127.0.0.1")]+++ ("turnstile_enabled", "verify_required", "turnstile_token", "expected_calls"),+ [+ (False, True, "provided-token", []),+ (True, False, None, []),+ (True, False, "provided-token", [("provided-token", "127.0.0.1", "signin_code_verify")]),+ (True, True, None, [(None, "127.0.0.1", "signin_code_verify")]),+ ],+)+def test_email_code_login_applies_turnstile_switches(+ turnstile_enabled: bool,+ verify_required: bool,+ turnstile_token: str | None,+ expected_calls: list[tuple[str | None, str, str]],+) -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account()]+ dependencies.workspaces.active = True++ dependencies.service(+ turnstile_enabled=turnstile_enabled,+ turnstile_verify_required=verify_required,+ ).login_with_email_code(_email_code_command(turnstile_token=turnstile_token))++ assert dependencies.human.calls == expected_calls+++def test_email_code_login_rejects_banned_account() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account(status="banned")]++ with pytest.raises(account_errors.LoginAccountBannedError):+ dependencies.service().login_with_email_code(_email_code_command())++ assert dependencies.audit.failures == [("[email protected]", LoginFailureReason.ACCOUNT_BANNED, "127.0.0.1")]+++ ("workspace_capacity", "workspace_creation_allowed", "error_type"),+ [+ (False, True, account_errors.LoginWorkspaceLimitError),+ (True, False, account_errors.LoginWorkspaceCreationNotAllowedError),+ ],+)+def test_email_code_login_enforces_workspace_policy(+ workspace_capacity: bool,+ workspace_creation_allowed: bool,+ error_type: type[account_errors.AccountApplicationError],+) -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account()]+ dependencies.policies.workspace_capacity = workspace_capacity+ dependencies.policies.workspace_creation_allowed = workspace_creation_allowed++ with pytest.raises(error_type):+ dependencies.service().login_with_email_code(_email_code_command())++ assert dependencies.workspaces_provisioning.account_ids == []+ assert dependencies.sessions.issued == []+++def test_email_code_login_rejects_registration_when_account_is_missing() -> None:+ dependencies = Dependencies()+ dependencies.policies.registration_allowed = False++ with pytest.raises(account_errors.AccountNotFoundError):+ dependencies.service().login_with_email_code(_email_code_command())++ assert dependencies.accounts_provisioning.calls == []+ assert dependencies.sessions.issued == []+++ ("account_capacity", "workspace_creation_allowed", "workspace_capacity", "error_type"),+ [+ (False, True, True, account_errors.LoginSeatLimitError),+ (True, False, True, account_errors.LoginWorkspaceCreationNotAllowedError),+ (True, True, False, account_errors.LoginWorkspaceLimitError),+ ],+)+def test_email_code_login_enforces_new_account_provisioning_policy(+ account_capacity: bool,+ workspace_creation_allowed: bool,+ workspace_capacity: bool,+ error_type: type[account_errors.AccountApplicationError],+) -> None:+ dependencies = Dependencies()+ dependencies.policies.account_capacity = account_capacity+ dependencies.policies.workspace_creation_allowed = workspace_creation_allowed+ dependencies.policies.workspace_capacity = workspace_capacity++ with pytest.raises(error_type):+ dependencies.service().login_with_email_code(_email_code_command())++ assert dependencies.accounts_provisioning.calls == []+ assert dependencies.sessions.issued == []+++def test_email_code_login_creates_workspace_for_existing_account() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account()]++ result = dependencies.service().login_with_email_code(_email_code_command())++ assert result == TOKEN_PAIR+ assert dependencies.workspaces_provisioning.account_ids == ["account-1"]+++def test_email_code_login_provisions_new_account() -> None:+ dependencies = Dependencies()++ result = dependencies.service().login_with_email_code(_email_code_command())++ assert result == TOKEN_PAIR+ assert dependencies.accounts_provisioning.calls == [+ {+ "email": "[email protected]",+ "name": "[email protected]",+ "interface_language": "zh-Hans",+ "timezone": "Asia/Singapore",+ "ip_address": "127.0.0.1",+ }+ ]+ assert dependencies.sessions.issued == ["new-account"]+++def test_reset_password_email_uses_shared_account_snapshot() -> None:+ dependencies = Dependencies()+ dependencies.accounts.candidates = [_account()]++ token = dependencies.service().send_reset_password_email(+ email="[email protected]",+ language="fr-FR",+ ip_address="127.0.0.1",+ )++ assert token == "reset-token"+ assert dependencies.reset_emails.sent == [("account-1", "[email protected]", "en-US", True)]+++def test_logout_and_refresh_delegate_to_session_gateway() -> None:+ dependencies = Dependencies()+ service = dependencies.service()++ service.logout("account-1")++ assert dependencies.sessions.revoked == ["account-1"]+ assert service.refresh("old-refresh") == TOKEN_PAIR+ assert dependencies.refresh_preparation.account_ids == ["account-1"]+ assert dependencies.sessions.rotations == [("old-refresh", "account-1")]+++ ("refresh_account_id", "refresh_status", "message"),+ [+ (None, RefreshAccountStatus.READY, "Invalid refresh token"),+ ("account-1", RefreshAccountStatus.NOT_FOUND, "Invalid account"),+ ("account-1", RefreshAccountStatus.BANNED, "Account is banned"),+ ],+)+def test_refresh_rejects_invalid_account_state(+ refresh_account_id: str | None,+ refresh_status: RefreshAccountStatus,+ message: str,+) -> None:+ dependencies = Dependencies()+ dependencies.sessions.refresh_account_id = refresh_account_id+ dependencies.refresh_preparation.status = refresh_status++ with pytest.raises(account_errors.InvalidRefreshTokenError, match=message):+ dependencies.service().refresh("old-refresh")++ assert dependencies.sessions.rotations == []diff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.pyindex 8614264708c..aad8e9d05c8 100644--- a/api/tests/unit_tests/services/test_account_service.py+++ b/api/tests/unit_tests/services/test_account_service.py@@ -31,8 +31,7 @@ from services.enterprise.rbac_service import MemberRolesResponse, MembersInRole,from services.errors.account import (AccountAlreadyInTenantError,AccountEmailAlreadyInUseError,- AccountLoginError,- AccountPasswordError,+ AccountNotFoundError,AccountRegisterError,EmailDomainSuspendedError,NoPermissionError,@@ -91,7 +90,6 @@ class TestAccountService:Comprehensive unit tests for AccountService methods.This test suite covers all account-related operations including:- - Authentication and login- Account creation and registration- Password management- JWT token generation@@ -103,12 +101,10 @@ class TestAccountService:def mock_password_dependencies(self) -> Iterator[_MockDependencies]:"""Mock setup for password-related functions."""with (- patch("services.account_service.compare_password") as mock_compare_password,patch("services.account_service.hash_password") as mock_hash_password,patch("services.account_service.valid_password") as mock_valid_password,):yield {- "compare_password": mock_compare_password,"hash_password": mock_hash_password,"valid_password": mock_valid_password,}@@ -127,113 +123,6 @@ class TestAccountService:"passport_service": mock_passport_service,}- # ==================== Authentication Tests ====================-- def test_authenticate_success(self, sqlite_session: Session, mock_password_dependencies: _MockDependencies) -> None:- """Test successful authentication with correct email and password."""- account = Account(- name="Test User",- email="[email protected]",- password="hashed_password",- password_salt="salt",- )- sqlite_session.add(account)- sqlite_session.commit()-- mock_password_dependencies["compare_password"].return_value = True-- result = AccountService.authenticate("[email protected]", "password", session=sqlite_session)-- assert result is account-- def test_authenticate_keeps_using_the_stored_email(- self,- sqlite_session: Session,- mock_password_dependencies: _MockDependencies,- ) -> None:- account = Account(- name="Gmail User",- email="[email protected]",- normalized_email="[email protected]",- password="hashed_password",- password_salt="salt",- )- sqlite_session.add(account)- sqlite_session.commit()-- mock_password_dependencies["compare_password"].return_value = True-- result = AccountService.authenticate("[email protected]", "password", session=sqlite_session)-- assert result is account-- def test_authenticate_account_not_found(self, sqlite_session: Session) -> None:- """Test authentication when account does not exist."""- with pytest.raises(AccountPasswordError):- AccountService.authenticate("[email protected]", "password", session=sqlite_session)-- def test_authenticate_account_banned(self, sqlite_session: Session) -> None:- """Test authentication when account is banned."""- account = Account(- name="Banned User",- email="[email protected]",- password="hashed_password",- password_salt="salt",- status=AccountStatus.BANNED,- )- sqlite_session.add(account)- sqlite_session.commit()-- with pytest.raises(AccountLoginError):- AccountService.authenticate("[email protected]", "password", session=sqlite_session)-- def test_authenticate_password_error(- self, sqlite_session: Session, mock_password_dependencies: _MockDependencies- ) -> None:- """Test authentication with wrong password."""- account = Account(- name="Test User",- email="[email protected]",- password="hashed_password",- password_salt="salt",- )- sqlite_session.add(account)- sqlite_session.commit()-- mock_password_dependencies["compare_password"].return_value = False-- with pytest.raises(AccountPasswordError):- AccountService.authenticate("[email protected]", "wrongpassword", session=sqlite_session)-- def test_authenticate_pending_account_activates(- self,- sqlite_session_factory: sessionmaker[Session],- mock_password_dependencies: _MockDependencies,- ) -> None:- """Test authentication for a pending account, which should activate on login."""- with sqlite_session_factory() as service_session:- account = Account(- name="Pending User",- email="[email protected]",- password="hashed_password",- password_salt="salt",- status=AccountStatus.PENDING,- )- service_session.add(account)- service_session.commit()- account_id = account.id-- mock_password_dependencies["compare_password"].return_value = True-- result = AccountService.authenticate("[email protected]", "password", session=service_session)- assert result.id == account_id-- with sqlite_session_factory() as assertion_session:- persisted_account = assertion_session.get(Account, account_id)- assert persisted_account is not None- assert persisted_account.status == AccountStatus.ACTIVE- assert persisted_account.initialized_at is not None-# ==================== Account Creation Tests ====================def test_create_account_success(@@ -350,13 +239,11 @@ class TestAccountService:self, unbound_session: Session, mock_external_service_dependencies: _MockDependencies) -> None:"""Test account creation when registration is disabled."""- from controllers.console.error import AccountNotFound-# Setup mocksmock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = False# Execute test and verify exception- with pytest.raises(AccountNotFound):+ with pytest.raises(AccountNotFoundError, match="Account registration is disabled"):AccountService.create_account(email="[email protected]",name="Test User",@@ -401,32 +288,6 @@ class TestAccountService:session=unbound_session,)- def test_get_user_through_email_rejects_suspended_email_domain(- self, unbound_session: Session, mock_external_service_dependencies: _MockDependencies- ) -> None:- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = True- mock_external_service_dependencies[- "billing_service"- ].get_email_freeze_type.return_value = "email_domain_suspended"-- with config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD):- with pytest.raises(EmailDomainSuspendedError):- AccountService.get_user_through_email("[email protected]", session=unbound_session)-- def test_get_account_freeze_type_is_enabled_only_for_cloud(- self, mock_external_service_dependencies: _MockDependencies- ) -> None:- mock_external_service_dependencies["billing_service"].get_email_freeze_type.return_value = "freeze"-- with config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD):- assert AccountService.get_account_freeze_type("[email protected]") == "freeze"- with config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY):- assert AccountService.get_account_freeze_type("[email protected]") is None-- mock_external_service_dependencies["billing_service"].get_email_freeze_type.assert_called_once_with(- )-def test_create_account_without_password(self,sqlite_session_factory: sessionmaker[Session],